Compare commits

..
18 Commits
Author SHA1 Message Date
waozi dba7d4efc2 Align Terminal’s locked toolchain and Kryon for Rill 2026-11-22 16:40:02 -03:00
waozi 7202eb01e1 Fix Terminal release runner prerequisites and private tests 2026-11-22 15:23:20 -03:00
waozi a2b7066ccd Split Terminal docs by topic and consolidate open work
README.md keeps usage, install, launch options, config and shortcuts; the package embedding guide moves to docs/EMBEDDING.md and the parser/graphics coverage list to docs/COMPATIBILITY.md. The finished 2026-11-12 clipboard/context-menu plan and the remaining-feature plan consolidate into plans/open-work.md; the unclear owner-question placeholder in the old plan is dropped. AGENTS.md is rewritten with layout, commands, pins and the docs index; the stale Bend section is dropped because no Bend sources remain, and the Ziran migration is recorded as finished.
2026-11-22 14:22:19 -03:00
waozi 84dd093363 Limit Terminal context-menu OCR to one thread 2026-11-22 13:10:21 -03:00
waozi e9dc785287 Wait for the rendered Terminal link menu in the Xvfb test 2026-11-22 06:33:55 -03:00
waozi 1df754a05d Preflight Terminal release dependencies and reuse the locked SDK 2026-11-22 06:28:08 -03:00
waozi fcbe13b21e Run Terminal release setup on the native Build host 2026-11-22 05:57:15 -03:00
waozi 4f061a822c Release Terminal 0.1.1 with Linux and ZX packages 2026-11-22 05:28:52 -03:00
waozi ee95373c92 Lock the public Terminal ZX provider 2026-11-21 20:58:06 -03:00
waozi ff62895443 Test physical Enter through the desktop terminal 2026-11-21 13:41:29 -03:00
waozi 038ec85450 Pin canonical Kryon with style size transport 2026-11-21 03:44:27 -03:00
waozi 13ba443df5 Use the aligned published Kryon and Ziran dependencies for generic text drawing
Resolve the validated upstream image/cache, asset digest and ARM fixes without local overrides.
2026-11-18 19:11:10 -03:00
waozi 1a32d33dca Keep rapidly typed lines apart and pin Kryon 0.6.0
Kryon's desktop input take hands over Enter together with the text typed
before it, which Enter commits, but the pane wrote Enter ahead of the
frame's text: two lines typed within a frame reached the shell as one.
With Enter queued, the frame's text now goes first; every other key keeps
its place before the text. A test types two lines through a Kryon session
and the pane and expects ls, Enter, pwd, Enter.

Pins Kryon 0.6.0 with Ziran 0.7.0. The startup label calls text's session
form directly: the generic Draw's specialization is emitted after its first
use without a declaration, which GCC refuses.
2026-11-18 15:04:26 -03:00
waozi dc6b575408 Run Terminal on Kryon's desktop host instead of raylib
The window, PTY-aware activity waits, frame pacing, fullscreen, monitor
placement, dropped files and typefaces now come from Kryon's
desktop_runtime, desktop_window_state, desktop_keyboard, desktop_activity
and cairo_typefaces, so the build has no CMake raylib step. Pins Kryon
b5a61b37 with Ziran 7fbc8152.

The desktop host reports button edges and wheel steps per poll, and the
loop polls several times per frame while it waits on the shells, so the
window keeps them, with the press position, until the frame reads them. A
Ctrl shortcut a key press triggered stays delivered while the key is held,
so Ctrl+V never also types its control byte. Text dialogs opt into
closing on an outside click under Kryon's modals. The tests' paint host
answers the new cursor-picture call, and the context-menu OCR reads a
400% capture.
2026-11-18 03:19:21 -03:00
waozi 2d33dbca77 Clear terminal selection after right-click copy 2026-11-17 01:42:23 -03:00
waozi 8b4e47d858 Start Thunar terminals in the selected folder and copy selections on right-click
Thunar's Open Terminal Here custom action passed --working-directory="%f".
Thunar already shell-quotes %f, so Terminal received the path with literal
quotes, the shell could not enter it and exited, and the window closed about
a second after opening. Terminal now starts the shell in HOME when the
working directory is missing, a file, or cannot be entered, and says why on
the terminal and on standard error instead of closing.

Right-click on selected text copies it to CLIPBOARD and keeps the selection
and PRIMARY. With nothing selected, after a plain click, or with Shift held,
right-click opens the context menu.

The Thunar regression runs real Thunar on a private Xvfb with a private bus
and checks the custom action, the Exo TerminalEmulator helper, the quoted
form, a folder outside HOME with spaces, and missing, file and locked paths.
2026-11-15 12:04:37 -03:00
waozi e7e6c53c29 Use PRIMARY, open links through Kryon and match the xfce4-terminal menu
Selections publish the system PRIMARY selection; middle-click, Shift+Insert
and Paste Selection read it, and never fall back to CLIPBOARD. Ctrl+V pastes
a clipboard PNG as a private file path and falls back to text, while
Ctrl+Shift+V and Paste stay text-only. Copy as HTML offers plain text and
escaped HTML through Kryon's MIME clipboard, and Kryon's image clipboard
replaces the local GTK reader.

Alt-click and Ctrl-click open web links, OSC 8 hyperlinks and e-mail
addresses through kryon/open_uri in standalone and embedded windows, with a
pointer cursor over links.

The right-click menu matches xfce4-terminal 1.1.4: link and e-mail actions,
Open Tab/Terminal/File Manager Here, Copy, Copy as HTML, Paste, Paste
Selection, Show Menubar/Fullscreen/Read-Only check rows, Send Signal and Zoom
submenus, Save Contents and Preferences. Right-click keeps the selection and
copies nothing until a copy action is chosen.

make install also installs the Xfce TerminalEmulator helper. Terminal starts
in HOME unless told otherwise, so the helper passes --working-directory=. for
the folder Exo starts it in, and runs launch commands with -x because Exo
splits them into words. Thunar's Open Terminal Here and exo-open now open the
selected folder.

Terminal builds against Kryon's package-qualified widget imports now that the
Widgets facade and *_props modules are gone, and the lock moves to the Kryon
commit with the PRIMARY API and to the matching Ziran toolchain. CI installs
the GTK, X11 and xcb development files, ImageMagick, tesseract and exo-utils
the build and the new window tests need.

The application context-menu test follows the new menu by label. The link
test focuses the window and Shift+right-clicks while the child tracks the
mouse; the selection test uses a window tall enough to reach Copy and gives
each menu copy a fresh CLIPBOARD owner; the rendered-menu test reads 2x
captures and waits for the submenu; the Thunar test launches the real
Terminal through Exo.
2026-11-14 10:58:31 -03:00
waozi f9b9223ca6 Keep captured terminal row colors scoped 2026-11-14 10:58:31 -03:00
90 changed files with 3905 additions and 929 deletions

No files matched your search

+198
View File
@@ -0,0 +1,198 @@
name: Terminal Linux release
on:
workflow_dispatch:
inputs:
version:
description: Numeric version already recorded in CHANGELOG.md and VERSION
type: string
required: true
permissions:
contents: write
concurrency:
group: terminal-linux-release
cancel-in-progress: false
jobs:
release:
if: github.ref == 'refs/heads/master'
runs-on: build-ubuntu24.04
timeout-minutes: 90
env:
RELEASE_VERSION: ${{ inputs.version }}
HARMONY_DESKTOP_RECOVERY: '0'
YUE_DESKTOP_RECOVERY: '0'
ZIRAN_PAR_THREADS: '1'
defaults:
run:
working-directory: kryonlabs/terminal
steps:
- uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955
with:
path: kryonlabs/terminal
persist-credentials: false
- name: Verify the release version and revision
run: |
set -eu
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
test ! -e ziran.local.toml
printf '%s\n' "$RELEASE_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'
./update_version.sh
test "$(cat VERSION)" = "$RELEASE_VERSION"
git diff --exit-code -- VERSION
- name: Verify native Build prerequisites
run: |
set -euo pipefail
test "$(uname -s):$(uname -m)" = Linux:x86_64
. /etc/os-release
printf 'Build host: %s (%s)\n' "$PRETTY_NAME" "$(uname -m)"
for tool in cc cmake curl dbus-run-session desktop-file-validate diff dpkg-deb dpkg-shlibdeps exo-open file git go import jq make pkg-config python3 rg sha256sum tesseract thunar timeout tmux xauth xclip xdotool xfce4-mime-helper xset xwininfo xvfb-run; do
if ! command -v "$tool" >/dev/null; then
printf 'Missing native Build prerequisite: %s\n' "$tool" >&2
exit 1
fi
done
pkg-config --print-errors --exists sdl2 cairo pangocairo fontconfig freetype2 glib-2.0 libwebpdemux libwebp gtk+-3.0 x11 xcb
tesseract --list-langs | grep -Fx eng >/dev/null
df -h . "$RUNNER_TEMP"
# Allow room for a cold SDK, locked sources and native test outputs.
for directory in . "$RUNNER_TEMP"; do
available=$(df -Pk "$directory" | awk 'NR == 2 { print $4 }')
if [ "$available" -lt 2097152 ]; then
printf 'Terminal requires at least 2 GiB free in %s for a cold build.\n' "$directory" >&2
exit 1
fi
done
{
printf 'ImageOS=%s-%s-cc%s\n' "$ID" "$VERSION_ID" "$(cc -dumpfullversion -dumpversion)"
printf 'XDG_CACHE_HOME=%s/terminal-cache\n' "$RUNNER_TEMP"
} >> "$GITHUB_ENV"
- name: Verify public locked revisions on Gitea
run: |
set -euo pipefail
# Use the same public routes for the preflight and the package fetch.
export GIT_CONFIG_GLOBAL="$RUNNER_TEMP/terminal-gitconfig"
export GIT_CONFIG_NOSYSTEM=1 GIT_TERMINAL_PROMPT=0
while read -r upstream mirror; do
git config --global url."$mirror".insteadOf "$upstream"
done <<'MIRRORS'
https://github.com/ziranlang/ https://git.waozi.xyz/ziranlang/
https://github.com/kryonlabs/ https://git.waozi.xyz/kryonlabs/
https://github.com/AOMediaCodec/libavif.git https://git.waozi.xyz/vendor/aomediacodec-libavif.git
https://github.com/libsndfile/libsamplerate.git https://git.waozi.xyz/vendor/libsndfile-libsamplerate.git
https://github.com/libsdl-org/SDL.git https://git.waozi.xyz/vendor/libsdl-org-sdl.git
https://github.com/videolan/dav1d.git https://git.waozi.xyz/vendor/videolan-dav1d.git
https://github.com/webmproject/libwebp.git https://git.waozi.xyz/vendor/webmproject-libwebp.git
https://github.com/xiph/opus.git https://git.waozi.xyz/vendor/xiph-opus.git
https://aomedia.googlesource.com/aom https://git.waozi.xyz/vendor/aomedia-aom.git
MIRRORS
locked=$(jq -er '(.toolchain, .packages[]) | [.url, .commit] | @tsv' ziran.lock)
while IFS=$'\t' read -r url commit; do
remote=$(git ls-remote --get-url "$url")
if [[ ! "$remote" =~ ^https://git\.waozi\.xyz/[A-Za-z0-9_-]+/[A-Za-z0-9_.-]+\.git$ || ! "$commit" =~ ^[0-9a-f]{40}$ ]]; then
printf 'No canonical public route for locked source %s at %s\n' "$url" "$commit" >&2
exit 1
fi
repository=${remote#https://git.waozi.xyz/}
endpoint="https://git.waozi.xyz/api/v1/repos/${repository%.git}/git/commits/$commit"
# Thin vendor mirrors can advertise the exact commit over Git
# even when the REST commit endpoint cannot describe their tree.
refs=$(timeout 12s git -c credential.helper= ls-remote "$remote")
if ! awk -v commit="$commit" '$1 == commit { found = 1 } END { exit !found }' <<< "$refs" &&
! curl -qfsS --connect-timeout 5 --max-time 12 "$endpoint" | jq -e --arg commit "$commit" '.sha == $commit' >/dev/null; then
printf 'Public locked revision is unavailable: %s at %s\n' "$repository" "$commit" >&2
exit 1
fi
printf 'Public lock verified: %s %s\n' "$repository" "$commit"
done <<< "$locked"
{
printf 'GIT_CONFIG_GLOBAL=%s\n' "$GIT_CONFIG_GLOBAL"
printf 'GIT_CONFIG_NOSYSTEM=1\nGIT_TERMINAL_PROMPT=0\n'
} >> "$GITHUB_ENV"
- name: Set up the locked compiler and packages
id: ziran
uses: https://git.waozi.xyz/ziranlang/ziran/.github/actions/setup@62d90ff97d10373f44f428bfff538f75185512e5
env:
# The setup action builds the lock's compiler before fetching sources.
ZIRAN_PINNED_LAUNCHER: '1'
with:
project: kryonlabs/terminal
path: ziranlang/ziran
fetch: true
jobs: 1
- name: Reuse the exact SDK in the locked package cache
env:
SDK_ROOT: ${{ steps.ziran.outputs.root }}
SDK_COMMIT: ${{ steps.ziran.outputs.commit }}
SDK_ORIGIN: ${{ steps.ziran.outputs.toolchain }}
SDK_COMPILED: ${{ steps.ziran.outputs.compiled }}
run: |
set -euo pipefail
test "$(jq -er .toolchain.commit ziran.lock)" = "$SDK_COMMIT"
test "$(git -C "$SDK_ROOT" rev-parse HEAD)" = "$SDK_COMMIT"
locked_root=$(ZIRAN_PINNED_LAUNCHER=1 "$SDK_ROOT/build/bin/ziran" pkg path ziran --offline --locked)
test "$(git -C "$locked_root" rev-parse HEAD)" = "$SDK_COMMIT"
if [ "$locked_root" != "$SDK_ROOT" ] &&
{ ! diff -qr --no-dereference "$SDK_ROOT/build/bin" "$locked_root/build/bin" >/dev/null 2>&1 ||
! cmp -s "$SDK_ROOT/build/libziran.a" "$locked_root/build/libziran.a"; }; then
install -d "$locked_root/build/bin"
cp -a --reflink=auto "$SDK_ROOT/build/bin/." "$locked_root/build/bin/"
install -m 0644 "$SDK_ROOT/build/libziran.a" "$locked_root/build/libziran.a"
printf 'Staged the exact SDK in the locked package checkout.\n'
fi
test -x "$locked_root/build/bin/ziran"
cmp "$SDK_ROOT/build/bin/ziran" "$locked_root/build/bin/ziran"
cmp "$SDK_ROOT/build/libziran.a" "$locked_root/build/libziran.a"
printf 'SDK %s from %s (%s C files compiled in setup); reused for the locked build\n' \
"$SDK_COMMIT" "$SDK_ORIGIN" "$SDK_COMPILED"
sha256sum ziran.lock "$locked_root/build/bin/ziran" "$locked_root/build/libziran.a"
- name: Build, test and package Terminal
env:
SHELL: /bin/sh
run: |
set -eu
unset DISPLAY WAYLAND_DISPLAY WAYLAND_SOCKET XAUTHORITY DBUS_SESSION_BUS_ADDRESS ICEAUTHORITY SESSION_MANAGER XDG_RUNTIME_DIR XDG_SESSION_ID
TERMINAL_PACKAGE_LOCKED=1 make -j1 all test zx-window-test pty-zx-test screen-zx-test
scripts/package-linux.sh "$RELEASE_VERSION" dist --with-zx
(cd dist && sha256sum -c SHA256SUMS)
test "$(dpkg-deb -f dist/terminal-linux-amd64.deb Version)" = "$RELEASE_VERSION"
- name: Publish the verified assets
env:
RELEASE_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
test -n "$RELEASE_TOKEN"
endpoint="$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/releases"
tag=v$RELEASE_VERSION
notes=$(awk -v heading="## [$RELEASE_VERSION] - " '
index($0, heading) == 1 { found=1; next }
found && /^## / { exit }
found { print }
' CHANGELOG.md)
test -n "$notes"
response=$(jq -cn --arg tag "$tag" --arg sha "$GITHUB_SHA" --arg body "$notes" \
'{tag_name:$tag, target_commitish:$sha, name:$tag, body:$body, draft:true}' |
curl --silent --show-error --fail-with-body \
--header "Authorization: token $RELEASE_TOKEN" --header 'Content-Type: application/json' \
--data-binary @- "$endpoint")
id=$(printf '%s' "$response" | jq -er --arg tag "$tag" '
select(.tag_name == $tag and .draft == true) | .id | select(type == "number")')
for asset in terminal-linux-amd64.deb terminal-linux-x86_64.AppImage Terminal.zx terminal-zx-linux-x86_64.tar.gz SHA256SUMS; do
expected_size=$(stat -c %s "dist/$asset")
curl --silent --show-error --fail-with-body --header "Authorization: token $RELEASE_TOKEN" \
--form "attachment=@dist/$asset" "$endpoint/$id/assets?name=$asset" |
jq -e --arg name "$asset" --argjson size "$expected_size" '.name == $name and .size == $size'
done
curl --silent --show-error --fail-with-body \
--header "Authorization: token $RELEASE_TOKEN" --header 'Content-Type: application/json' \
--request PATCH --data-binary '{"draft":false}' "$endpoint/$id" |
jq -e --arg tag "$tag" '.tag_name == $tag and .draft == false'
+15 -99
View File
@@ -18,7 +18,6 @@ permissions:
env:
TERMINAL_DIR: terminal
ZIRAN: ${{ github.workspace }}/ziran/build/bin/ziran
TERMINAL_BUILD_JOBS: 1
LP_NUM_THREADS: 1
OMP_NUM_THREADS: 1
@@ -43,7 +42,8 @@ jobs:
import os
with open("ziran.lock") as source:
toolchain = json.load(source)["toolchain"]
assert toolchain["url"] == "https://github.com/ziranlang/ziran.git"
assert toolchain["url"] in ("https://git.waozi.xyz/ziranlang/ziran.git",
"https://github.com/ziranlang/ziran.git")
commit = toolchain["commit"]
assert len(commit) == 40 and all(c in "0123456789abcdef" for c in commit)
with open(os.environ["GITHUB_OUTPUT"], "a") as output:
@@ -66,15 +66,24 @@ jobs:
cmake \
git \
curl \
dbus \
desktop-file-utils \
dpkg-dev \
exo-utils \
file \
fonts-dejavu-core \
libgl1-mesa-dev \
imagemagick \
libcairo2-dev \
libgtk-3-dev \
libpango1.0-dev \
libwebp-dev \
libsdl2-dev \
libx11-dev \
libxcb1-dev \
pkg-config \
ripgrep \
tesseract-ocr \
thunar \
xauth \
xdotool \
x11-apps \
@@ -96,103 +105,10 @@ jobs:
- name: Package Linux release assets
working-directory: ${{ env.TERMINAL_DIR }}
run: |
set -eu
umask 022
version="${GITHUB_REF_NAME:-${GITHUB_SHA}}"
version="$(printf '%s' "${version}" | tr '/ :' '---')"
deb_version="$(printf '%s' "${version}" | sed 's/^v//; s/[^A-Za-z0-9.+:~_-]/-/g')"
case "${deb_version}" in
[0-9]*) ;;
*) deb_version="0.0.0+${deb_version}" ;;
esac
# Version-free names keep /releases/latest/download/<name> stable.
deb_root="dist/deb/terminal"
mkdir -p "${deb_root}/DEBIAN" \
"${deb_root}/usr/bin" \
"${deb_root}/usr/share/applications" \
"${deb_root}/usr/share/doc/terminal" \
"${deb_root}/usr/share/icons/hicolor/scalable/apps"
chmod 755 "${deb_root}/DEBIAN"
cp build/linux-x86_64/bin/terminal "${deb_root}/usr/bin/terminal"
cp README.md "${deb_root}/usr/share/doc/terminal/README.md"
cp docs/site/favicon.svg \
"${deb_root}/usr/share/icons/hicolor/scalable/apps/terminal.svg"
cat > "${deb_root}/usr/share/applications/terminal.desktop" <<'EOF'
[Desktop Entry]
Type=Application
Name=Terminal
Comment=Kryon terminal emulator
Exec=terminal
Icon=terminal
Terminal=false
Categories=System;TerminalEmulator;
Keywords=shell;prompt;command;terminal;
EOF
# Depends comes from the binary's real libraries, GTK included.
mkdir -p dist/shlibdeps/debian
printf 'Source: terminal\n\nPackage: terminal\nArchitecture: any\n' \
> dist/shlibdeps/debian/control
depends="$(cd dist/shlibdeps && dpkg-shlibdeps -O \
"${GITHUB_WORKSPACE}/${TERMINAL_DIR}/${deb_root}/usr/bin/terminal" |
sed -n 's/^shlibs:Depends=//p')"
test -n "${depends}"
cat > "${deb_root}/DEBIAN/control" <<EOF
Package: terminal
Version: ${deb_version}
Section: x11
Priority: optional
Architecture: amd64
Maintainer: Waozi <[email protected]>
Depends: ${depends}
Recommends: fonts-dejavu-core
Description: Kryon terminal emulator
Terminal is a standalone terminal application using Kryon for windowing,
rendering, input, and platform integration.
EOF
chmod 644 "${deb_root}/DEBIAN/control"
dpkg-deb --build --root-owner-group "${deb_root}" \
"dist/terminal-linux-amd64.deb"
appdir="dist/AppDir"
mkdir -p "${appdir}/usr/bin" \
"${appdir}/usr/share/applications" \
"${appdir}/usr/share/icons/hicolor/scalable/apps"
cp build/linux-x86_64/bin/terminal "${appdir}/usr/bin/terminal"
cp docs/site/favicon.svg \
"${appdir}/usr/share/icons/hicolor/scalable/apps/terminal.svg"
cp "${deb_root}/usr/share/applications/terminal.desktop" \
"${appdir}/usr/share/applications/terminal.desktop"
# linuxdeploy bundles SDL2, WebP and their dependencies. GTK, GLib,
# Cairo, Pango and GL come from the host: a bundled GTK would not
# match the desktop's themes and modules.
linuxdeploy="${RUNNER_TEMP}/linuxdeploy-x86_64.AppImage"
curl -fsSL -o "${linuxdeploy}" \
https://github.com/linuxdeploy/linuxdeploy/releases/download/1-alpha-20251107-1/linuxdeploy-x86_64.AppImage
echo "c20cd71e3a4e3b80c3483cef793cda3f4e990aca14014d23c544ca3ce1270b4d ${linuxdeploy}" |
sha256sum -c -
chmod 755 "${linuxdeploy}"
root="${GITHUB_WORKSPACE}/${TERMINAL_DIR}"
(
cd dist
APPIMAGE_EXTRACT_AND_RUN=1 ARCH=x86_64 \
LINUXDEPLOY_OUTPUT_VERSION="${deb_version}" \
LDAI_OUTPUT=terminal-linux-x86_64.AppImage \
"${linuxdeploy}" --appdir "${root}/${appdir}" \
--executable "${root}/${appdir}/usr/bin/terminal" \
--desktop-file "${root}/${appdir}/usr/share/applications/terminal.desktop" \
--icon-file "${root}/${appdir}/usr/share/icons/hicolor/scalable/apps/terminal.svg" \
--exclude-library 'libgtk-3.so*' --exclude-library 'libgdk-3.so*' \
--exclude-library 'libgdk_pixbuf-2.0.so*' --exclude-library 'libglib-2.0.so*' \
--exclude-library 'libgobject-2.0.so*' --exclude-library 'libgio-2.0.so*' \
--exclude-library 'libgmodule-2.0.so*' --exclude-library 'libcairo*' \
--exclude-library 'libpango*' --exclude-library 'libatk*' \
--exclude-library 'libGL.so*' --exclude-library 'libGLX*' \
--output appimage
)
test -x dist/terminal-linux-x86_64.AppImage
sha256sum dist/terminal-linux-amd64.deb \
dist/terminal-linux-x86_64.AppImage > dist/SHA256SUMS
version="$(printf '%s' "${version}" | sed 's/^v//; s/[^A-Za-z0-9.+:~_-]/-/g')"
case "$version" in [0-9]*) ;; *) version="0.0.0+$version" ;; esac
scripts/package-linux.sh "$version" dist
- name: Upload workflow artifact
uses: actions/upload-artifact@v4
+51 -25
View File
@@ -1,28 +1,54 @@
# AGENTS.md — Terminal
# Terminal
Terminal is the Terminal application in the KryonLabs organization, built on Kryon.
Its canonical checkout is `kryonlabs/terminal`; Kapsule's history belongs here.
The Terminal application of the KryonLabs organization, built on Kryon. Its
canonical checkout is `kryonlabs/terminal`; Kapsule's history belongs here.
README.md documents usage, install and the launch options.
- Keep terminal emulator code in this repository.
- Do not add Terminal product code, parser behavior, terminal UI, or app state to
Kryon. Reusable Kryon changes belong in its canonical `kryonlabs/kryon`
repository, never a dependency copy.
- Add code to Kryon only when it is a small reusable primitive that more than
one project needs.
## Layout
| Path | Contents |
| --- | --- |
| `src/terminal.zi`, `src/engine/` | The terminal engine: parser, screen, capture, keyboard |
| `src/app/` | Application modules: config, sessions, launch options, state, input, menus |
| `src/terminal_pane/` | The `TerminalPane` widget hosts embed |
| `src/terminal_clipboard.zi`, `src/terminal_drop.zi`, `src/terminal_pty_linux.zi` | Clipboard, drag-and-drop and PTY transports |
| `tests/` | Focused suites and private-Xvfb window tests |
| `benchmarks/` | Benchmark harness; README.md explains the workloads |
| `docs/` | EMBEDDING.md, COMPATIBILITY.md, VIEWPORT.md, ZIRAN_MIGRATION.md |
| `plans/open-work.md` | Open items, one line each |
## Commands
```sh
scripts/ziran.sh ... # dependency wrapper; builds the toolchain once
make # build; generates native C from the .zi entrypoint
make run
make test # full suite, window tests on private Xvfb
make pane-ziran-test # focused Ziran suites without the application
make standalone-window-test
make package-test # consumer build with package-qualified imports
make install # PREFIX=~/.local by default
```
## Pins
- Ziran toolchain: `5db3d3c39425d5dfe4bfe4a84e6f6e2e5a810ad0`
- Kryon: `a66edf19807c221b6f6818e0a54d13c2ad855241`
## Rules
- Keep terminal emulator code here. Do not add Terminal product code, parser
behavior, terminal UI or app state to Kryon; reusable changes belong in
`kryonlabs/kryon`, and only small primitives more than one project needs.
- Use direct names for Terminal APIs and types: `Terminal`, `Cell`, `Session`,
`Palette`. Do not add artificial `Kry*` prefixes.
- Resolve dependencies with `scripts/ziran.sh`, `ziran.toml`, and `ziran.lock`.
Canonical local paths belong only in ignored `ziran.local.toml` overrides.
- Continue the Ziran migration in `docs/ZIRAN_MIGRATION.md`; retain one product
implementation per module. Focused pane tests work without legacy Kryon.
- Run display-affecting tests only on a private Xvfb display, with inherited
`DISPLAY` and `WAYLAND_DISPLAY` scrubbed and window operations scoped to
the tested process.
## Bend
When using Bend:
- run `bend guide` to learn it
- use `LAWS.bend` to keep important rules
- run `bend PROOF.bend` before committing
- parallelize the code whenever possible
`Palette`. No artificial `Kry*` prefixes.
- Resolve dependencies with `scripts/ziran.sh`, `ziran.toml` and `ziran.lock`;
canonical local paths belong only in ignored `ziran.local.toml` overrides.
- The Ziran migration is finished: `docs/ZIRAN_MIGRATION.md` maps the
maintained modules, and `tests/ziran_migration_test.sh` rejects restored
legacy files.
- Run display-affecting tests only on a private Xvfb display with inherited
`DISPLAY` and `WAYLAND_DISPLAY` scrubbed. Keep `make test` and `make all`
green from a clean checkout.
- Commit as Waozi <waozi@proton.me>; ordinary changes stay in CHANGELOG's
`Unreleased` section.
+47
View File
@@ -2,6 +2,53 @@
## [Unreleased]
## [0.1.1] - 2026-11-22
- Publish Linux DEB and AppImage packages alongside `Terminal.zx` and its
matching Linux ZX player. The player supplies the terminal screen and PTY
services used by the bundle.
- Send text typed before Enter to the shell ahead of the Enter that commits
it, as Kryon's desktop input hands them over together: lines typed faster
than a frame no longer merge.
- Pin Kryon 0.6.0 with Ziran 0.7.0.
- Run on Kryon's desktop host instead of raylib: the window, PTY-aware
activity waits, frame pacing, fullscreen, monitor placement, dropped files
and typefaces come from `desktop_runtime`, `desktop_window_state`,
`desktop_keyboard`, `desktop_activity` and `cairo_typefaces`. Builds need no
CMake raylib step. Pins Kryon b5a61b37 with Ziran 7fbc8152.
- Keep the Find and other text dialogs closing on an outside click under
Kryon's modals, which now stay open unless they opt in.
- Keep every button press, release and wheel step that arrives while the
terminal waits on its shells, at the cell where the press happened, so
quick clicks and drags select from the right place.
- A Ctrl shortcut that a key press triggered (such as Ctrl+V paste) no longer
also types its control byte while the key is still held.
- Keep captured terminal rows in their own colors when reflowing or resizing,
so a colored diff or status row cannot flood later blank rows.
- Consume Kryon's ordered per-session key and text delivery.
- Build against Kryon's package-qualified widget imports (`kryon/menu`,
`kryon/context_menu`, `kryon/tab_bar`, `kryon/text_field` and others) now that
the `Widgets` facade and `*_props` modules are gone.
- Use the platform PRIMARY selection for selected text, middle-click,
Shift+Insert, and Paste Selection. Ctrl+V prefers a clipboard PNG and falls
back to text, while Ctrl+Shift+V and the Paste menu action stay text-only.
- Match the xfce4-terminal 1.1.4 right-click menu, including link and email
actions, Copy as HTML, open/save actions, checked state, signals, zoom
accelerators, and preferences. Right-click on selected text copies it to the
clipboard and keeps the selection and PRIMARY; with nothing selected, or
with Shift held, right-click opens the menu.
- Alt-click also opens email addresses, and links open through Kryon in both
standalone and embedded Terminal windows.
- `make install` also installs the Xfce TerminalEmulator helper, so Thunar's
Open Terminal Here and `exo-open --launch TerminalEmulator` start this
terminal in the selected folder, and Exo launch commands run through `-x`.
- A working directory that is missing, a file, or cannot be entered no
longer closes the window as soon as it opens: the shell starts in the home
folder and Terminal says why (missing, not a folder, or not permitted), on
the terminal and on standard error. Thunar custom actions pass
`--working-directory=%f` without extra quotes, because Thunar quotes `%f`
itself.
## [0.1.0] - 2026-11-13
- Releases publish `terminal-linux-amd64.deb` and
+54 -10
View File
@@ -8,6 +8,7 @@ BUILD_DIR ?= $(BUILD_ROOT)/linux-$(shell uname -m)
PREFIX ?= $(HOME)/.local
BINDIR ?= $(PREFIX)/bin
APPDIR ?= $(PREFIX)/share/applications
HELPERDIR ?= $(PREFIX)/share/xfce4/helpers
INSTALL ?= install
APP := $(BUILD_DIR)/bin/terminal
SOURCES := $(wildcard src/*.zi src/app/*.zi src/engine/*.zi src/terminal_pane/*.zi)
@@ -30,7 +31,7 @@ run: $(APP)
standalone-window-test: $(APP)
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER \
LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24' \
HARMONY_DESKTOP_RECOVERY=0 LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24' \
env TERMINAL_PRIVATE_XVFB=1 python3 tests/standalone_window_test.py "$(APP)"
.PHONY: image-input-window-test
@@ -42,25 +43,36 @@ image-input-window-test: $(APP)
.PHONY: link-window-test
link-window-test: $(APP)
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER \
YUE_DESKTOP_RECOVERY=0 LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24' \
HARMONY_DESKTOP_RECOVERY=0 LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24' \
env TERMINAL_PRIVATE_XVFB=1 python3 tests/link_window_test.py "$(APP)"
.PHONY: selection-copy-window-test
selection-copy-window-test: $(APP)
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER \
YUE_DESKTOP_RECOVERY=0 LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24' \
HARMONY_DESKTOP_RECOVERY=0 LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24' \
env TERMINAL_PRIVATE_XVFB=1 python3 tests/selection_copy_window_test.py "$(APP)"
.PHONY: context-menu-window-test
context-menu-window-test: $(APP)
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER \
HARMONY_DESKTOP_RECOVERY=0 LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1280x900x24' \
env TERMINAL_PRIVATE_XVFB=1 python3 tests/context_menu_window_test.py "$(APP)"
.PHONY: thunar-terminal-test
thunar-terminal-test: $(APP)
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER \
HARMONY_DESKTOP_RECOVERY=0 LP_NUM_THREADS=1 OMP_NUM_THREADS=1 sh tests/thunar_terminal_test.sh "$(APP)"
.PHONY: independent-window-test
independent-window-test: $(APP)
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER \
LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24' \
HARMONY_DESKTOP_RECOVERY=0 LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24' \
env TERMINAL_PRIVATE_XVFB=1 python3 tests/independent_windows_test.py "$(APP)"
.PHONY: keyboard-layout-window-test
keyboard-layout-window-test: $(APP)
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER -u TMUX -u TMUX_PANE \
LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24 -noreset' \
HARMONY_DESKTOP_RECOVERY=0 LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24 -noreset' \
env TERMINAL_PRIVATE_XVFB=1 python3 tests/keyboard_layout_window_test.py "$(APP)"
.PHONY: cursor-blink-window-test
@@ -70,7 +82,7 @@ cursor-blink-window-test: $(APP)
env TERMINAL_PRIVATE_XVFB=1 python3 tests/cursor_blink_window_test.py "$(APP)"
standalone-test: $(APP)
ZIRAN="$(ZIRAN)" RAYLIB_A="$(if $(RAYLIB_A),$(RAYLIB_A),$(abspath $(BUILD_DIR))/raylib/raylib/libraylib.a)" sh tests/standalone_test.sh
ZIRAN="$(ZIRAN)" sh tests/standalone_test.sh
parser-replay:
ZIRAN="$(ZIRAN)" sh scripts/parser-replay.sh
@@ -85,6 +97,33 @@ pty-native:
$(CC) -std=c11 -O1 -fPIC -I$(PTY_GEN) -c "$$source" -o "$${source%.c}.o"; \
done
.PHONY: zx zx-window-test pty-zx-test screen-zx-test
zx:
ZIRAN="$(ZIRAN)" CC="$(CC)" sh scripts/build-zx.sh "$(BUILD_DIR)"
zx-window-test: zx
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER -u TMUX -u TMUX_PANE \
HARMONY_DESKTOP_RECOVERY=0 YUE_DESKTOP_RECOVERY=0 LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24' \
env TERMINAL_PRIVATE_XVFB=1 SHELL=/bin/sh python3 tests/zx_window_test.py "$(BUILD_DIR)/terminal-zx-player"
pty-zx-test:
$(ZIRAN) bundle --project $(LOCK_FLAGS) --root src --entry terminal_pty_zx_test:main \
-o $(BUILD_DIR)/terminal_pty_zx_test.zx tests/terminal_pty_zx_test.zi
set -e; ziran_root="$$($(ZIRAN) pkg path ziran $(LOCK_FLAGS))"; \
LDLIBS="$$ziran_root/build/libziran.a -lm -ldl -lpthread" \
$(ZIRAN) build --project $(LOCK_FLAGS) --root src --target=c --entry terminal_pty_zx_host_test:main \
--exe -o $(BUILD_DIR)/pty-zx-host-test tests/terminal_pty_zx_host_test.zi
$(BUILD_DIR)/pty-zx-host-test/terminal_pty_zx_host_test $(BUILD_DIR)/terminal_pty_zx_test.zx
screen-zx-test:
$(ZIRAN) bundle --project $(LOCK_FLAGS) --root src --entry terminal_screen_zx_test:main \
-o $(BUILD_DIR)/terminal_screen_zx_test.zx tests/terminal_screen_zx_test.zi
set -e; ziran_root="$$($(ZIRAN) pkg path ziran $(LOCK_FLAGS))"; \
LDLIBS="$$ziran_root/build/libziran.a -lm -ldl -lpthread" \
$(ZIRAN) build --project $(LOCK_FLAGS) --root src --target=c --entry terminal_screen_zx_host_test:main \
--exe -o $(BUILD_DIR)/screen-zx-host-test tests/terminal_screen_zx_host_test.zi
$(BUILD_DIR)/screen-zx-host-test/terminal_screen_zx_host_test $(BUILD_DIR)/terminal_screen_zx_test.zx
.PHONY: ziran-migration-check
ziran-migration-check:
$(ZIRAN_MIGRATION_TEST)
@@ -167,7 +206,7 @@ pane-native:
rm -f $(PANE_LIB)
$(AR) rcs $(PANE_LIB) $(PANE_GEN)/*.o
.PHONY: application-test input-test view-test host-test
.PHONY: application-test input-test view-test host-test context-menu-test
application-test:
ZIRAN="$(ZIRAN)" sh tests/application_test.sh
@@ -180,19 +219,22 @@ view-test:
host-test:
ZIRAN="$(ZIRAN)" sh tests/application_test.sh host
pane-ziran-test: terminal-test terminal-capture-test terminal-capture-storage-test reflow-span-test config-test widget-test profile-test session-test launch-test application-test input-test view-test host-test clipboard-test selection-test keys-test osc-test metrics-test pty-test ziran-migration-check
context-menu-test:
ZIRAN="$(ZIRAN)" sh tests/context_menu_test.sh
pane-ziran-test: terminal-test terminal-capture-test terminal-capture-storage-test reflow-span-test config-test widget-test profile-test session-test launch-test application-test input-test view-test host-test context-menu-test clipboard-test selection-test keys-test osc-test metrics-test pty-test ziran-migration-check
package-test:
ZIRAN="$(ZIRAN)" sh tests/package_test.sh
test: package-test pane-ziran-test link-window-test selection-copy-window-test standalone-test independent-window-test cursor-blink-window-test install-test parser-replay-test reflow-cursor-test
test: package-test pane-ziran-test image-input-window-test link-window-test selection-copy-window-test context-menu-window-test thunar-terminal-test standalone-test independent-window-test cursor-blink-window-test install-test parser-replay-test reflow-cursor-test
.PHONY: reflow-cursor-test
reflow-cursor-test:
sh tests/reflow_cursor_test.sh
install: $(APP)
mkdir -p "$(DESTDIR)$(BINDIR)" "$(DESTDIR)$(APPDIR)"
mkdir -p "$(DESTDIR)$(BINDIR)" "$(DESTDIR)$(APPDIR)" "$(DESTDIR)$(HELPERDIR)"
$(INSTALL) -m 755 "$(APP)" "$(DESTDIR)$(BINDIR)/.terminal-install"
mv -f "$(DESTDIR)$(BINDIR)/.terminal-install" "$(DESTDIR)$(BINDIR)/terminal"
{ \
@@ -201,6 +243,7 @@ install: $(APP)
printf '%s\n' 'Icon=utilities-terminal' 'Terminal=false' 'Categories=System;TerminalEmulator;'; \
printf '%s\n' 'Keywords=terminal;shell;' 'StartupNotify=true'; \
} > "$(DESTDIR)$(APPDIR)/terminal.desktop"
$(INSTALL) -m 644 data/terminal-helper.desktop "$(DESTDIR)$(HELPERDIR)/terminal.desktop"
if command -v update-desktop-database >/dev/null 2>&1; then update-desktop-database "$(DESTDIR)$(APPDIR)"; fi
install-test: $(APP)
@@ -208,6 +251,7 @@ install-test: $(APP)
trap 'rm -rf "$$stage"' EXIT HUP INT TERM; \
$(MAKE) --no-print-directory install DESTDIR="$$stage" PREFIX=/usr; \
test -x "$$stage/usr/bin/terminal"; test -f "$$stage/usr/share/applications/terminal.desktop"; \
test -f "$$stage/usr/share/xfce4/helpers/terminal.desktop"; \
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY "$$stage/usr/bin/terminal" --version | grep -qx "Terminal 0.1"; \
if command -v desktop-file-validate >/dev/null 2>&1; then desktop-file-validate "$$stage/usr/share/applications/terminal.desktop"; fi
+26 -163
View File
@@ -16,10 +16,9 @@ make install
The application, terminal engine, pane and shared application host are
maintained in Ziran. `make` generates native C from the current `.zi`
entrypoint and links Kryon's Raylib backend over SDL2. The build needs a C
compiler, CMake, pkg-config, SDL2, WebP and OpenGL development files. Raylib's source
is resolved from the Git-backed package lock. Builds default to one job;
`TERMINAL_BUILD_JOBS` may select up to four.
entrypoint and links Kryon's desktop host: an SDL2 window drawn with Cairo and
Pango. The build needs a C compiler, pkg-config, and the SDL2, Cairo, Pango,
GTK 3, WebP, X11 and XCB development files.
`standalone-window-test` runs the actual executable on a private Xvfb display.
It checks CLI routes, a rendered window, real child-process input, held and
@@ -42,90 +41,15 @@ Hosts can import `terminal/app_host`; begin its frame with `Host.BeginFrame`
so shell keys reach the terminal before retained widget navigation. The host owns the surrounding frame,
device input and window operations.
## Embedding as a Ziran package
Terminal is also a Git-backed Ziran package. Add it to an existing application:
```sh
ziran add https://github.com/kryonlabs/terminal.git --name terminal
ziran pkg list terminal
```
Commit the generated `ziran.lock` with the application's manifest. Use
`#import "terminal/terminal"` for the parser, `Terminal`/`Cell` state, scrollback and
owned PTY lifecycle, and `#import "terminal/terminal_pane_widget"` for
`TerminalPane` and `DrawTerminalPane`. The pane accepts the host's existing
Kryon session and bounds; it creates no window, event loop or application
configuration. `terminal/app_host` is available when embedding the complete tabbed
Terminal application instead of a single pane.
Initialize each state with `terminal_init`, then either `terminal_spawn` for
an owned child or `terminal_resize` and `terminal_feed` for host-supplied
output. Draw it inside the host's `BeginFrame`/`EndFrame`, with `handle_input`
enabled only while the terminal owns keyboard focus. Call `terminal_poll` for
owned children and `terminal_close` when removing a terminal to release its
buffers and supervised child. Display and window lifecycle stay with the host.
For complete captured output in a detached state, `terminal_feed_capture`
normalizes LF to CRLF and can omit the final capture-pane delimiter. Start
with `terminal_init` and `terminal_resize`. Plain text, Unicode and SGR use
batched history transfers on an empty screen; cursor controls, other escape
sequences and existing screen content use the ordinary parser. Owned PTYs
are rejected. The call preserves styles, soft wrapping and the configured
logical history limit, and ordinary `terminal_feed` can continue afterward.
It reserves at most one screen minus one row beyond the history limit while
batching. `make terminal-capture-test` checks parity before and after later
input and resize. `sh scripts/capture-replay.sh` measures allocation, capture
parsing and reflow separately in C from source or saved IR.
For repeated complete snapshots, `terminal_reset_capture` resets a detached
engine while reusing compatible screen and history storage. It clears prior
parser, mode, image and clipboard state before replay, and leaves the prior
capture intact if replacement storage cannot be allocated. It rejects a live
PTY or supervised process. `make terminal-capture-storage-test` checks state
parity and allocation failures from source and saved IR.
For a remote or otherwise host-managed process, set the pane's `write_input`
callback and `input_userdata`; keyboard input is encoded by Terminal and handed to
that callback instead of a local PTY. Hosts that capture input themselves can
call `TerminalPaneHandleInputTo` with a `KeyboardFrame`. Set `scroll_offset`
to the number of history rows above the live screen (zero follows the live
screen); cells retain their ANSI colors and styles while drawing history.
The package also exports `terminal/terminal_keyboard`, `terminal/terminal_pane_keys`,
`terminal/terminal_pane_profile_colors` and `terminal/terminal_clipboard` for hosts that
manage input frames, protocol encoding, colors or clipboard routing directly.
`terminal/terminal_drop` turns a file or folder a host received from a drag
and drop into the text to write as input: `DroppedPathText` single-quotes the
path (escaping quotes inside), adds a separating space, and refuses paths with
control characters such as a newline.
Internal parser modules remain private. Applications should use the same
locked Kryon dependency as Terminal so their session and geometry types are shared.
Hosts that own pointer gestures can call `TerminalPaneLinkAt(terminal,
viewport, col, row, storage)` from `terminal/terminal_pane_widget`; pass a null
viewport for the engine's native history/screen grid. The returned target
borrows `storage`; the host opens it with its platform URL handler.
Local application overrides may name the canonical `kryonlabs/terminal` checkout
in an ignored `ziran.local.toml`; no source copies or sibling module paths are
needed in application code.
`make package-test` adds Terminal by its HTTPS URL to a generated consumer,
then compiles and runs package-qualified imports in C from source and
saved IR. It checks Unicode/ANSI parsing, pane painting through the host's
Kryon session, keyboard encoding and clipboard storage without a desktop
display. The consumer has its own module roots and checks that Terminal's
private modules stay unavailable through package-qualified imports.
`TERMINAL_PACKAGE_LOCKED=1 make package-test` checks committed Git packages with
`--locked` after generating the consumer's dependency lock.
`make install` installs the `terminal` command and a desktop launcher named Terminal.
`make install` installs the `terminal` command, a desktop launcher named Terminal,
and the Xfce TerminalEmulator helper definition.
The default `PREFIX` is `~/.local`; `DESTDIR` supports staged packaging.
`install-test` checks a disposable staged installation.
The Linux release workflow is in `.github/workflows/release.yml`. Its intended
assets are `tar.gz`, `.deb`, and `.AppImage` packages. The remaining behavior
and release-readiness work is tracked in `docs/REMAINING_FEATURE_PLAN.md` and
`docs/ZIRAN_MIGRATION.md`.
assets are `tar.gz`, `.deb`, and `.AppImage` packages. Release-readiness work
is tracked in `plans/open-work.md`; `docs/ZIRAN_MIGRATION.md` maps the
maintained modules.
Dependencies resolve through `scripts/ziran.sh`, `ziran.toml`, and the
command-generated `ziran.lock`. Install Ziran on `PATH` for a locked checkout.
@@ -142,9 +66,8 @@ ziran = "../../ziranlang/ziran"
kryon = "../../kryonlabs/kryon"
```
Additional source-package overrides, such as Kryon's `raylib` dependency,
may point to an existing local package checkout. Local overrides do not
belong in the manifest or release artifacts.
Additional source-package overrides may point to an existing local package
checkout. Local overrides do not belong in the manifest or release artifacts.
Run options:
@@ -180,6 +103,11 @@ command-line specs. `--drop-down` starts a borderless top-of-screen terminal
window. `--window` is accepted as a separator and currently opens another tab
because Terminal does not have multi-window process/server support yet.
A working directory that is missing, a file, or cannot be entered starts the
shell in the home folder with a notice instead. A Thunar custom action
writes `terminal --working-directory=%f`: Thunar quotes `%f` itself, so
quotes around it become part of the path.
Config is read from `$XDG_CONFIG_HOME/terminal/config` or
`~/.config/terminal/config`:
@@ -250,6 +178,8 @@ case-insensitively; queries containing uppercase letters are case-sensitive.
Mouse selection keeps a local primary selection for the terminal; middle click
pastes that selection before falling back to the system clipboard, and the
right-click menu exposes both clipboard paste and primary-selection paste.
Right-click on selected text copies it to the clipboard instead; with nothing
selected, or with Shift held, right-click opens the menu.
Copied soft-wrapped lines are joined without adding artificial newlines.
Bracketed paste wraps pasted text and strips embedded terminal control
sequences so copied text cannot break out of the paste bracket.
@@ -259,83 +189,16 @@ OSC 8 terminal hyperlinks are underlined with the theme link color and open
with `Alt` + left click or `Ctrl` + left click. Visible HTTP and HTTPS URLs
also open with either modifier, including links wrapped across terminal rows.
Terminal graphics:
## Documentation
- Sixel images are decoded from DCS sequences and rendered inline in the
terminal viewport.
- DEC special graphics character sets are mapped to Unicode line-drawing
characters for ncurses-style terminal UIs.
- Insert/replace mode (`CSI 4 h/l`) is supported, including terminal mode
reports.
- ANSI newline mode (`CSI 20 h/l`) controls whether LF/VT/FF also return to
column zero, including terminal mode reports.
- SGR rendering covers bold, faint, italic, underline, underline color, blink,
inverse, conceal, strike, overline, indexed colors, and truecolor.
- Application cursor-key mode covers arrow keys plus Home/End, including
modified Home/End sequences.
- Function-key output covers F1-F24 with xterm-style modifier sequences, and
XTGETTCAP advertises those emitted key capabilities.
- Application keypad mode covers digits, operators, center/corner keys, and
Enter, with matching XTGETTCAP keypad capability reports.
- Printable-key input maps Ctrl letters and common Ctrl punctuation, including
`Ctrl+/` and `Ctrl+-`, to terminal control bytes, with Alt preserved as an
ESC prefix.
- xterm `modifyOtherKeys` mode (`CSI > 4 ; n m`) is supported for modified
printable-key reporting, including the xterm disable sequence (`CSI > 4 n`).
- Mouse reporting covers X10, normal, button-event, any-event, SGR coordinates,
SGR-Pixels coordinates, UTF-8 coordinates, urxvt coordinates, wheel events,
motion events, and modifier bits.
- Cursor save/restore keeps cursor position, rendition, active character set,
origin/wrap mode, insert mode, and hyperlink state.
- Alternate-screen mode presents only the alternate grid while preserving normal
scrollback for restoration after full-screen apps exit.
- xterm alternate-scroll mode (`DECSET 1007`) sends wheel movement as cursor
keys in the alternate screen when mouse reporting is not active.
- xterm focus reporting (`DECSET 1004`) sends focus changes for both window
focus and active-tab changes.
- 8-bit C1 CSI/OSC/DCS plus IND/NEL/HTS/RI controls are parsed, and APC/PM/SOS
control strings are ignored so their payloads do not leak into the terminal
grid.
- BEL triggers a short theme-colored visual bell without writing text into the
terminal grid.
- CAN/SUB cancel active control sequences and return the parser to text mode.
- Common CSI aliases are supported, including horizontal/vertical relative
moves, horizontal absolute moves, and repeat preceding graphic character.
- DECSTR soft reset (`CSI ! p`) resets terminal modes, margins, rendition, and
character sets without clearing the visible grid.
- DECRQSS status-string reports answer SGR, scroll-margin, cursor-style, and
character-protection queries with valid DCS responses.
- XTGETTCAP (`DCS + q`) reports the terminal name, color capabilities, and the
special-key sequences Terminal actually emits.
- Horizontal tab set/clear controls are supported, including clearing all tab
stops for terminal UI alignment.
- DEC private cursor-position reports and DEC screen-alignment test are
handled.
- DEC private cursor visibility and blink modes are reported and rendered.
- DECSCUSR cursor-shape controls distinguish blinking and steady block,
underline, and bar cursors.
- XTWINOPS text-area and screen character-size reports return the active
terminal grid dimensions.
- VT next-line and DECID escape controls are handled.
- OSC palette queries return xterm-style indexed responses and fall back to the
built-in 256-color palette when a color has not been overridden.
- OSC color parsing accepts compact and wide X-style hash forms in addition to
`rgb:` values.
- OSC dynamic colors cover default foreground/background, cursor, selection
background, selection foreground, and indexed palette entries.
- OSC title handling distinguishes window and icon titles, and includes
target-aware save/restore stack controls for terminal programs that
temporarily replace titles.
- OSC 52 clipboard sequences can set the host clipboard and answer bounded
clipboard queries from the current host clipboard.
- Terminal foreground, background, and cursor-color resets return to the
resolved Kryon/system theme colors unless the profile explicitly overrides
them.
- Sixel color registers, RGB/HLS color definitions, raster attributes, repeat
commands, row advance, carriage return, transparency, 7-bit DCS, and 8-bit
DCS/ST are supported.
- Erase-line, erase-display, reset, alternate-screen clear, scrolling, and
scrollback eviction keep sixel images attached to the terminal content.
| Question | File |
| --- | --- |
| Embed Terminal or a pane in another app | docs/EMBEDDING.md |
| Parser, graphics and mode coverage | docs/COMPATIBILITY.md |
| Read-only viewport projection API | docs/VIEWPORT.md |
| Ziran migration module map | docs/ZIRAN_MIGRATION.md |
| Benchmarks and workloads | benchmarks/README.md |
| Open work | plans/open-work.md |
## Name and repository
+1
View File
@@ -0,0 +1 @@
0.1.1
+1 -1
View File
@@ -263,7 +263,7 @@ Current command-line compatibility coverage:
| `--title`, `-T` | implemented as the initial tab/window title and per-tab title |
| `--hold`, `-H` | accepted; ktrem already keeps command sessions visible after child exit |
| `--geometry COLSxROWS` | implemented for initial terminal grid estimate and window size |
| `--fullscreen`, `--maximize` | implemented through Kryon/raylib window state |
| `--fullscreen`, `--maximize` | implemented through Kryon desktop window state |
| `--drop-down` | implemented for first-run borderless top-of-screen window shape |
| `--show-menubar`, `--hide-menubar` | accepted; ktrem has fixed minimal chrome today |
| `--show-toolbar`, `--hide-toolbar` | accepted; no separate toolbar exists today |
+10
View File
@@ -0,0 +1,10 @@
[Desktop Entry]
Version=1.0
Type=X-XFCE-Helper
Name=Terminal
Icon=utilities-terminal
StartupNotify=false
X-XFCE-Binaries=terminal;
X-XFCE-Category=TerminalEmulator
X-XFCE-Commands=%B --working-directory=.;
X-XFCE-CommandsWithParameter=%B --working-directory=. -x %s;
+83
View File
@@ -0,0 +1,83 @@
# Terminal compatibility
What Terminal parses and renders today. Each listed behavior is implemented
and covered by the focused suites (`make pane-ziran-test`) and the benchmark
workloads in `benchmarks/`.
Terminal graphics and compatibility:
- Sixel images are decoded from DCS sequences and rendered inline in the
terminal viewport.
- DEC special graphics character sets are mapped to Unicode line-drawing
characters for ncurses-style terminal UIs.
- Insert/replace mode (`CSI 4 h/l`) is supported, including terminal mode
reports.
- ANSI newline mode (`CSI 20 h/l`) controls whether LF/VT/FF also return to
column zero, including terminal mode reports.
- SGR rendering covers bold, faint, italic, underline, underline color, blink,
inverse, conceal, strike, overline, indexed colors, and truecolor.
- Application cursor-key mode covers arrow keys plus Home/End, including
modified Home/End sequences.
- Function-key output covers F1-F24 with xterm-style modifier sequences, and
XTGETTCAP advertises those emitted key capabilities.
- Application keypad mode covers digits, operators, center/corner keys, and
Enter, with matching XTGETTCAP keypad capability reports.
- Printable-key input maps Ctrl letters and common Ctrl punctuation, including
`Ctrl+/` and `Ctrl+-`, to terminal control bytes, with Alt preserved as an
ESC prefix.
- xterm `modifyOtherKeys` mode (`CSI > 4 ; n m`) is supported for modified
printable-key reporting, including the xterm disable sequence (`CSI > 4 n`).
- Mouse reporting covers X10, normal, button-event, any-event, SGR coordinates,
SGR-Pixels coordinates, UTF-8 coordinates, urxvt coordinates, wheel events,
motion events, and modifier bits.
- Cursor save/restore keeps cursor position, rendition, active character set,
origin/wrap mode, insert mode, and hyperlink state.
- Alternate-screen mode presents only the alternate grid while preserving normal
scrollback for restoration after full-screen apps exit.
- xterm alternate-scroll mode (`DECSET 1007`) sends wheel movement as cursor
keys in the alternate screen when mouse reporting is not active.
- xterm focus reporting (`DECSET 1004`) sends focus changes for both window
focus and active-tab changes.
- 8-bit C1 CSI/OSC/DCS plus IND/NEL/HTS/RI controls are parsed, and APC/PM/SOS
control strings are ignored so their payloads do not leak into the terminal
grid.
- BEL triggers a short theme-colored visual bell without writing text into the
terminal grid.
- CAN/SUB cancel active control sequences and return the parser to text mode.
- Common CSI aliases are supported, including horizontal/vertical relative
moves, horizontal absolute moves, and repeat preceding graphic character.
- DECSTR soft reset (`CSI ! p`) resets terminal modes, margins, rendition, and
character sets without clearing the visible grid.
- DECRQSS status-string reports answer SGR, scroll-margin, cursor-style, and
character-protection queries with valid DCS responses.
- XTGETTCAP (`DCS + q`) reports the terminal name, color capabilities, and the
special-key sequences Terminal actually emits.
- Horizontal tab set/clear controls are supported, including clearing all tab
stops for terminal UI alignment.
- DEC private cursor-position reports and DEC screen-alignment test are
handled.
- DEC private cursor visibility and blink modes are reported and rendered.
- DECSCUSR cursor-shape controls distinguish blinking and steady block,
underline, and bar cursors.
- XTWINOPS text-area and screen character-size reports return the active
terminal grid dimensions.
- VT next-line and DECID escape controls are handled.
- OSC palette queries return xterm-style indexed responses and fall back to the
built-in 256-color palette when a color has not been overridden.
- OSC color parsing accepts compact and wide X-style hash forms in addition to
`rgb:` values.
- OSC dynamic colors cover default foreground/background, cursor, selection
background, selection foreground, and indexed palette entries.
- OSC title handling distinguishes window and icon titles, and includes
target-aware save/restore stack controls for terminal programs that
temporarily replace titles.
- OSC 52 clipboard sequences can set the host clipboard and answer bounded
clipboard queries from the current host clipboard.
- Terminal foreground, background, and cursor-color resets return to the
resolved Kryon/system theme colors unless the profile explicitly overrides
them.
- Sixel color registers, RGB/HLS color definitions, raster attributes, repeat
commands, row advance, carriage return, transparency, 7-bit DCS, and 8-bit
DCS/ST are supported.
- Erase-line, erase-display, reset, alternate-screen clear, scrolling, and
scrollback eviction keep sixel images attached to the terminal content.
+77
View File
@@ -0,0 +1,77 @@
# Embedding Terminal as a Ziran package
## Embedding as a Ziran package
Terminal is also a Git-backed Ziran package. Add it to an existing application:
```sh
ziran add https://github.com/kryonlabs/terminal.git --name terminal
ziran pkg list terminal
```
Commit the generated `ziran.lock` with the application's manifest. Use
`#import "terminal/terminal"` for the parser, `Terminal`/`Cell` state, scrollback and
owned PTY lifecycle, and `#import "terminal/terminal_pane_widget"` for
`TerminalPane` and `DrawTerminalPane`. The pane accepts the host's existing
Kryon session and bounds; it creates no window, event loop or application
configuration. `terminal/app_host` is available when embedding the complete tabbed
Terminal application instead of a single pane.
Initialize each state with `terminal_init`, then either `terminal_spawn` for
an owned child or `terminal_resize` and `terminal_feed` for host-supplied
output. Draw it inside the host's `BeginFrame`/`EndFrame`, with `handle_input`
enabled only while the terminal owns keyboard focus. Call `terminal_poll` for
owned children and `terminal_close` when removing a terminal to release its
buffers and supervised child. Display and window lifecycle stay with the host.
For complete captured output in a detached state, `terminal_feed_capture`
normalizes LF to CRLF and can omit the final capture-pane delimiter. Start
with `terminal_init` and `terminal_resize`. Plain text, Unicode and SGR use
batched history transfers on an empty screen; cursor controls, other escape
sequences and existing screen content use the ordinary parser. Owned PTYs
are rejected. The call preserves styles, soft wrapping and the configured
logical history limit, and ordinary `terminal_feed` can continue afterward.
It reserves at most one screen minus one row beyond the history limit while
batching. `make terminal-capture-test` checks parity before and after later
input and resize. `sh scripts/capture-replay.sh` measures allocation, capture
parsing and reflow separately in C from source or saved IR.
For repeated complete snapshots, `terminal_reset_capture` resets a detached
engine while reusing compatible screen and history storage. It clears prior
parser, mode, image and clipboard state before replay, and leaves the prior
capture intact if replacement storage cannot be allocated. It rejects a live
PTY or supervised process. `make terminal-capture-storage-test` checks state
parity and allocation failures from source and saved IR.
For a remote or otherwise host-managed process, set the pane's `write_input`
callback and `input_userdata`; keyboard input is encoded by Terminal and handed to
that callback instead of a local PTY. Hosts that capture input themselves can
call `TerminalPaneHandleInputTo` with a `KeyboardFrame`. Set `scroll_offset`
to the number of history rows above the live screen (zero follows the live
screen); cells retain their ANSI colors and styles while drawing history.
The package also exports `terminal/terminal_keyboard`, `terminal/terminal_pane_keys`,
`terminal/terminal_pane_profile_colors` and `terminal/terminal_clipboard` for hosts that
manage input frames, protocol encoding, colors or clipboard routing directly.
`terminal/terminal_drop` turns a file or folder a host received from a drag
and drop into the text to write as input: `DroppedPathText` single-quotes the
path (escaping quotes inside), adds a separating space, and refuses paths with
control characters such as a newline.
Internal parser modules remain private. Applications should use the same
locked Kryon dependency as Terminal so their session and geometry types are shared.
Hosts that own pointer gestures can call `TerminalPaneLinkAt(terminal,
viewport, col, row, storage)` from `terminal/terminal_pane_widget`; pass a null
viewport for the engine's native history/screen grid. The returned target
borrows `storage`; the host opens it with its platform URL handler.
Local application overrides may name the canonical `kryonlabs/terminal` checkout
in an ignored `ziran.local.toml`; no source copies or sibling module paths are
needed in application code.
`make package-test` adds Terminal by its HTTPS URL to a generated consumer,
then compiles and runs package-qualified imports in C from source and
saved IR. It checks Unicode/ANSI parsing, pane painting through the host's
Kryon session, keyboard encoding and clipboard storage without a desktop
display. The consumer has its own module roots and checks that Terminal's
private modules stay unavailable through package-qualified imports.
`TERMINAL_PACKAGE_LOCKED=1 make package-test` checks committed Git packages with
`--locked` after generating the consumer's dependency lock.
-91
View File
@@ -1,91 +0,0 @@
# Terminal Remaining Feature Plan
Terminal is currently faster than xfce4-terminal on the saved synthetic and
externally driven Xvfb benchmark set. The full xfce4-terminal alternative goal
is still open until the feature and release-readiness gaps below are complete.
## Current Measured Status
Saved benchmark results show Terminal ahead on average for:
- Startup payload, ANSI flood, Unicode output, alternate-screen redraw, dense
SGR styling, wrapped output, scrollback flood, and cursor matrix updates.
- Paste-like output, OSC 8 hyperlink-heavy output, and search-corpus output.
- External live resize, external clipboard paste, and external find workflow.
The benchmark files are in `benchmarks/results/`. These are directional Xvfb
benchmarks, not a substitute for broader real-desktop validation.
## Must Finish Before Calling Terminal a Full Alternative
### 1. Release And Installability
- Keep GitHub Actions green for `make test` and `make all` from a clean
checkout.
- Publish Linux release assets from GitHub Releases.
- Add a `.desktop` file, app icon install target, and documented install path.
- Decide whether Terminal should advertise a custom `TERM` and ship terminfo, or
keep xterm-compatible defaults.
- Add changelog/version automation before the first numbered release.
### 2. Xfce Launch And Process Parity
- Implement real multi-window launch semantics for `--window`.
- Add single-instance command routing equivalent to xfce4-terminal server
behavior, while keeping `--disable-server` as an opt-out.
- Make repeated `--drop-down` invocation toggle an existing drop-down window
instead of launching another instance.
- Preserve working directory, title, hold, geometry, and command specs across
mixed `--tab` and `--window` launch requests.
### 3. Preferences And Profiles
- Add a complete preferences UI for font, colors, scrollback, cursor, command,
working directory, shortcuts, and behavior toggles.
- Add import/export or profile files that can be copied between machines.
- Add shortcut remapping while keeping terminal-standard defaults.
### 4. Glyph And Font Coverage
- Finish fontconfig-backed fallback for missing glyphs beyond the current
static fallback paths.
- Verify box drawing, blocks, Powerline, Nerd Font symbols, Greek, Cyrillic,
emoji samples, and common CJK on a clean Linux install.
- Add a glyph smoke workload that screenshots representative cells and fails on
tofu/missing-glyph rendering.
### 5. Terminal Compatibility
- Keep expanding parser/input coverage with real applications: `vim`, `nano`,
`less`, `htop`, `tmux`, `ssh`, `git`, package managers, Python/Node/Rust test
output, curses dashboards, and sixel tools.
- Add automated scenario tests for bracketed paste, OSC 52, OSC 8, mouse modes,
modifyOtherKeys, keypad/application cursor modes, and title/color stacks.
- Validate close behavior with stubborn child processes and held sessions.
### 6. Real-Desktop Benchmark Validation
- Repeat the Xvfb benchmark suite on a real desktop without killing or
controlling the user's active xfce4-terminal.
- Add memory/RSS measurements for large scrollback and sixel workloads.
- Add startup cold/warm measurements from an installed binary.
- Keep benchmark docs honest: measured categories only, no broad claims from
narrow tests.
### 7. Kryon Renderer Direction
Kryon's current raylib/SDL backend is good enough for the measured parity set.
The next major performance step should be a Kryon terminal-grid primitive, not
a Terminal-only renderer and not a move away from Kryon.
The renderer should use:
- Persistent glyph atlas and cached glyph metrics.
- Retained row/cell state with dirty-region damage.
- Batched quads for glyphs, backgrounds, underlines, cursor, and selections.
- A backend-neutral Kryon API first, with the current raylib/SDL backend as the
first implementation.
- A future `wgpu-native`/WebGPU backend only after the abstraction is proven.
This keeps Terminal as the showcase for Kryon while improving Kryon for other
applications too.
+35
View File
@@ -0,0 +1,35 @@
# Open Terminal work
One line per open item: what, where in the code, how to check.
- Release assets: publish `tar.gz`, `.deb` and `.AppImage` from
`.github/workflows/release.yml`, add a `.desktop` and icon install target with a
documented install path, decide custom `TERM`/terminfo versus xterm defaults,
and add changelog/version automation before the first numbered release; check
with `make install` and a staged `DESTDIR` install.
- Multi-window launch semantics for `--window`, single-instance routing with
`--disable-server`, repeated `--drop-down` toggling, and preserving working
directory/title/hold/geometry across mixed `--tab`/`--window` requests:
`src/app/app_launch_options.zi`; covered by `make standalone-window-test`.
- Complete preferences UI (font, colors, scrollback, cursor, command, working
directory, shortcuts, behavior), profile import/export and shortcut remapping:
`src/app/app_profile.zi`, `src/app/app_config.zi`; check with the profile and
config suites in `make pane-ziran-test`.
- Fontconfig-backed glyph fallback beyond the static paths, verified against
box drawing, Powerline, Nerd Font, Greek, Cyrillic, emoji and CJK samples, plus
a glyph smoke workload that fails on tofu: `src/` font modules; run as a new
test beside the widget suite.
- Expand parser/input coverage with real applications and add scenario tests
for bracketed paste, OSC 52, OSC 8, mouse modes, `modifyOtherKeys`, keypad and
application cursor modes, and title/color stacks: `src/engine/`; covered by
`make pane-ziran-test` and `tests/`.
- Repeat the Xvfb benchmark suite on a real desktop without touching the
owner's sessions, and add RSS plus cold/warm startup measurements:
`benchmarks/run-terminal-benchmarks.sh`; keep claims limited to measured
categories.
- The next major performance step is a backend-neutral Kryon terminal-grid
primitive (persistent glyph atlas, retained dirty rows, batched quads), owned
in `kryonlabs/kryon`, not a Terminal-only renderer.
- Rill still owes its host integration of Terminal's Ziran implementation
(native whole-application graphics and complete graphical font fallback):
background in `docs/ZIRAN_MIGRATION.md`; the active Rill task owns it.
+52
View File
@@ -0,0 +1,52 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS SESSION_MANAGER
output=${1:-build/linux-$(uname -m)}
mkdir -p "$output"
output=$(CDPATH= cd -- "$output" && pwd)
case "$output" in "$PWD"/build/*) ;; *) echo 'Terminal ZX output must be under build/' >&2; exit 2 ;; esac
ziran=${ZIRAN:-./scripts/ziran.sh}
lock_flag=
if [ ! -f ziran.local.toml ]; then lock_flag=--locked; fi
toolchain=$("$ziran" pkg path ziran $lock_flag)
kryon=$("$ziran" pkg path kryon $lock_flag)
entry=$kryon/src/backend/zx_run.zi
frame=$kryon/src/backend/frame_entry.zi
guest=src/app/app_zx_frame.zi
opus=$kryon/build/opus/libopus/libopus.a
generated=$output/generated/terminal-zx-player
scratch=$(mktemp -d "$output/terminal-zx.XXXXXX")
trap 'rm -rf "$scratch"' EXIT HUP INT TERM
if [ ! -r "$opus" ]; then
make -j1 -C "$kryon" ZIRAN_DIR="$toolchain" CODEC_JOBS=1 "$opus"
fi
# Ask the compiler for Kryon's resolved module identity. Locked dependencies
# and local overrides can resolve to different package IDs.
mkdir "$scratch/ir"
"$ziran" ir --project $lock_flag --root src --define KRYON_ZX -o "$scratch/ir" "$entry" "$frame"
set -- "$scratch"/ir/*_zx_run.zir
if [ "$#" -ne 1 ] || [ ! -f "$1" ]; then
echo 'Cannot identify the resolved Kryon ZX frame host' >&2
exit 1
fi
module=$(basename "$1" _zx_run.zir)
"$ziran" bundle --project $lock_flag --root src --define KRYON_ZX \
--bind "${module}_frame_entry:ProjectFrame=app_zx_frame:Frame" \
--entry "${module}_zx_run:main" -o "$scratch/Terminal.zx" "$entry" "$guest" "$frame"
mkdir -p "$generated"
"$ziran" build --project $lock_flag --root src --target=c --prune-stale \
--define PLATFORM_DESKTOP -o "$generated" src/app/terminal_zx_player.zi
packages=$(pkg-config --libs sdl2 cairo freetype2 pangocairo fontconfig glib-2.0 x11)
"${CC:-cc}" -std=c99 -Wno-main -O2 -ffunction-sections -fdata-sections \
-I"$toolchain/include" -I"$generated" "$generated"/*.c \
"$toolchain/build/libziran.a" "$opus" \
-Wl,--gc-sections $packages -l:libcurl.so.4 -lm -ldl -lpthread \
-o "$scratch/terminal-zx-player"
"$scratch/terminal-zx-player" --check
mv "$scratch/Terminal.zx" "$output/Terminal.zx"
mv "$scratch/terminal-zx-player" "$output/terminal-zx-player"
+3 -15
View File
@@ -19,25 +19,13 @@ generated=$output/generated
"$ziran" build --project $lock_flags --target="$target" --no-main --prune-stale \
--root src -o "$generated" "$input"
jobs=${TERMINAL_BUILD_JOBS:-1}
case "$jobs" in 1|2|3|4) ;; *) echo 'TERMINAL_BUILD_JOBS must be between 1 and 4' >&2; exit 2 ;; esac
if test -n "${RAYLIB_A:-}"; then
raylib_archive=$RAYLIB_A
else
raylib=$("$ziran" pkg path raylib $lock_flags)
cmake -S "$raylib" -B "$output/raylib" -DPLATFORM=SDL \
-DCMAKE_DISABLE_FIND_PACKAGE_SDL3=ON -DCMAKE_BUILD_TYPE=Release \
-DBUILD_EXAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DCMAKE_POSITION_INDEPENDENT_CODE=ON
cmake --build "$output/raylib" --parallel "$jobs"
raylib_archive=$output/raylib/raylib/libraylib.a
fi
test -f "$raylib_archive"
mkdir -p "$output/bin"
temporary=$(mktemp "$output/bin/terminal.XXXXXX")
trap 'rm -f "$temporary"' EXIT HUP INT TERM
"${CC:-cc}" -std=c11 -O1 -ffunction-sections -fdata-sections \
-I"$generated" "$generated"/*.c -Wl,--gc-sections "$raylib_archive" \
$(pkg-config --libs sdl2 libwebpdemux libwebp) -l:libgtk-3.so.0 -l:libgdk-3.so.0 -l:libglib-2.0.so.0 -lGL -ldl -lpthread -lm -o "$temporary"
-I"$generated" "$generated"/*.c -Wl,--gc-sections \
$(pkg-config --libs sdl2 cairo pangocairo fontconfig freetype2 glib-2.0 libwebpdemux libwebp gtk+-3.0 x11 xcb) \
-ldl -lpthread -lm -o "$temporary"
chmod 755 "$temporary"
mv "$temporary" "$output/bin/terminal"
trap - EXIT HUP INT TERM
+136
View File
@@ -0,0 +1,136 @@
#!/bin/sh
set -eu
umask 022
cd "$(dirname "$0")/.."
if [ "$#" -lt 2 ] || [ "$#" -gt 3 ]; then
echo 'Usage: scripts/package-linux.sh DEB-VERSION OUTPUT-DIR [--with-zx]' >&2
exit 2
fi
deb_version=$1
dpkg --validate-version "$deb_version"
zx_option=${3:-}
case "$zx_option" in ''|--with-zx) ;; *) echo 'Unknown packaging option' >&2; exit 2 ;; esac
output=$(realpath -m -- "$2")
case "$output" in "$PWD"/build/*|"$PWD"/dist) ;; *) echo 'Terminal packages must go under build/ or dist' >&2; exit 2 ;; esac
mkdir -p "$output"
root=$PWD
work=$(mktemp -d "$output/.terminal-package.XXXXXX")
trap 'rm -rf "$work"' EXIT
trap 'exit 1' HUP INT TERM
cd "$work"
# Version-free names keep /releases/latest/download/<name> stable.
deb_root="deb/terminal"
mkdir -p "${deb_root}/DEBIAN" \
"${deb_root}/usr/bin" \
"${deb_root}/usr/share/applications" \
"${deb_root}/usr/share/doc/terminal" \
"${deb_root}/usr/share/icons/hicolor/scalable/apps"
chmod 755 "${deb_root}/DEBIAN"
cp "$root/build/linux-x86_64/bin/terminal" "${deb_root}/usr/bin/terminal"
cp "$root/README.md" "${deb_root}/usr/share/doc/terminal/README.md"
cp "$root/docs/site/favicon.svg" \
"${deb_root}/usr/share/icons/hicolor/scalable/apps/terminal.svg"
cat > "${deb_root}/usr/share/applications/terminal.desktop" <<'EOF'
[Desktop Entry]
Type=Application
Name=Terminal
Comment=Kryon terminal emulator
Exec=terminal
Icon=terminal
Terminal=false
Categories=System;TerminalEmulator;
Keywords=shell;prompt;command;terminal;
EOF
# Depends comes from the binary's real libraries, GTK included.
mkdir -p shlibdeps/debian
printf 'Source: terminal\n\nPackage: terminal\nArchitecture: any\n' \
> shlibdeps/debian/control
shlibdeps=$(cd shlibdeps && dpkg-shlibdeps -O "$work/$deb_root/usr/bin/terminal")
depends=$(printf '%s\n' "$shlibdeps" | sed -n 's/^shlibs:Depends=//p')
test -n "${depends}"
cat > "${deb_root}/DEBIAN/control" <<EOF
Package: terminal
Version: ${deb_version}
Section: x11
Priority: optional
Architecture: amd64
Maintainer: Waozi <[email protected]>
Depends: ${depends}
Recommends: fonts-dejavu-core
Description: Kryon terminal emulator
Terminal is a standalone terminal application using Kryon for windowing,
rendering, input, and platform integration.
EOF
chmod 644 "${deb_root}/DEBIAN/control"
dpkg-deb --build --root-owner-group "${deb_root}" \
terminal-linux-amd64.deb
appdir=AppDir
mkdir -p "${appdir}/usr/bin" \
"${appdir}/usr/share/applications" \
"${appdir}/usr/share/icons/hicolor/scalable/apps"
cp "$root/build/linux-x86_64/bin/terminal" "${appdir}/usr/bin/terminal"
cp "$root/docs/site/favicon.svg" \
"${appdir}/usr/share/icons/hicolor/scalable/apps/terminal.svg"
cp "${deb_root}/usr/share/applications/terminal.desktop" \
"${appdir}/usr/share/applications/terminal.desktop"
# linuxdeploy bundles SDL2, WebP and their dependencies. GTK, GLib,
# Cairo, Pango and GL come from the host: a bundled GTK would not
# match the desktop's themes and modules.
linuxdeploy="$work/linuxdeploy-x86_64.AppImage"
if [ -n "${LINUXDEPLOY_APPIMAGE:-}" ]; then
cp "$LINUXDEPLOY_APPIMAGE" "$linuxdeploy"
else
curl --retry 2 -fsSL -o "$linuxdeploy" \
https://github.com/linuxdeploy/linuxdeploy/releases/download/1-alpha-20251107-1/linuxdeploy-x86_64.AppImage
fi
echo "c20cd71e3a4e3b80c3483cef793cda3f4e990aca14014d23c544ca3ce1270b4d ${linuxdeploy}" |
sha256sum -c -
chmod 755 "${linuxdeploy}"
(
APPIMAGE_EXTRACT_AND_RUN=1 ARCH=x86_64 \
LINUXDEPLOY_OUTPUT_VERSION="${deb_version}" \
LDAI_OUTPUT=terminal-linux-x86_64.AppImage \
"${linuxdeploy}" --appdir "${work}/${appdir}" \
--executable "${work}/${appdir}/usr/bin/terminal" \
--desktop-file "${work}/${appdir}/usr/share/applications/terminal.desktop" \
--icon-file "${work}/${appdir}/usr/share/icons/hicolor/scalable/apps/terminal.svg" \
--exclude-library 'libgtk-3.so*' --exclude-library 'libgdk-3.so*' \
--exclude-library 'libgdk_pixbuf-2.0.so*' --exclude-library 'libglib-2.0.so*' \
--exclude-library 'libgobject-2.0.so*' --exclude-library 'libgio-2.0.so*' \
--exclude-library 'libgmodule-2.0.so*' --exclude-library 'libcairo*' \
--exclude-library 'libpango*' --exclude-library 'libatk*' \
--exclude-library 'libGL.so*' --exclude-library 'libGLX*' \
--output appimage
)
test -x terminal-linux-x86_64.AppImage
set -- terminal-linux-amd64.deb terminal-linux-x86_64.AppImage
if [ "$zx_option" = --with-zx ]; then
guest="$root/build/linux-x86_64/Terminal.zx"
player="$root/build/linux-x86_64/terminal-zx-player"
mkdir zx
install -m 644 "$guest" zx/Terminal.zx
install -m 755 "$player" zx/terminal-zx-player
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS \
-u SESSION_MANAGER HARMONY_DESKTOP_RECOVERY=0 YUE_DESKTOP_RECOVERY=0 \
zx/terminal-zx-player --check
cat > zx/README.txt <<'EOF'
Terminal ZX for Linux x86-64
Keep Terminal.zx in the same directory as terminal-zx-player. Run
./terminal-zx-player to open Terminal, or ./terminal-zx-player --check
to validate the bundle and its host bindings. The player uses the
system SDL2, Cairo, Pango, Fontconfig, GLib, X11 and libcurl libraries.
The guest uses the player's POSIX PTY and terminal screen bindings.
EOF
tar -czf terminal-zx-linux-x86_64.tar.gz -C zx README.txt Terminal.zx terminal-zx-player
cp zx/Terminal.zx Terminal.zx
set -- "$@" Terminal.zx terminal-zx-linux-x86_64.tar.gz
fi
sha256sum "$@" > SHA256SUMS
for file in "$@"; do
mv -f "$file" "$output/$file"
done
mv -f SHA256SUMS "$output/SHA256SUMS"
+1 -1
View File
@@ -1,5 +1,5 @@
State :: #import "app_state";
Tabs :: #import "kryon/Widgets";
Tabs :: #import "kryon/tab_bar";
MenuBarHeight :: (app: *State.State) -> s32 {
if app == null || !app.launch.show_menubar { return 0 }
+145 -13
View File
@@ -7,6 +7,18 @@ Pane :: #import "terminal_pane_clipboard";
Engine :: #import "terminal";
Data :: #import "terminal_clipboard";
Drop :: #import "terminal_drop";
SystemImage :: #import "kryon/SystemClipboardLinux";
Mime :: #import "kryon/MimeClipboardLinux";
File :: #import "std/file_linux";
Text :: #import "std/byte_text_linux";
CString :: #import "std/c_string";
Random :: #import "std/random_linux";
using V :: #import "std/vec";
libc :: #system_library "c";
Environment :: (name: *u8) -> *u8 #foreign libc "getenv";
Allocate :: (count: usize, size: usize) -> *u8 #foreign libc "calloc";
Release :: (memory: *void) #foreign libc "free";
Remove :: (path: *u8) -> s32 #foreign libc "remove";
Actions :: (app: *State.State, session: *Session.Session) -> Pane.TerminalPaneClipboardActions {
selection: Pane.TerminalPaneClipboardController
@@ -20,15 +32,77 @@ ActiveActions :: (app: *State.State) -> Pane.TerminalPaneClipboardActions {
return Actions(app, Sessions.Active(app))
}
image_bytes: *u8;
selection_bytes: [262144]u8;
path_bytes: [4096]u8;
mime_open: bool;
mime_owner: u64;
Bytes :: (value: string) -> *u8 {
descriptor := cast(*Text.TextDescriptor)(*value)
return descriptor.data
}
ByteView :: (value: string) -> []u8 {
descriptor := cast(*Text.TextDescriptor)(*value)
return Text.BytesFromPointer(descriptor.data, cast(u64)value.count)
}
MimeReady :: () -> bool {
if !mime_open { mime_open = Mime.MimeClipboardOpen() }
return mime_open
}
LocalMimeOwner :: () -> bool {
return mime_owner != 0 && MimeReady() && Mime.MimeClipboardOwner() == mime_owner
}
ReleaseMime :: () {
if mime_owner != 0 && MimeReady() { unused Mime.MimeClipboardRelease(mime_owner) }
mime_owner = 0
}
ImagePath :: () -> string {
if image_bytes == null { image_bytes = Allocate(cast(usize)33554432, cast(usize)1) }
if image_bytes == null { return "" }
result := SystemImage.SystemClipboardImage(Text.BytesFromPointer(image_bytes, cast(u64)33554432))
if !result.available || !result.found || result.png.count < 8 || result.png.count != result.size { return "" }
home := Environment(Bytes("XDG_CACHE_HOME")); root := ifx home != null then Text.TextFromCString(home) else ""
folder_builder: Vec(u8)
if root == "" {
home = Environment(Bytes("HOME")); if home == null { return "" }
BuilderPrint(*folder_builder, "%/.cache", Text.TextFromCString(home))
} else { BuilderPrint(*folder_builder, "%", root) }
BuilderPrint(*folder_builder, "/terminal/clipboard")
folder := BuilderFinish(folder_builder); defer Release(cast(*void)Bytes(folder))
for index: 1..cast(s32)folder.count - 1 {
if folder[index] == 47 && !File.CreatePrivateDirectory(folder[:index]) { return "" }
}
if !File.CreatePrivateDirectory(folder) { return "" }
random: [16]u8; if !Random.FillSecure(random[:]) { return "" }
name: Vec(u8); BuilderPrint(*name, "%/", folder); digits := "0123456789abcdef"
for byte: random {
at := cast(s32)byte
BuilderPrint(*name, "%", digits[at / 16:at / 16 + 1])
BuilderPrint(*name, "%", digits[at % 16:at % 16 + 1])
}
BuilderPrint(*name, ".png")
path := BuilderFinish(name); defer Release(cast(*void)Bytes(path))
if !CString.CopyCString(path, path_bytes[:]) { return "" }
file := File.OpenReplace(path); if !file.valid { return "" }
used: s64
while used < result.png.count {
count := File.Write(file, result.png[used:])
if count <= 0 { break }
used += count
}
closed := File.CloseFile(file)
if !closed || used != result.png.count { unused Remove(*path_bytes[0]); return "" }
return Text.TextFromCString(*path_bytes[0])
}
#scope_export
ImagePath :: #type () -> string;
image_path: ImagePath;
PasteImage :: (session: *Session.Session) -> bool {
if session==null || image_path==null { return false }
path:=image_path(); if path=="" { return false }
buffer: [16384]u8; text:=Drop.DroppedPathText(path,buffer[:])
if text=="" { return false }
PasteText(session,text); return true
if session == null || session.read_only { return false }
path := ImagePath(); if path == "" { return false }
buffer: [16384]u8; text := Drop.DroppedPathText(path, buffer[:])
if text == "" { return false }
PasteText(session, text); return true
}
CollectSelection :: (app: *State.State, output: []u8) -> s32 {
if output.count <= 0 { return 0 }
@@ -39,20 +113,78 @@ CollectSelection :: (app: *State.State, output: []u8) -> s32 {
}
PrimaryAvailable :: () -> bool { return Pane.TerminalPaneClipboardPrimarySelectionAvailable() != 0 }
UpdatePrimary :: (app: *State.State) { Pane.TerminalPaneClipboardUpdatePrimary(ActiveActions(app)) }
CopySelection :: (app: *State.State) -> bool { return Pane.TerminalPaneClipboardCopy(ActiveActions(app)) != 0 }
CopySelection :: (app: *State.State) -> bool {
ReleaseMime()
return Pane.TerminalPaneClipboardCopy(ActiveActions(app)) != 0
}
CopyText :: (session: *Session.Session, text: string) -> bool {
if session == null || text == "" { return false }
ReleaseMime()
clipboard := Engine.terminal_clipboard(*session.terminal)
if Data.RequestClipboardBufferWrite(clipboard.clipboard, Bytes(text)) == 0 { return false }
Data.FlushClipboardBufferToHost(clipboard.clipboard)
return true
}
CopySelectionHtml :: (app: *State.State) -> bool {
session := Sessions.Active(app)
if session == null { return false }
if CollectSelection(app, selection_bytes[:]) == 0 || !MimeReady() { return false }
plain := Text.TextFromCString(*selection_bytes[0])
if plain == "" { return false }
html: Vec(u8); BuilderPrint(*html, "<pre>")
for index: cast(s64)0..plain.count - 1 {
byte := plain[index]
if byte == #char "&" { BuilderPrint(*html, "&amp;") }
else if byte == #char "<" { BuilderPrint(*html, "&lt;") }
else if byte == #char ">" { BuilderPrint(*html, "&gt;") }
else if byte == #char "\"" { BuilderPrint(*html, "&quot;") }
else { BuilderPrint(*html, "%", plain[index:index + 1]) }
}
BuilderPrint(*html, "</pre>")
markup := BuilderFinish(html); defer Release(cast(*void)Bytes(markup))
payloads: [3]Mime.MimeClipboardPayload
payloads[0] = Mime.MimeClipboardPayload.{"text/plain;charset=utf-8", ByteView(plain)}
payloads[1] = Mime.MimeClipboardPayload.{"UTF8_STRING", ByteView(plain)}
payloads[2] = Mime.MimeClipboardPayload.{"text/html", ByteView(markup)}
published := Mime.MimeClipboardPublish(payloads[:])
if published.status != Mime.MimeClipboardStatus.Ok { return false }
mime_owner = published.owner
clipboard := Engine.terminal_clipboard(*session.terminal)
return Data.SetClipboardBufferText(clipboard.clipboard, *selection_bytes[0]) != 0
}
SelectAll :: (app: *State.State) { Pane.TerminalPaneClipboardSelectAll(ActiveActions(app)) }
PasteText :: (session: *Session.Session, text: string) {
if session == null || text == "" { return }
if session == null || session.read_only || text == "" { return }
clipboard := Engine.terminal_clipboard(*session.terminal)
if Data.PasteText(clipboard.clipboard, text, clipboard.bracketed_paste,
clipboard.write_text, clipboard.userdata) != 0 { session.scroll_offset = 0 }
}
PasteClipboard :: (session: *Session.Session) { Pane.TerminalPaneClipboardPasteActionsClipboard(Actions(null, session)) }
PasteClipboard :: (session: *Session.Session) {
if session == null || session.read_only { return }
if LocalMimeOwner() {
clipboard := Engine.terminal_clipboard(*session.terminal)
PasteText(session, Text.TextFromCString(Data.GetClipboardBufferText(clipboard.clipboard)))
return
}
Pane.TerminalPaneClipboardPasteActionsClipboard(Actions(null, session))
}
PastePrimary :: (app: *State.State, session: *Session.Session) {
if app != null { Pane.TerminalPaneClipboardPasteActionsPrimary(Actions(app, session)) }
if app != null && session != null && !session.read_only { Pane.TerminalPaneClipboardPasteActionsPrimary(Actions(app, session)) }
}
PastePreferred :: (app: *State.State, session: *Session.Session) {
if app != null { Pane.TerminalPaneClipboardPasteActionsPreferred(Actions(app, session)) }
if app != null && session != null && !session.read_only { Pane.TerminalPaneClipboardPasteActionsPreferred(Actions(app, session)) }
}
Pump :: () {
if MimeReady() { unused Mime.MimeClipboardPump(32) }
if mime_owner != 0 && !LocalMimeOwner() { mime_owner = 0 }
}
SyncFromHost :: (session: *Session.Session) {
Pump()
if !LocalMimeOwner() { Pane.TerminalPaneClipboardActionsSyncFromHost(Actions(null, session)) }
}
SyncFromHost :: (session: *Session.Session) { Pane.TerminalPaneClipboardActionsSyncFromHost(Actions(null, session)) }
FlushToHost :: (session: *Session.Session) { Pane.TerminalPaneClipboardActionsFlushToHost(Actions(null, session)) }
Close :: () {
if mime_open { Mime.MimeClipboardClose() }
if image_bytes != null { Release(cast(*void)image_bytes); image_bytes = null }
mime_open = false; mime_owner = 0
}
+6 -2
View File
@@ -17,6 +17,7 @@ Command :: enum s32 {
Copy :: 1004
Paste :: 1005
PasteImage :: 1043
PastePrimary :: 1044
SelectAll :: 1006
FontIncrease :: 1007
FontDecrease :: 1008
@@ -73,7 +74,10 @@ Execute :: (app: *State.State, command: Command, persist: bool = true) -> bool {
else if command == Command.Quit { app.quit_requested = true }
else if command == Command.Copy { Clipboard.CopySelection(app) }
else if command == Command.Paste { Clipboard.PasteClipboard(session) }
else if command == Command.PasteImage { unused Clipboard.PasteImage(session) }
else if command == Command.PasteImage {
if !Clipboard.PasteImage(session) { Clipboard.PasteClipboard(session) }
}
else if command == Command.PastePrimary { Clipboard.PastePrimary(app, session) }
else if command == Command.SelectAll { Clipboard.SelectAll(app) }
else if command == Command.FontIncrease { SetFontSize(app, app.config.font_size + 1, persist) }
else if command == Command.FontDecrease { SetFontSize(app, app.config.font_size - 1, persist) }
@@ -121,7 +125,7 @@ HandleShortcut :: (app: *State.State, key: s32, modifiers: s32, persist: bool =
else if control && (key == #char "=" || key == 334) { command = Command.FontIncrease }
else if control && (key == #char "-" || key == 333) { command = Command.FontDecrease }
else if control && (key == #char "0" || key == 320) { command = Command.FontReset }
else if shift && key == 260 { command = Command.Paste }
else if shift && key == 260 { command = Command.PastePrimary }
else if control && key == 260 { command = Command.Copy }
else if control && shift && key == #char "C" { command = Command.Copy }
else if control && shift && key == #char "V" { command = Command.Paste }
+186 -22
View File
@@ -1,39 +1,203 @@
#scope_module
State :: #import "app_state";
Sessions :: #import "app_sessions";
Session :: #import "app_session";
Clipboard :: #import "app_clipboard";
Commands :: #import "app_commands";
Menu :: #import "app_menu";
Engine :: #import "terminal";
Frames :: #import "kryon/session";
using UI :: #import "kryon/Widgets";
OpenUri :: #import "kryon/open_uri";
Dialog :: #import "kryon/FileDialogLinux";
File :: #import "std/file_linux";
Text :: #import "std/byte_text_linux";
CString :: #import "std/c_string";
#import "kryon/geometry"
#import "kryon/tree_input"
#import "kryon/key_input"
#import "kryon/input_protocol"
MenuWidget :: #import "kryon/context_menu";
libc :: #system_library "c";
Fork :: () -> s32 #foreign libc "fork";
ExecutePath :: (path: *u8, arguments: **u8) -> s32 #foreign libc "execvp";
ExitChild :: (status: s32) #foreign libc "_exit";
ForegroundGroup :: (descriptor: s32) -> s32 #foreign libc "tcgetpgrp";
SignalProcess :: (pid: s32, number: s32) -> s32 #foreign libc "kill";
PastePrimary :: 2005;
OpenContextLink :: 3001;
CopyContextLink :: 3002;
OpenTerminal :: 3003;
OpenFileManager :: 3004;
CopyHtml :: 3005;
ToggleMenubar :: 3006;
ToggleFullscreen :: 3007;
ToggleReadOnly :: 3008;
SignalMenu :: 3100;
SignalFirst :: 3110;
ZoomMenu :: 3200;
SaveContents :: 3300;
Preferences :: 3301;
Add :: (items: []MenuWidget.ContextMenuItem, at: *s32, id: s32, label: string,
disabled: bool = false, parent: s32 = 0, accelerator: string = "") {
items[at.*] = MenuWidget.ContextMenuItem.{.id=id,.label=label,.disabled=disabled,
.parent=parent,.accelerator=accelerator}
at.* += 1
}
Separator :: (items: []MenuWidget.ContextMenuItem, at: *s32, parent: s32 = 0) {
items[at.*] = MenuWidget.ContextMenuItem.{.separator=true,.parent=parent}
at.* += 1
}
Check :: (items: []MenuWidget.ContextMenuItem, at: *s32, id: s32, label: string, checked: bool) {
items[at.*] = MenuWidget.ContextMenuItem.{.id=id,.label=label,.checkable=true,.checked=checked}
at.* += 1
}
CurrentLink :: (app: *State.State) -> string {
if app == null { return "" }
return Text.TextFromCString(*app.context_link[0])
}
IsEmail :: (link: string) -> bool { return link.count > 7 && link[0:7] == "mailto:" }
SpawnTerminal :: (session: *Session.Session) -> bool {
if session == null { return false }
cwd: [4096]u8; command: [32]u8; option: [32]u8
value := Session.CurrentCwd(session, cwd[:])
if value == "" || !CString.CopyCString("terminal", command[:]) ||
!CString.CopyCString("--working-directory", option[:]) { return false }
arguments: [4]*u8
arguments[0] = *command[0]; arguments[1] = *option[0]
arguments[2] = *cwd[0]; arguments[3] = null
process := Fork()
if process < 0 { return false }
if process == 0 {
unused ExecutePath(*command[0], *arguments[0])
ExitChild(127)
}
return true
}
OpenDirectory :: (session: *Session.Session) -> bool {
if session == null { return false }
cwd: [4096]u8
value := Session.CurrentCwd(session, cwd[:])
return value != "" && OpenUri.OpenUri(value)
}
SendSignal :: (session: *Session.Session, number: s32) -> bool {
if session == null || number < 1 || number > 30 { return false }
group := ForegroundGroup(session.terminal.fd)
if group > 0 && SignalProcess(-group, number) == 0 { return true }
return session.terminal.pid > 0 && SignalProcess(-session.terminal.pid, number) == 0
}
Save :: (session: *Session.Session) -> bool {
if session == null { return false }
cwd: [4096]u8; path: [4096]u8
folder := Session.CurrentCwd(session, cwd[:])
patterns: [1]string = .{"*.txt"}
props: Dialog.FileDialogProps
props.title = "Save Terminal Contents"; props.accept_label = "_Save"
props.filename = "terminal.txt"; props.save = true
props.filter_name = "Text Files"; props.patterns = patterns[:]; props.folder = folder
selected := Dialog.FileDialog(props, path[:])
if !selected.available || !selected.accepted { return false }
file := File.OpenReplace(Text.TextFromCString(*path[0])); if !file.valid { return false }
line: [65536]u8; complete: bool = true
count := Engine.terminal_visible_line_count(*session.terminal)
for row: 0..count - 1 {
Engine.terminal_visible_line(*session.terminal, row, *line[0], 65536)
value := Text.TextFromCString(*line[0])
if value != "" && File.Write(file,
Text.BytesFromPointer(*line[0], cast(u64)value.count)) != value.count {
complete = false; break
}
if Engine.terminal_visible_line_wrapped(*session.terminal, row) == 0 {
newline: [1]u8 = .{10}
if File.Write(file, newline[:]) != 1 { complete = false; break }
}
}
if !File.CloseFile(file) { complete = false }
return complete
}
Activate :: (app: *State.State, session: *Session.Session, id: s32, persist: bool) {
link := CurrentLink(app)
if id == OpenContextLink { unused OpenUri.OpenUri(link) }
else if id == CopyContextLink {
value := link; if IsEmail(link) { value = link[7:] }
unused Clipboard.CopyText(session, value)
}
else if id == OpenTerminal { unused SpawnTerminal(session) }
else if id == OpenFileManager { unused OpenDirectory(session) }
else if id == CopyHtml { unused Clipboard.CopySelectionHtml(app) }
else if id == ToggleMenubar { app.launch.show_menubar = !app.launch.show_menubar }
else if id == ToggleFullscreen {
app.launch.fullscreen = !app.launch.fullscreen; app.fullscreen_toggle_requested = true
}
else if id == ToggleReadOnly { session.read_only = !session.read_only }
else if id > SignalFirst && id <= SignalFirst + 30 { unused SendSignal(session, id - SignalFirst) }
else if id == SaveContents { unused Save(session) }
else if id == Preferences { Menu.OpenPreferences(app) }
else if id > 0 { Commands.Execute(app, cast(Commands.Command)id, persist) }
}
#scope_export
BuildItems :: (app: *State.State, active: *Session.Session,
items: []MenuWidget.ContextMenuItem) -> s32 {
if app == null || active == null || items.count < 57 { return 0 }
at: s32
link := CurrentLink(app)
if link != "" {
Add(items[:], *at, OpenContextLink, ifx IsEmail(link) then "Compose Email" else "Open Link")
Add(items[:], *at, CopyContextLink, ifx IsEmail(link) then "Copy Email Address" else "Copy Link Address")
Separator(items[:], *at)
}
Add(items[:], *at, cast(s32)Commands.Command.NewTab, "Open Tab")
Add(items[:], *at, OpenTerminal, "Open Terminal")
Add(items[:], *at, OpenFileManager, "Open File Manager Here")
Separator(items[:], *at)
Add(items[:], *at, cast(s32)Commands.Command.Copy, "Copy", app.selection.active == 0)
Add(items[:], *at, CopyHtml, "Copy as HTML", app.selection.active == 0)
Separator(items[:], *at)
Add(items[:], *at, cast(s32)Commands.Command.Paste, "Paste")
Add(items[:], *at, cast(s32)Commands.Command.PastePrimary, "Paste Selection", !Clipboard.PrimaryAvailable())
Separator(items[:], *at)
Check(items[:], *at, ToggleMenubar, "Show Menubar", app.launch.show_menubar)
Check(items[:], *at, ToggleFullscreen, "Fullscreen", app.launch.fullscreen)
Check(items[:], *at, ToggleReadOnly, "Read-Only", active.read_only)
Separator(items[:], *at)
Add(items[:], *at, SignalMenu, "Send Signal")
Separator(items[:], *at)
Add(items[:], *at, ZoomMenu, "Zoom")
Separator(items[:], *at)
Add(items[:], *at, SaveContents, "Save Contents...")
Separator(items[:], *at)
Add(items[:], *at, Preferences, "Preferences...")
signals: [30]string = .{"1 - HUP","2 - INT","3 - QUIT","4 - ILL","5 - TRAP","6 - ABRT",
"7 - BUS","8 - FPE","9 - KILL","10 - USR1","11 - SEGV","12 - USR2","13 - PIPE",
"14 - ALRM","15 - TERM","16 - STKFLT","17 - CHLD","18 - CONT","19 - STOP",
"20 - TSTP","21 - TTIN","22 - TTOU","23 - URG","24 - XCPU","25 - XFSZ",
"26 - VTALRM","27 - PROF","28 - WINCH","29 - IO","30 - PWR"}
for number: 1..30 { Add(items[:], *at, SignalFirst + cast(s32)number, signals[number - 1], false, SignalMenu) }
Add(items[:], *at, cast(s32)Commands.Command.FontIncrease, "Zoom In", false, ZoomMenu, "Ctrl++")
Add(items[:], *at, cast(s32)Commands.Command.FontDecrease, "Zoom Out", false, ZoomMenu, "Ctrl+-")
Add(items[:], *at, cast(s32)Commands.Command.FontReset, "Normal Size", false, ZoomMenu, "Ctrl+0")
return at
}
Draw :: (frame: Frames.Session, app: *State.State, persist: bool = true) {
if app == null || !app.context_menu_open { return }
active := Sessions.Active(app)
if active == null { app.context_menu_open = false; return }
items: [11]ContextMenuItem
items[0] = .{cast(s32)Commands.Command.NewTab, "New Tab Ctrl+Shift+T", false, false}
items[1] = .{cast(s32)Commands.Command.CloseTab, "Close Tab Ctrl+Shift+W", app.session_count <= 1, false}
items[2].separator = true
items[3] = .{cast(s32)Commands.Command.Copy, "Copy Ctrl+Shift+C", app.selection.active == 0, false}
items[4] = .{cast(s32)Commands.Command.Paste, "Paste Ctrl+Shift+V", false, false}
items[5] = .{PastePrimary, "Paste Primary", !Clipboard.PrimaryAvailable(), false}
items[6] = .{cast(s32)Commands.Command.SelectAll, "Select All Ctrl+Shift+A", false, false}
items[7].separator = true
items[8] = .{cast(s32)Commands.Command.Find, "Find Ctrl+Shift+F", false, false}
items[9] = .{cast(s32)Commands.Command.FindNext, "Find Next Ctrl+Shift+G", false, false}
items[10] = .{cast(s32)Commands.Command.FindPrevious, "Find Previous Ctrl+Shift+B", false, false}
props: ContextMenuProps
items: [57]MenuWidget.ContextMenuItem
count := BuildItems(app, active, items[:])
if count <= 0 { app.context_menu_open = false; return }
props: MenuWidget.Props
props.key = cast(u64)1300; props.open = app.context_menu_open
props.x = cast(float32)app.context_menu_x; props.y = cast(float32)app.context_menu_y
props.escape = KeyboardTake(frame) == KeyEscape
// An overlay owns this frame's text, including keys it does not handle.
ignored: [128]u8
TypedTextTake(frame, ignored[:])
result := ContextMenu(frame, props, items[:])
props.escape = KeyboardTake(frame) == KeyEscape; props.scale = app.scale
ignored: [128]u8; TypedTextTake(frame, ignored[:])
result := MenuWidget.Draw(frame, props, items[0:count])
app.context_menu_open = result.open
if result.activated_id == PastePrimary { Clipboard.PastePrimary(app, active) }
else if result.activated_id > 0 { Commands.Execute(app, cast(Commands.Command)result.activated_id, persist) }
if result.activated_id > 0 { Activate(app, active, result.activated_id, persist) }
}
+17 -13
View File
@@ -1,14 +1,16 @@
#scope_module
using UI :: #import "kryon/Widgets";
#import "kryon/control_props"
Modal :: #import "kryon/modal";
Button :: #import "kryon/button";
Sessions :: #import "kryon/session";
Fields :: #import "kryon/text_input_props";
Fields :: #import "kryon/text_field";
Text :: #import "std/text_buffer";
Tree :: #import "kryon/tree";
Kinds :: #import "kryon/widget_kind";
#scope_export
// Kryon owns editing policy; Terminal owns the prompt's bounded storage.
ApplyEdit :: (output: []u8, edit: Fields.TextFieldEdit) -> bool {
ApplyEdit :: (output: []u8, edit: Fields.Edit) -> bool {
if !edit.changed || output.count <= 0 || output.count > 1024 { return false }
next: [1024]u8
used: s64
@@ -33,26 +35,28 @@ ApplyEdit :: (output: []u8, edit: Fields.TextFieldEdit) -> bool {
// Zero means no action, one Cancel, two the affirmative action.
Draw :: (session: Sessions.Session, key: u64, title: string, action: string,
output: []u8, cursor: *s32, anchor: *s32, scroll_x: *s32,
focused: *bool, input: Fields.TextFieldInput, scale: float32 = 1.0) -> s32 {
focused: *bool, input: Fields.Input, scale: float32 = 1.0) -> s32 {
if output.count <= 0 || output.count > 1024 || cursor == null || anchor == null ||
scroll_x == null || focused == null { return 0 }
if scale <= 0.0 { scale = 1.0 }
frame_props: ModalFrameProps
frame_props: Modal.Props
frame_props.key = key; frame_props.title = title
frame_props.width = cast(s32)(420.0 * scale); frame_props.height = cast(s32)(160.0 * scale)
frame_props.scale = scale
frame_props.has_right_action = true; frame_props.right_label = "Close"
frame := ModalFrame(session, frame_props)
// A click outside closes the dialog, as the terminal's dialogs always have.
frame_props.dismiss_on_outside = true
frame := Modal.Draw(session, frame_props)
if frame.dismissed || frame.right_clicked { return 1 }
if !frame.opened { return 0 }
edit: Fields.TextFieldEdit
edit: Fields.Edit
replacement: [1024]u8
replacement_count: s64
valid_edit: bool = true
next_cursor: s32; next_anchor: s32; next_scroll: s32
next_focused: bool; committed: bool; escaped: bool
{
field: TextFieldProps
field: Fields.Props
field.key = key + cast(u64)1; field.focus_id = cast(s32)(key + cast(u64)1)
field.bounds = frame.layout.content
field.bounds.height = 32.0 * scale
@@ -66,7 +70,7 @@ Draw :: (session: Sessions.Session, key: u64, title: string, action: string,
previous := Tree.TreePrevious(session, Tree.TreeCurrentParent(session), field.key,
cast(s32)Kinds.WidgetKind.WidgetKindTextField)
field.input.focus = input.focus || (focused.* && previous < 0)
result := TextField(session, field)
result := Fields.Draw(session, field)
next_cursor = result.cursor; next_anchor = result.anchor; next_scroll = result.scroll_x
next_focused = result.focused; committed = result.committed; escaped = result.escaped
edit.changed = result.edit.changed; edit.start = result.edit.start; edit.end = result.edit.end
@@ -87,21 +91,21 @@ Draw :: (session: Sessions.Session, key: u64, title: string, action: string,
cursor.* = next_cursor; anchor.* = next_anchor; scroll_x.* = next_scroll
}
focused.* = next_focused
cancel: ButtonProps
cancel: Button.Props
cancel.key = key + cast(u64)2; cancel.label = "Cancel"
cancel.bounds = frame.layout.content
cancel.bounds.width = 100.0 * scale; cancel.bounds.height = 32.0 * scale
cancel.bounds.y += frame.layout.content.height - cancel.bounds.height
cancel.bounds.x += frame.layout.content.width - cancel.bounds.width * 2.0 - 12.0 * scale
cancel.emphasis = ButtonEmphasis.ButtonEmphasisSoft
cancel_clicked := Button(session, cancel) != 0
cancel_clicked := Button.Draw(session, cancel) != 0
confirm := cancel
confirm.key = key + cast(u64)3; confirm.label = action
confirm.bounds.x += cancel.bounds.width + 12.0 * scale
confirm.emphasis = ButtonEmphasis.ButtonEmphasisFilled
confirm.tone = ButtonTone.ButtonToneAccent
confirm_clicked := Button(session, confirm) != 0
End(session)
confirm_clicked := Button.Draw(session, confirm) != 0
Tree.End(session)
if escaped || cancel_clicked { return 1 }
if committed || confirm_clicked { return 2 }
return 0
+5
View File
@@ -21,6 +21,7 @@ Frames :: #import "kryon/session";
Frame :: #import "kryon/Frame";
Tree :: #import "kryon/tree";
Device :: #import "kryon/tree_input";
Cursor :: #import "kryon/cursor";
Text :: #import "std/text_buffer";
Bytes :: #import "std/byte_text_linux";
using Geometry :: #import "kryon/geometry";
@@ -268,6 +269,9 @@ Draw :: (host: *Host, frame: Frames.Session, bounds: Rectangle,
input.right = Input.ButtonFrame.{}; input.wheel = 0.0
}
result.input = Input.Handle(app, input, host.persist)
if result.input.link_hovered {
unused Cursor.CursorHover(frame, cast(s32)Cursor.CursorShape.CursorClickable)
}
if result.input.wrote > 0 || Input.ModalActive(app) || input.left.down ||
input.middle.down || input.right.down || input.keyboard.mods != 0 {
host.fast_poll_until = device.now + 0.25
@@ -291,6 +295,7 @@ Close :: (host: *Host, session_path: string = "") -> bool {
if host.persist && host.started && host.owns_session && host.app.session_count > 0 {
saved = Tabs.Save(host.app, session_path)
}
Clipboard.Close()
State.Dispose(host.app)
}
host.* = Host.{}
-74
View File
@@ -1,74 +0,0 @@
// The native window reads an explicitly pasted image; no desktop capture.
#scope_module
File :: #import "std/file_linux";
Text :: #import "std/byte_text_linux";
CString :: #import "std/c_string";
Random :: #import "std/random_linux";
Clock :: #import "std/timer_linux";
using V :: #import "std/vec";
gtk :: #system_library "gtk-3";
gdk :: #system_library "gdk-3";
glib :: #system_library "glib-2.0";
libc :: #system_library "c";
Init :: (argc: *s32, argv: ***u8) -> s32 #foreign gtk "gtk_init_check";
Atom :: (name: *u8) -> *void #foreign gdk "gdk_atom_intern_static_string";
Clipboard :: (selection: *void) -> *void #foreign gtk "gtk_clipboard_get";
Received :: #type (clipboard: *void, data: *void, userdata: *void) -> void #c_call;
Request :: (clipboard: *void, target: *void, callback: Received, userdata: *void) #foreign gtk "gtk_clipboard_request_contents";
Data :: (selection: *void) -> *u8 #foreign gtk "gtk_selection_data_get_data";
Length :: (selection: *void) -> s32 #foreign gtk "gtk_selection_data_get_length";
Iterate :: (context: *void, block: s32) -> s32 #foreign glib "g_main_context_iteration";
Allocate :: (size: usize) -> *u8 #foreign libc "malloc";
Release :: (memory: *void) #foreign libc "free";
Environment :: (name: *u8) -> *u8 #foreign libc "getenv";
Rename :: (from: *u8, to: *u8) -> s32 #foreign libc "rename";
Remove :: (path: *u8) -> s32 #foreign libc "remove";
path_bytes: [4096]u8;
generation: usize;
finished: bool;
image: *u8;
image_size: s32;
Bytes :: (value: string) -> *u8 { descriptor:=cast(*Text.TextDescriptor)(*value); return descriptor.data }
Complete :: (clipboard: *void, selection: *void, userdata: *void) {
if cast(usize)userdata!=generation { return }
finished=true; size:=Length(selection); data:=Data(selection)
if data==null || size<8 || size>33554432 { return }
signature: [8]u8=.{137,80,78,71,13,10,26,10}
for i: 0..7 { if data[i]!=signature[i] { return } }
image=Allocate(cast(usize)size); if image==null { return }
for i: 0..size-1 { image[i]=data[i] }; image_size=size
}
#scope_export
Path :: () -> string {
if Init(null,null)==0 { return "" }
generation+=1; finished=false; image=null; image_size=0
callback: Received=Complete
Request(Clipboard(Atom(Bytes("CLIPBOARD"))),Atom(Bytes("image/png")),callback,cast(*void)generation)
deadline:=Clock.MonotonicMilliseconds()+800
while !finished && Clock.MonotonicMilliseconds()<deadline { unused Iterate(null,0); Clock.SleepMilliseconds(1) }
generation+=1
if image==null { return "" }
defer { Release(cast(*void)image); image=null; image_size=0 }
home:=Environment(Bytes("XDG_CACHE_HOME")); root:=ifx home!=null then Text.TextFromCString(home) else ""
out: Vec(u8)
if root=="" { home=Environment(Bytes("HOME")); if home==null { return "" }; BuilderPrint(*out,"%/.cache",Text.TextFromCString(home)) }
else { BuilderPrint(*out,"%",root) }
BuilderPrint(*out,"/terminal/clipboard")
folder:=BuilderFinish(out); defer { Release(cast(*void)Bytes(folder)) }
for i: 1..cast(s32)folder.count-1 { if folder[i]==47 && !File.CreatePrivateDirectory(folder[:i]) { return "" } }
if !File.CreatePrivateDirectory(folder) { return "" }
random: [16]u8; if !Random.FillSecure(random[:]) { return "" }
name: Vec(u8); BuilderPrint(*name,"%/",folder); digits: string="0123456789abcdef"
for byte: random { at:=cast(s32)byte; BuilderPrint(*name,"%",digits[at/16:at/16+1]); BuilderPrint(*name,"%",digits[at%16:at%16+1]) }
BuilderPrint(*name,".png"); path:=BuilderFinish(name); defer { Release(cast(*void)Bytes(path)) }
if !CString.CopyCString(path,path_bytes[:]) { return "" }
file:=File.OpenReplace(path); if !file.valid { return "" }
used: s64
while used<cast(s64)image_size {
count:=File.Write(file,Text.BytesFromPointer(*image[used],cast(u64)(image_size)-cast(u64)used))
if count<=0 { break }; used+=count
}
closed:=File.CloseFile(file)
if !closed || used!=cast(s64)image_size { unused Remove(*path_bytes[0]); return "" }
return Text.TextFromCString(*path_bytes[0])
}
+51 -21
View File
@@ -17,6 +17,7 @@ Frames :: #import "kryon/session";
Geometry :: #import "kryon/geometry";
Text :: #import "std/byte_text_linux";
Links :: #import "terminal_pane_links";
OpenUri :: #import "kryon/open_uri";
#scope_export
ButtonFrame :: struct { down: bool; pressed: bool; released: bool; }
@@ -35,6 +36,7 @@ Frame :: struct {
Result :: struct {
wrote: s32
hyperlink: string
link_hovered: bool
cursor_changed: bool
cursor_hidden: bool
}
@@ -94,6 +96,25 @@ Contains :: (keys: []s32, key: s32) -> bool {
for index: cast(s64)0..keys.count - 1 { if keys[index] == key { return true } }
return false
}
// A plain click leaves the one cell under it selected. That is not text the
// user chose, so it does not count as a selection for right-click.
ChosenSelection :: (app: *State.State) -> bool {
selection := *app.selection
if selection.active == 0 { return false }
return selection.mode != Select.TERMINAL_PANE_SELECTION_CHAR || app.selection_click_count > 1 ||
selection.start_row != selection.end_row || selection.end_col - selection.start_col > 1
}
// Right-click on a selection copies it to CLIPBOARD and clears the highlight.
// PRIMARY keeps its published text. With no selection, or with Shift held, it opens
// the context menu, so menu actions stay reachable while text is selected.
RightClickCopies :: (app: *State.State, keyboard: Keys.KeyboardFrame) -> bool {
if !ChosenSelection(app) || (keyboard.mods & Keys.TERMINAL_PANE_MOD_SHIFT) != 0 { return false }
if !Clipboard.CopySelection(app) { return false }
app.selection.active = 0; app.selection.dragging = 0
return true
}
LinkModifiers :: (keyboard: Keys.KeyboardFrame) -> bool {
if (keyboard.mods & (Keys.TERMINAL_PANE_MOD_ALT | Keys.TERMINAL_PANE_MOD_CTRL)) != 0 { return true }
return Contains(keyboard.keys, 341) || Contains(keyboard.keys, 342) ||
@@ -220,7 +241,7 @@ Sink :: struct { app: *State.State; keys: []s32; wrote: s32; persist: bool; }
Write :: (userdata: *void, value: *u8, length: s32) -> s32 {
sink := cast(*Sink)userdata
session := Sessions.Active(sink.app)
if session == null || value == null || length <= 0 { return 0 }
if session == null || session.read_only || value == null || length <= 0 { return 0 }
replacement: [1]u8
if length == 1 && value[0] == 127 && sink.app.config.backspace_binding == Types.TERMINAL_PANE_KEY_BINDING_CONTROL_H {
replacement[0] = 8; value = *replacement[0]
@@ -276,6 +297,17 @@ Handle :: (app: *State.State, frame: Frame, persist: bool = true) -> Result {
if frame.focused && (frame.keyboard.keys.count > 0 || frame.keyboard.repeated.count > 0 || frame.keyboard.codepoints.count > 0) {
State.ResetCursorBlink(app, frame.now)
}
link_bytes: [8192]u8
target: string
if Inside(app, frame) {
col := cast(s32)((frame.x - app.viewport.x) / cast(float32)app.cell_w)
viewport_row := cast(s32)((frame.y - app.viewport.y) / cast(float32)app.line_h)
if viewport_row >= 0 && viewport_row < app.visible_rows {
target = Links.LinkAt(*session.terminal, null, col,
app.first_visible_row + viewport_row, link_bytes[:])
result.link_hovered = target != ""
}
}
if app.link_pointer_claimed && !frame.left.pressed {
if frame.left.released || !frame.left.down { app.link_pointer_claimed = false }
if frame.focused { result.wrote = PumpKeyboard(app, frame.keyboard, persist) }
@@ -286,17 +318,12 @@ Handle :: (app: *State.State, frame: Frame, persist: bool = true) -> Result {
// click-to-focus. Alt-click must work in full-screen and embedded views too,
// without sending half a click.
if Inside(app, frame) && frame.left.pressed && LinkModifiers(frame.keyboard) {
col := cast(s32)((frame.x - app.viewport.x) / cast(float32)app.cell_w)
viewport_row := cast(s32)((frame.y - app.viewport.y) / cast(float32)app.line_h)
if viewport_row < app.visible_rows {
link_bytes: [8192]u8
target := Links.LinkAt(*session.terminal, null, col, app.first_visible_row + viewport_row, link_bytes[:])
// Copy the detected substring into persistent application storage
// before returning it across the borrowed frame boundary.
if target != "" {
Session.CopyText(app.link_text[:], target)
result.hyperlink = Text.TextFromCString(*app.link_text[0])
}
// Copy the detected substring into persistent application storage
// before returning it across the borrowed frame boundary.
if target != "" {
Session.CopyText(app.link_text[:], target)
result.hyperlink = Text.TextFromCString(*app.link_text[0])
unused OpenUri.OpenUri(result.hyperlink)
}
if result.hyperlink != "" {
app.link_pointer_claimed = !frame.left.released
@@ -311,12 +338,7 @@ Handle :: (app: *State.State, frame: Frame, persist: bool = true) -> Result {
app.keyboard_state = Keys.TerminalPaneInputState.{}
return result
}
if app.selection.active != 0 && Inside(app, frame) &&
(frame.right.down || frame.right.pressed || frame.right.released) {
if frame.right.released && Clipboard.CopySelection(app) {
app.selection.active = 0; app.selection.dragging = 0
}
} else if TerminalMouse(app, session, frame) {
if TerminalMouse(app, session, frame) {
app.selection.active = 0; session.scroll_offset = 0; app.context_menu_open = false
} else {
if Inside(app, frame) && frame.wheel != 0.0 {
@@ -328,10 +350,18 @@ Handle :: (app: *State.State, frame: Frame, persist: bool = true) -> Result {
if consumed { session.scroll_offset = 0 }
else { ScrollBy(app, session, WheelScrollDelta(frame.wheel)) }
}
if session.terminal.mouse_mode == 0 && Inside(app, frame) && frame.middle.pressed { Clipboard.PastePreferred(app, session) }
HandleSelection(app, session, frame)
if session.terminal.mouse_mode == 0 && Inside(app, frame) && frame.middle.pressed { Clipboard.PastePrimary(app, session) }
// A secondary-button gesture owns this frame. It may open the menu,
// and leaves selection changes to the copy action.
if !frame.right.down && !frame.right.pressed && !frame.right.released {
HandleSelection(app, session, frame)
}
if Inside(app, frame) && frame.right.released {
app.context_menu_open = true; app.context_menu_x = cast(s32)frame.x; app.context_menu_y = cast(s32)frame.y
if !RightClickCopies(app, frame.keyboard) {
app.context_menu_open = true; app.context_menu_x = cast(s32)frame.x; app.context_menu_y = cast(s32)frame.y
app.context_link[0] = 0
if target != "" { Session.CopyText(app.context_link[:], target) }
}
}
}
if !app.context_menu_open { result.wrote = PumpKeyboard(app, frame.keyboard, persist) }
+11 -7
View File
@@ -2,13 +2,14 @@
#scope_module
Host :: #import "app_host";
Clipboard :: #import "app_clipboard";
ImageClipboard :: #import "app_image_clipboard";
Runtime :: #import "kryon/Raylib";
Runtime :: #import "kryon/desktop_runtime";
Activity :: #import "kryon/desktop_activity";
View :: #import "app_terminal_view";
Window :: #import "app_window";
Launch :: #import "app_launch_options";
Frames :: #import "kryon/session";
Frame :: #import "kryon/Frame";
InputSnapshot :: #import "kryon/frame_snapshot";
Bytes :: #import "std/byte_text_linux";
Files :: #import "std/file_linux";
libc :: #system_library "c";
@@ -44,12 +45,11 @@ Run :: (arguments: []string) -> s32 {
return Error("Terminal: could not open the graphics window")
}
defer Window.Close()
Clipboard.image_path=ImageClipboard.Path
Window.LoadFont(*host.app.config)
idle := Window.IdleRate(); active := Window.ActiveRate(idle)
host.burst_ms = Window.BurstMilliseconds()
start := Window.Now()
View.prepare_glyphs = Runtime.RaylibPrepareGlyphs
View.prepare_glyphs = Runtime.DesktopPrepareGlyphs
if !Host.Start(*host, Window.Bounds(), start) { return Error("Terminal: could not start Terminal") }
Window.FitGeometry(*host.app.launch, Host.GridWindow(*host, Window.Bounds()))
session := Frames.SessionOpen()
@@ -78,10 +78,10 @@ Run :: (arguments: []string) -> s32 {
remaining := next_tick - now
if remaining > HostPollSeconds { remaining = HostPollSeconds }
woke := Window.Wait(shells[0:Host.Descriptors(*host, shells[:])], remaining)
if woke == Runtime.RaylibActivityUnsupported { waits = false }
if woke == Activity.DesktopActivityUnsupported { waits = false }
else {
// A frame reads input at its end and uses it in the next.
if woke == Runtime.RaylibActivityInput { input_frames = 2 }
if woke == Activity.DesktopActivityInput { input_frames = 2 }
continue
}
}
@@ -90,18 +90,22 @@ Run :: (arguments: []string) -> s32 {
Window.Begin()
bounds := Window.Bounds()
down: [512]s32
unused Runtime.DesktopFrameInputBegin(session)
device := Window.Sample(session, now, down[:])
if cast(s32)Host.BeginFrame(*host, session, cast(u64)1, bounds, device.focused) != 0 {
InputSnapshot.FrameInputEnd(session)
Window.End()
return Error("Terminal: could not begin a UI frame")
}
result := Host.Draw(*host, session, bounds, device)
next_tick = View.NextTick(host.app, now)
if cast(s32)Frame.EndFrame(session) != 0 {
InputSnapshot.FrameInputEnd(session)
Window.End()
return Error("Terminal: could not draw the UI frame")
}
Window.Apply(result.input)
InputSnapshot.FrameInputEnd(session)
Window.Apply(result.input, host.app)
if result.font_changed { Window.LoadFont(*host.app.config) }
if result.title_changed { Window.Title(Host.Title(*host)) }
captured: bool
+31 -25
View File
@@ -4,34 +4,40 @@ Commands :: #import "app_commands";
Engine :: #import "terminal";
Keys :: #import "terminal_pane_keys";
Frames :: #import "kryon/session";
Menus :: #import "kryon/menu_props";
using UI :: #import "kryon/Widgets";
Menus :: #import "kryon/menu";
#import "kryon/geometry"
#import "kryon/tree_input"
#import "kryon/key_input"
#import "kryon/input_protocol"
#scope_file
Item :: (command: Commands.Command, label: string, accelerator: string = "") -> MenuItem {
result: MenuItem
Item :: (command: Commands.Command, label: string, accelerator: string = "") -> Menus.MenuItem {
result: Menus.MenuItem
result.id = cast(s32)command; result.label = label; result.accelerator = accelerator
return result
}
Open :: (app: *State.State, index: s32) {
MenuStateInit(*app.menu)
Menus.MenuStateInit(*app.menu)
app.menu.open_index = index; app.menu.top_index = index
app.menu.focused = true; app.menu.reveal = true
}
#scope_export
OpenPreferences :: (app: *State.State) {
if app != null { Open(app, 3) }
}
// Physical app shortcuts are consumed before terminal protocol encoding.
// Repeats belong to the shortcut but do not toggle the menu repeatedly.
HandleShortcut :: (app: *State.State, key: s32, mods: s32, fresh: bool = true) -> bool {
if app == null { return false }
if key == 290 && app.config.disable_help_shortcut == 0 {
if fresh { MenuStateInit(*app.menu); app.about_visible = true }
if fresh { Menus.MenuStateInit(*app.menu); app.about_visible = true }
return true
}
if !app.launch.show_menubar { return false }
if key == 299 && app.config.disable_menu_shortcut == 0 {
if fresh {
if app.menu.focused || app.menu.open_index >= 0 { MenuStateInit(*app.menu) }
if app.menu.focused || app.menu.open_index >= 0 { Menus.MenuStateInit(*app.menu) }
else { app.menu.focused = true }
}
return true
@@ -53,8 +59,8 @@ HandleShortcut :: (app: *State.State, key: s32, mods: s32, fresh: bool = true) -
Draw :: (frame: Frames.Session, app: *State.State, bounds: Rectangle,
persist: bool = true, fresh: bool = true) {
if app == null { return }
if !app.launch.show_menubar { MenuStateInit(*app.menu); return }
props: MenuProps
if !app.launch.show_menubar { Menus.MenuStateInit(*app.menu); return }
props: Menus.Props
props.key = cast(u64)1200; props.bounds = bounds; props.scale = app.scale
owned := app.menu.focused || app.menu.open_index >= 0
if owned {
@@ -71,33 +77,33 @@ Draw :: (frame: Frames.Session, app: *State.State, bounds: Rectangle,
props.input.escape = key == KeyEscape
}
}
file: [4]MenuItem
file: [4]Menus.MenuItem
file[0] = Item(Commands.Command.NewTab, "New Tab", "Ctrl+Shift+T")
file[1] = Item(Commands.Command.CloseTab, "Close Tab", "Ctrl+Shift+W")
file[2].kind = MenuItemKind.MenuSeparator
file[2].kind = Menus.MenuItemKind.MenuSeparator
file[3] = Item(Commands.Command.Quit, "Quit", "Ctrl+Shift+Q")
edit: [7]MenuItem
edit: [7]Menus.MenuItem
edit[0] = Item(Commands.Command.Copy, "Copy", "Ctrl+Shift+C")
edit[1] = Item(Commands.Command.Paste, "Paste", "Ctrl+Shift+V")
edit[2] = Item(Commands.Command.SelectAll, "Select All", "Ctrl+Shift+A")
edit[3].kind = MenuItemKind.MenuSeparator
edit[3].kind = Menus.MenuItemKind.MenuSeparator
edit[4] = Item(Commands.Command.Find, "Find", "Ctrl+Shift+F")
edit[5] = Item(Commands.Command.FindNext, "Find Next", "Ctrl+Shift+G")
edit[6] = Item(Commands.Command.FindPrevious, "Find Previous", "Ctrl+Shift+B")
view: [3]MenuItem
view: [3]Menus.MenuItem
view[0] = Item(Commands.Command.FontIncrease, "Zoom In", "Ctrl++")
view[1] = Item(Commands.Command.FontDecrease, "Zoom Out", "Ctrl+-")
view[2] = Item(Commands.Command.FontReset, "Normal Size", "Ctrl+0")
cursor: [3]MenuItem
cursor: [3]Menus.MenuItem
cursor[0] = Item(Commands.Command.CursorBlock, "Block")
cursor[1] = Item(Commands.Command.CursorUnderline, "Underline")
cursor[2] = Item(Commands.Command.CursorBar, "Bar")
for index: 0..2 { cursor[index].kind = MenuItemKind.MenuRadio }
for index: 0..2 { cursor[index].kind = Menus.MenuItemKind.MenuRadio }
cursor[0].checked = app.config.cursor_style == Engine.TERMINAL_CURSOR_BLOCK
cursor[1].checked = app.config.cursor_style == Engine.TERMINAL_CURSOR_UNDERLINE
cursor[2].checked = app.config.cursor_style == Engine.TERMINAL_CURSOR_BAR
terminal: [29]MenuItem
terminal[0] = file[0]; terminal[1] = edit[1]; terminal[2].kind = MenuItemKind.MenuSeparator
terminal: [29]Menus.MenuItem
terminal[0] = file[0]; terminal[1] = edit[1]; terminal[2].kind = Menus.MenuItemKind.MenuSeparator
terminal[3] = Item(Commands.Command.ProfileShell, "Shell...")
terminal[4] = Item(Commands.Command.ProfileCwd, "Working Directory...")
terminal[5] = Item(Commands.Command.ProfileFontFile, "Terminal Font...")
@@ -108,8 +114,8 @@ Draw :: (frame: Frames.Session, app: *State.State, bounds: Rectangle,
terminal[10] = Item(Commands.Command.ProfileCursorColor, "Cursor Color...")
terminal[11] = Item(Commands.Command.ProfileSelectionForeground, "Selection Foreground...")
terminal[12] = Item(Commands.Command.ProfileSelectionBackground, "Selection Background...")
terminal[13].kind = MenuItemKind.MenuSubmenu; terminal[13].label = "Cursor Style"; terminal[13].submenu = cursor[:]
terminal[14].kind = MenuItemKind.MenuSeparator
terminal[13].kind = Menus.MenuItemKind.MenuSubmenu; terminal[13].label = "Cursor Style"; terminal[13].submenu = cursor[:]
terminal[14].kind = Menus.MenuItemKind.MenuSeparator
terminal[15] = Item(Commands.Command.ProfileDynamicTitleMode, "Dynamic Title Mode...")
terminal[16] = Item(Commands.Command.ProfileBackspaceBinding, "Backspace Key...")
terminal[17] = Item(Commands.Command.ProfileDeleteBinding, "Delete Key...")
@@ -124,17 +130,17 @@ Draw :: (frame: Frames.Session, app: *State.State, bounds: Rectangle,
terminal[26] = Item(Commands.Command.ProfileDisableHelpShortcut, "Disable F1 Help Shortcut...")
terminal[27] = Item(Commands.Command.ProfileBackgroundOpacity, "Background Opacity...")
terminal[28] = Item(Commands.Command.ProfileBackgroundImage, "Background Image...")
tabs: [5]MenuItem
tabs[0] = file[0]; tabs[1] = file[1]; tabs[2].kind = MenuItemKind.MenuSeparator
tabs: [5]Menus.MenuItem
tabs[0] = file[0]; tabs[1] = file[1]; tabs[2].kind = Menus.MenuItemKind.MenuSeparator
tabs[3] = Item(Commands.Command.NextTab, "Next Tab", "Ctrl+Tab")
tabs[4] = Item(Commands.Command.PreviousTab, "Previous Tab", "Ctrl+Shift+Tab")
help: [1]MenuItem
help: [1]Menus.MenuItem
help[0] = Item(Commands.Command.About, "About Terminal")
groups: [6]MenuGroup
groups: [6]Menus.MenuGroup
groups[0] = .{"File", file[:]}; groups[1] = .{"Edit", edit[:]}
groups[2] = .{"View", view[:]}; groups[3] = .{"Terminal", terminal[:]}
groups[4] = .{"Tabs", tabs[:]}; groups[5] = .{"Help", help[:]}
result := Menu(frame, props, groups[:], *app.menu)
result := Menus.Draw(frame, props, groups[:], *app.menu)
if owned || app.menu.focused || app.menu.open_index >= 0 {
ignored: [128]u8
TypedTextTake(frame, ignored[:])
+6 -4
View File
@@ -5,7 +5,9 @@ Engine :: #import "terminal";
Pane :: #import "terminal_pane_selection";
Dialog :: #import "app_dialog";
Text :: #import "std/text_buffer";
using UI :: #import "kryon/Widgets";
UI :: #import "kryon/key_input";
Keys :: #import "kryon/tree_input";
Codes :: #import "kryon/input_protocol";
Frames :: #import "kryon/session";
#scope_export
@@ -31,9 +33,9 @@ Find :: (app: *State.State) -> bool {
}
Draw :: (session: Frames.Session, app: *State.State) {
if app == null || !app.search_visible { return }
key := UI.KeyboardTake(session)
modifiers := UI.KeyboardModifiers(session)
if (modifiers & UI.KeyModifierControl) != 0 && (modifiers & UI.KeyModifierShift) != 0 {
key := Keys.KeyboardTake(session)
modifiers := Keys.KeyboardModifiers(session)
if (modifiers & Codes.KeyModifierControl) != 0 && (modifiers & Codes.KeyModifierShift) != 0 {
if key == #char "G" { FindDirection(app, 1); app.search_focused = true }
else if key == #char "B" { FindDirection(app, -1); app.search_focused = true }
}
+34 -1
View File
@@ -5,6 +5,7 @@ Pane :: #import "terminal_pane_session";
Types :: #import "terminal_pane_profile_types";
Text :: #import "std/byte_text_linux";
Numbers :: #import "std/number_text";
Files :: #import "std/file_linux";
libc :: #system_library "c";
EnvironmentHost :: (name: *s8) -> *s8 #foreign libc "getenv";
HostnameHost :: (output: *s8, capacity: usize) -> s32 #foreign libc "gethostname";
@@ -74,6 +75,35 @@ SetShellTitle :: (session: *Session, value: string) -> bool {
return true
}
// A launcher can name a folder that is gone, a file, or a path carrying its
// own shell quotes. The shell could not enter it and the window would close,
// so start in the home folder instead and say why.
StartDirectory :: (requested: string, output: []u8) -> string {
if requested == "" || Files.DirectoryExists(requested) { return CopyText(output, requested) }
home: [1024]u8
fallback := Environment("HOME", home[:])
if fallback == "" || !Files.DirectoryExists(fallback) { fallback = "/" }
return CopyText(output, fallback)
}
// The path is quoted, so quotes that are part of it stay visible.
ReportStartDirectory :: (session: *Session, requested: string, started: string) {
notice: [2304]u8
used: s64
Append(notice[:], *used, "Terminal: working directory \"")
Append(notice[:], *used, requested)
Append(notice[:], *used, ifx Files.PathExists(requested) then "\" is not a folder" else "\" does not exist")
Append(notice[:], *used, "; starting in ")
Append(notice[:], *used, started)
Append(notice[:], *used, "\n")
// One line for the launcher's log, and the same notice above the prompt.
diagnostic: Files.FileHandle = .{2, true}
Files.Write(diagnostic, notice[0:used])
Engine.terminal_feed(*session.terminal, cast(*void)(*notice[0]), cast(s32)(used - 1))
ending := "\r\n"
Engine.terminal_feed(*session.terminal, cast(*void)Bytes(ending), cast(s32)ending.count)
}
#scope_export
Session :: struct {
terminal: Engine.Terminal
@@ -84,6 +114,7 @@ Session :: struct {
command: [1024]u8
title: [128]u8
title_override: bool
read_only: bool
initialized: bool
}
@@ -144,13 +175,15 @@ Open :: (session: *Session, cwd: string, shell: string, command: string,
CopyText(directory[:], cwd); CopyText(executable[:], shell); CopyText(script[:], command)
Close(session)
Init(session)
CopyText(session.cwd[:], Text.TextFromCString(*directory[0]))
requested := Text.TextFromCString(*directory[0])
started := StartDirectory(requested, session.cwd[:])
CopyText(session.shell[:], Text.TextFromCString(*executable[0]))
CopyText(session.command[:], Text.TextFromCString(*script[0]))
SetDefaultTitle(session)
opened := Engine.terminal_spawn(*session.terminal, *session.cwd[0],
*session.shell[0], *session.command[0], cols, rows) != 0
Engine.terminal_set_scrollback_limit(*session.terminal, scrollback_limit)
if started != requested { ReportStartDirectory(session, requested, started) }
if !opened {
message := "Could not start shell\r\n"
Engine.terminal_feed(*session.terminal, cast(*void)Bytes(message), cast(s32)message.count)
+3 -1
View File
@@ -7,7 +7,7 @@ Sessions :: #import "app_session";
Selection :: #import "terminal_pane_selection";
Mouse :: #import "terminal_pane_mouse";
Keys :: #import "terminal_pane_keys";
Menus :: #import "kryon/menu_props";
Menus :: #import "kryon/menu";
#scope_file
libc :: #system_library "c";
@@ -60,6 +60,7 @@ State :: struct {
mouse_report_x: s32
mouse_report_y: s32
link_text: [8192]u8
context_link: [8192]u8
link_pointer_claimed: bool
mouse_report_button: s32
selection_click_time: float64
@@ -69,6 +70,7 @@ State :: struct {
context_menu_open: bool
context_menu_x: s32
context_menu_y: s32
fullscreen_toggle_requested: bool
keyboard_state: Keys.TerminalPaneInputState
mouse_hidden: bool
last_mouse_x: s32
+28 -17
View File
@@ -1,5 +1,13 @@
#scope_module
using UI :: #import "kryon/Widgets";
#import "kryon/geometry"
#import "kryon/drawing_props"
#import "kryon/tree_input"
#import "kryon/key_input"
#import "kryon/input_protocol"
Image :: #import "kryon/image";
TabBar :: #import "kryon/tab_bar";
Modal :: #import "kryon/modal";
Label :: #import "kryon/text";
Frames :: #import "kryon/session";
Paint :: #import "kryon/paint_queue";
Geometry :: #import "kryon/geometry";
@@ -55,22 +63,22 @@ ColorFor :: (app: *State.State, terminal: *Engine.Terminal,
BackgroundImage :: (frame: Frames.Session, app: *State.State, viewport: Rectangle) {
path := Text.TextUntilNul(app.config.background_image[:])
if path == "" || viewport.width <= 0.0 || viewport.height <= 0.0 { return }
props: ImageProps
props: Image.Props
props.key = cast(u64)1401; props.asset_path = path
props.bounds = viewport; props.fit = ImageFit.ImageFitCover
Image(frame, props)
props.bounds = viewport; props.fit = Image.ImageFit.ImageFitCover
Image.Draw(frame, props)
}
DrawTabs :: (frame: Frames.Session, app: *State.State, bounds: Rectangle,
input: ViewInput) {
if !Chrome.TabBarVisible(app) { return }
tabs: [8]Tab
tabs: [8]TabBar.Tab
for index: 0..app.session_count - 1 {
tabs[index].key = cast(u64)(1500 + index)
tabs[index].label = Records.Title(*app.sessions[index])
tabs[index].closeable = app.session_count > 1
}
props: TabBarProps
props: TabBar.Props
props.key = cast(u64)1500; props.bounds = bounds; props.scale = app.scale
props.selected_index = app.active
props.min_tab_width = cast(s32)(72.0 * app.scale)
@@ -84,7 +92,7 @@ DrawTabs :: (frame: Frames.Session, app: *State.State, bounds: Rectangle,
props.input.now = cast(float32)input.now
props.input.middle_click = input.middle_pressed
props.input.middle_x = input.middle_x; props.input.middle_y = input.middle_y
result := TabBar(frame, props, tabs[0:app.session_count])
result := TabBar.Draw(frame, props, tabs[0:app.session_count])
app.tab_scroll = result.scroll_offset
app.tab_dragging = result.dragging; app.tab_drag_from = result.drag_from
app.tab_last_clicked_index = result.last_clicked_index
@@ -252,13 +260,13 @@ DrawDialogs :: (frame: Frames.Session, app: *State.State, persist: bool) -> bool
key := KeyboardTake(frame)
ignored: [128]u8
TypedTextTake(frame, ignored[:])
props: ActionModalProps
props: Modal.ActionModalProps
props.key = cast(u64)9100; props.title = "Terminal"
props.message = "A Kryon terminal application."; props.scale = app.scale
props.show_close = true; props.close_label = "Close"
actions: [1]ActionModalAction
actions: [1]Modal.ActionModalAction
actions[0].key = cast(u64)9101; actions[0].label = "OK"
result := ActionModal(frame, props, actions[:])
result := Modal.ActionModal(frame, props, actions[:])
if result.action != 0 || key == KeyEscape || key == KeyEnter { app.about_visible = false }
}
Search.Draw(frame, app)
@@ -322,10 +330,6 @@ Draw :: (frame: Frames.Session, app: *State.State, bounds: Rectangle,
if app == null || !Frames.SessionValid(frame) || !Tree.TreeIsBuilding(frame) { return result }
Paint.PaintRoundedFill(frame, Tree.TreeCurrentParent(frame), bounds, 0.0, 0, Opaque(app.palette.background))
menu_h := Chrome.MenuBarHeight(app)
if menu_h > 0 {
Menu.Draw(frame, app, Rectangle.{bounds.x, bounds.y, bounds.width, cast(float32)menu_h},
persist, input.menu_key_fresh)
}
tab_h := Chrome.TabBarHeight(app)
if tab_h > 0 {
DrawTabs(frame, app, Rectangle.{bounds.x, bounds.y + cast(float32)menu_h,
@@ -341,12 +345,12 @@ Draw :: (frame: Frames.Session, app: *State.State, bounds: Rectangle,
if active == null {
Paint.PaintRoundedFill(frame, result.node, viewport, 0.0, 0,
Opacity(theme.background, app.config.background_opacity))
props: TextProps
props: Label.Props
props.key = cast(u64)1402; props.text = "Starting terminal..."
props.bounds = Rectangle.{viewport.x + 10.0, viewport.y + 10.0,
viewport.width - 20.0, 24.0 * app.scale}
props.font = app.config.font_size; props.wrap = TextWrap.TextWrapNone
UI.Text(frame, props)
props.size = app.config.font_size; props.wrap = Label.Wrap.TextWrapNone
Label.Draw(frame, props)
} else {
terminal := *active.terminal
Profile.SeedMissing(*app.config, *app.palette, terminal)
@@ -383,6 +387,13 @@ Draw :: (frame: Frames.Session, app: *State.State, bounds: Rectangle,
.{viewport, active.scroll_offset, cast(s32)(13.0 * app.scale), theme}, app.scale)
}
}
// Kryon menus are submitted after the page content: their dropdown and
// submenu panels must paint above, and take pointer input over, the tabs
// and terminal pane. Dialogs and the context menu still stack on top.
if menu_h > 0 {
Menu.Draw(frame, app, Rectangle.{bounds.x, bounds.y, bounds.width, cast(float32)menu_h},
persist, input.menu_key_fresh)
}
result.font_changed = DrawDialogs(frame, app, persist)
return result
}
+98 -78
View File
@@ -1,6 +1,7 @@
// OS device facts and owned-window operations. Terminal behavior is in app_host.
#scope_module
Host :: #import "app_host";
AppState :: #import "app_state";
Launch :: #import "app_launch_options";
Profile :: #import "terminal_pane_profile_types";
Input :: #import "app_input";
@@ -15,23 +16,17 @@ Environment :: (name: *s8) -> *s8 #foreign libc "getenv";
MemoryCopy :: (target: *void, source: *void, count: usize) -> *void #foreign libc "memcpy";
DlOpen :: (name: *u8, flags: s32) -> *void #foreign dl "dlopen";
DlSymbol :: (handle: *void, name: *u8) -> *void #foreign dl "dlsym";
Runtime :: #import "kryon/Raylib";
Runtime :: #import "kryon/desktop_runtime";
WindowState :: #import "kryon/desktop_window_state";
Keys :: #import "kryon/desktop_keyboard";
Activity :: #import "kryon/desktop_activity";
Typefaces :: #import "kryon/cairo_typefaces";
Raster :: #import "kryon/Cairo";
Files :: #import "std/file_linux";
Clock :: #import "std/timer_linux";
raylib :: #system_library "raylib";
sdl :: #system_library "SDL2";
SetTraceLevel :: (level: s32) #foreign raylib "SetTraceLogLevel";
Maximize :: () #foreign raylib "MaximizeWindow";
Fullscreen :: () #foreign raylib "ToggleFullscreen";
SetWindowSize :: (width: s32, height: s32) #foreign raylib "SetWindowSize";
SetWindowPosition :: (x: s32, y: s32) #foreign raylib "SetWindowPosition";
CurrentMonitor :: () -> s32 #foreign raylib "GetCurrentMonitor";
MonitorWidth :: (monitor: s32) -> s32 #foreign raylib "GetMonitorWidth";
MonitorHeight :: (monitor: s32) -> s32 #foreign raylib "GetMonitorHeight";
MonitorPosition :: (monitor: s32) -> Geometry.Vector2 #foreign raylib "GetMonitorPosition";
ShowCursor :: () #foreign raylib "ShowCursor";
HideCursor :: () #foreign raylib "HideCursor";
OpenURL :: (value: *u8) -> s32 #foreign sdl "SDL_OpenURL";
PlaceWindow :: (window: *void, x: s32, y: s32) #foreign sdl "SDL_SetWindowPosition";
CursorShown :: (toggle: s32) -> s32 #foreign sdl "SDL_ShowCursor";
VideoError :: () -> *u8 #foreign sdl "SDL_GetError";
ModState :: () -> u32 #foreign sdl "SDL_GetModState";
KeyboardFocus :: () -> *void #foreign sdl "SDL_GetKeyboardFocus";
@@ -43,10 +38,8 @@ FnQueryPointer :: #type (*void, u64, *u64, *u64, *s32, *s32, *s32, *s32, *u32) -
x_display: *void;
x_window: u64;
x_query_pointer: FnQueryPointer;
DroppedFiles :: struct { count: u32; paths: **u8; }
HasDroppedFiles :: () -> bool #foreign raylib "IsFileDropped";
LoadDroppedFiles :: () -> DroppedFiles #foreign raylib "LoadDroppedFiles";
UnloadDroppedFiles :: (files: DroppedFiles) #foreign raylib "UnloadDroppedFiles";
ShowCursor :: () { unused CursorShown(1) }
HideCursor :: () { unused CursorShown(0) }
BindX11 :: () {
x_display = null; x_window = 0
@@ -111,15 +104,12 @@ Number :: (name: string, fallback: s32, maximum: s32) -> s32 {
}
#scope_export
// Raylib owns the OS drop payload until UnloadDroppedFiles.
// The desktop host hands over one dropped path at a time.
Drops :: (host: *Host.Host) -> bool {
if !HasDroppedFiles() { return false }
files := LoadDroppedFiles()
defer UnloadDroppedFiles(files)
accepted: bool
if files.paths == null { return false }
for index: 0..cast(s32)files.count-1 {
if files.paths[index] != null && Host.DropPath(host, Text.TextFromCString(files.paths[index])) { accepted = true }
path: [4096]u8
while Runtime.DesktopTakeDroppedFile(path[:]) {
if Host.DropPath(host, Text.TextFromCString(*path[0])) { accepted = true }
}
return accepted
}
@@ -157,20 +147,20 @@ BurstMilliseconds :: () -> s32 {
return Number("KTREM_PTY_BURST_MS", fallback, 20)
}
Rate :: (fps: s32) {
Runtime.RaylibFrameRate(fps)
unused Runtime.DesktopFrameRate(fps)
}
ForwardToRill :: () -> bool {
return false
}
Title :: (title: string) -> bool {
return Runtime.RaylibSetTitle(title)
return Runtime.DesktopSetTitle(title)
}
Open :: (launch: *Launch.LaunchOptions) -> bool {
flags: u32 = cast(u32)4
if launch.drop_down { flags |= cast(u32)(8 | 4096 | 256) }
else if !launch.show_borders { flags |= cast(u32)8 }
SetTraceLevel(4)
if !Runtime.OpenRaylib(Width(launch), Height(launch), "Terminal", flags) {
flags := cast(u32)Runtime.DesktopWindowResizable
if launch.drop_down {
flags |= cast(u32)(Runtime.DesktopWindowUndecorated | Runtime.DesktopWindowTopmost | Runtime.DesktopWindowAlwaysRun)
} else if !launch.show_borders { flags |= cast(u32)Runtime.DesktopWindowUndecorated }
if !Runtime.OpenDesktopWindow(Width(launch), Height(launch), "Terminal", flags) {
failure := Text.TextFromCString(VideoError())
if failure != "" {
diagnostic: Files.FileHandle = .{2, true}
@@ -179,21 +169,20 @@ Open :: (launch: *Launch.LaunchOptions) -> bool {
}
return false
}
Runtime.RaylibExitKey(0)
unused Runtime.DesktopExitKey(0)
BindX11()
if launch.drop_down {
monitor := CurrentMonitor()
width := MonitorWidth(monitor); height := MonitorHeight(monitor)
monitor := WindowState.DesktopMonitorBounds()
width := cast(s32)monitor.width; height := cast(s32)monitor.height
if width <= 0 { width = Width(launch) }
if height > 0 { height = height * 45 / 100 } else { height = 420 }
if height < 280 { height = 280 }
if height > 720 { height = 720 }
origin := MonitorPosition(monitor)
SetWindowSize(width, height)
SetWindowPosition(cast(s32)origin.x, cast(s32)origin.y)
unused Runtime.ResizeDesktop(width, height)
PlaceWindow(Runtime.DesktopWindow(), cast(s32)monitor.x, cast(s32)monitor.y)
} else {
if launch.maximize { Maximize() }
if launch.fullscreen { Fullscreen() }
if launch.maximize { unused WindowState.DesktopMaximize() }
if launch.fullscreen { unused WindowState.DesktopToggleFullscreen() }
}
return true
}
@@ -202,91 +191,122 @@ Open :: (launch: *Launch.LaunchOptions) -> bool {
FitGeometry :: (launch: *Launch.LaunchOptions, size: Geometry.Vector2) {
if launch == null || launch.drop_down || launch.fullscreen || launch.maximize ||
launch.geometry_cols <= 0 || launch.geometry_rows <= 0 || size.x <= 0.0 || size.y <= 0.0 { return }
SetWindowSize(cast(s32)size.x, cast(s32)size.y)
unused Runtime.ResizeDesktop(cast(s32)size.x, cast(s32)size.y)
}
Close :: () {
x_display = null; x_window = 0
ShowCursor(); Runtime.CloseRaylib()
ShowCursor(); Runtime.CloseDesktop()
}
LoadFont :: (config: *Profile.TerminalPaneProfileSettings) -> bool {
path := Text.TextFromCString(*config.terminal_font[0])
if path != "" && Runtime.LoadTypefaceFile("Terminal", path, null, 0) {
return Runtime.SelectTypeface("Terminal")
if path != "" && Typefaces.LoadTypefaceFile("Terminal", path, null, 0) {
return Typefaces.SelectTypeface("Terminal")
}
paths: [3]string = .{"/usr/share/fonts/truetype/noto/NotoSansMono-Regular.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
"/usr/share/fonts/opentype/urw-base35/NimbusMonoPS-Regular.otf"}
for index: 0..2 {
if Runtime.LoadTypefaceFile("Terminal", paths[index], null, 0) {
return Runtime.SelectTypeface("Terminal")
if Typefaces.LoadTypefaceFile("Terminal", paths[index], null, 0) {
return Typefaces.SelectTypeface("Terminal")
}
}
return false
}
// Each desktop poll reports only its own button edges and wheel steps, and
// the loop polls several times per frame while it waits on the shells: keep
// them until the frame that reads them.
Edges :: struct { pressed: bool; released: bool; }
pending_left: Edges;
pending_right: Edges;
pending_middle: Edges;
pending_wheel: float32;
// Where the first press since the last frame happened, so a drag that moved
// on before the frame still starts at the pressed cell.
pending_press: bool;
pending_press_x: float32;
pending_press_y: float32;
Gather :: () {
left := Runtime.PollPointer(); right := Runtime.PollSecondaryPointer(); middle := Runtime.PollMiddlePointer()
if !pending_press && (left.pressed || right.pressed || middle.pressed) {
pending_press = true; pending_press_x = left.x; pending_press_y = left.y
}
pending_left.pressed = pending_left.pressed || left.pressed
pending_left.released = pending_left.released || left.released
pending_right.pressed = pending_right.pressed || right.pressed
pending_right.released = pending_right.released || right.released
pending_middle.pressed = pending_middle.pressed || middle.pressed
pending_middle.released = pending_middle.released || middle.released
pending_wheel += Runtime.DesktopWheelMove()
}
Poll :: () -> bool {
return Runtime.PollRaylib()
alive := Runtime.PollDesktop()
Gather()
return alive
}
// Sleeps without drawing until a shell writes or window input arrives.
Wait :: (descriptors: []s32, seconds: float64) -> s32 {
return Runtime.RaylibWaitForActivity(descriptors, cast(s32)(seconds * 1000.0) + 1)
return Activity.DesktopWaitForActivity(descriptors, cast(s32)(seconds * 1000.0) + 1)
}
Bounds :: () -> Geometry.Rectangle {
return Runtime.RaylibViewport()
return Runtime.DesktopViewport()
}
Begin :: () {
Runtime.BeginRaylibFrame()
Runtime.BeginDesktopFrame()
}
End :: () -> bool {
return Runtime.EndRaylibFrame()
return Runtime.EndDesktopFrame()
}
CaptureRequested :: () -> bool { return Runtime.CaptureRequested() }
Capture :: () -> bool { return Runtime.CaptureConfigured() }
CaptureRequested :: () -> bool { return Raster.CaptureRequested() }
Capture :: () -> bool { return Raster.CaptureConfigured() }
Sample :: (session: Frames.Session, now: float64, down: []s32) -> Host.DeviceFrame {
result: Host.DeviceFrame
result.now = now; result.key_fresh = true
// The edges every poll since the last frame saw; a press released again
// before this frame still counts as held, so it reaches the cell under it.
pointer := Runtime.PollPointer()
pointer.pressed = pending_left.pressed; pointer.released = pending_left.released
if pointer.pressed { pointer.down = true }
secondary := Runtime.PollSecondaryPointer()
secondary.pressed = pending_right.pressed; secondary.released = pending_right.released
if secondary.pressed { secondary.down = true }
middle := Runtime.PollMiddlePointer()
middle.pressed = pending_middle.pressed; middle.released = pending_middle.released
if middle.pressed { middle.down = true }
if pending_press { pointer.x = pending_press_x; pointer.y = pending_press_y }
wheel := pending_wheel
pending_left = .{}; pending_right = .{}; pending_middle = .{}; pending_wheel = 0.0
pending_press = false
result.middle = .{middle.down, middle.pressed, middle.released}
Device.TreePointerUpdate(session, pointer)
Device.TreeSecondaryPointerUpdate(session, Runtime.PollSecondaryPointer())
result.focused = Runtime.RaylibFocused()
Device.PointerWheelSend(session, pointer.x, pointer.y, Runtime.RaylibWheelMove())
// A modifier press must not consume the frame's key and discard a following
// shortcut. It still counts when released again within this same frame.
modifiers := Runtime.RaylibModifiers() | SDLModifiers(ModState())
Device.TreeSecondaryPointerUpdate(session, secondary)
result.focused = Runtime.WindowFocusedHost()
Device.PointerWheelSend(session, pointer.x, pointer.y, wheel)
// Kryon preserves key/text arrival order and attaches the modifiers held
// for the key when it was observed.
key, modifiers := Runtime.DesktopInputTake(session)
modifiers |= SDLModifiers(ModState())
if pointer.pressed || pointer.down || pointer.released {
modifiers |= PointerModifiers()
}
key := Runtime.RaylibPressedKey()
for event: 0..511 {
unused event
if key < 340 || key > 347 { break }
modifiers |= Runtime.RaylibModifierBit(key)
key = Runtime.RaylibPressedKeyRaw()
}
Device.KeyboardModifiersSend(session, modifiers)
if key == 0 { key = Runtime.RaylibRepeatedKey(); result.key_fresh = false }
if key != 0 { Device.KeyboardSend(session, key) }
count: s32
// Desktop keys are already the active layout's codes. A key released
// during this poll is up, so a tapped shortcut key is never held into
// the next frame.
for held: 1..511 {
if Runtime.RaylibKeyDown(cast(s32)held) && count < down.count {
down[count] = Runtime.RaylibLayoutKey(cast(s32)held); count += 1
if Keys.DesktopKeyDown(cast(s32)held) && !Keys.DesktopKeyReleased(cast(s32)held) && count < down.count {
down[count] = cast(s32)held; count += 1
}
}
result.down = down[0:count]
codepoint := Runtime.RaylibTypedCodepoint()
while codepoint > 0 {
Device.TypedCodepointSend(session, codepoint)
codepoint = Runtime.RaylibTypedCodepoint()
}
return result
}
Apply :: (result: Input.Result) {
Apply :: (result: Input.Result, app: *AppState.State) {
if result.cursor_changed {
if result.cursor_hidden { HideCursor() } else { ShowCursor() }
}
if result.hyperlink != "" {
bytes: [2048]u8
if CString.CopyCString(result.hyperlink, bytes[:]) { OpenURL(*bytes[0]) }
if app != null && app.fullscreen_toggle_requested {
unused WindowState.DesktopToggleFullscreen(); app.fullscreen_toggle_requested = false
}
}
+298
View File
@@ -0,0 +1,298 @@
#scope_module
using Geometry :: #import "kryon/geometry";
using Drawing :: #import "kryon/drawing_props";
using Frames :: #import "kryon/session";
using Input :: #import "kryon/tree_input";
using Keys :: #import "kryon/input_protocol";
Box :: #import "kryon/box";
Button :: #import "kryon/button";
TabBar :: #import "kryon/tab_bar";
Paint :: #import "kryon/paint_queue";
Clock :: #import "kryon/Clock";
Fonts :: #import "kryon/font_metrics";
Keyboard :: #import "terminal_keyboard";
Screen :: #import "terminal_screen_host";
Metrics :: #import "terminal_pane_metrics";
Selection :: #import "terminal_pane_selection";
Colors :: #import "terminal_pane_profile_colors";
Render :: #import "terminal_pane_render";
Style :: #import "terminal_cell_style";
MaxCols :: 240;
MaxRows :: 120;
TabHeight :: 34.0;
DefaultFont :: 14;
Tab :: struct {
handle: s32
scroll: s32
selection: Selection.TerminalPaneSelection
}
tabs: [8]Tab;
active: s32;
count: s32;
started: bool;
tab_scroll: s32;
dragging: bool;
drag_from: s32;
font_size: s32 = DefaultFont;
Grid :: struct {
bounds: Rectangle
cols: s32
rows: s32
width: s32
height: s32
}
Clamp :: (value: s32, low: s32, high: s32) -> s32 {
if value < low { return low }
if value > high { return high }
return value
}
Layout :: (viewport: Rectangle) -> Grid {
policy := Metrics.TerminalPaneMetricsPolicyFor(1.0)
grid: Grid
grid.bounds = Metrics.TerminalPaneContentBoundsFor(viewport, cast(s32)TabHeight, policy.padding)
grid.width = Fonts.GlyphWidth("M", font_size, "")
if grid.width < 6 { grid.width = font_size * 6 / 10 }
grid.height = Metrics.TerminalPaneLineHeightFor(Fonts.GlyphLineHeight(font_size, ""), font_size, policy)
grid.cols = Metrics.TerminalPaneClampCols(cast(s32)grid.bounds.width / grid.width, MaxCols, policy)
grid.rows = Metrics.TerminalPaneClampRows(cast(s32)grid.bounds.height / grid.height, MaxRows, policy)
return grid
}
NewTab :: (grid: Grid) {
if count >= tabs.count { return }
handle := Screen.ScreenOpen("", "", "", grid.cols, grid.rows)
if handle == 0 { return }
tabs[count] = .{handle=handle}
active = count
count += 1
}
CloseTab :: (index: s32) {
if index < 0 || index >= count { return }
unused Screen.ScreenClose(tabs[index].handle)
for position: index..count - 2 { tabs[position] = tabs[position + 1] }
count -= 1
tabs[count] = .{}
if active > index { active -= 1 }
if active >= count { active = count - 1 }
if active < 0 { active = 0 }
}
MoveTab :: (from: s32, to: s32) {
if from == to || from < 0 || from >= count || to < 0 || to >= count { return }
moved := tabs[from]
step: s32 = ifx from < to then 1 else -1
while from != to {
if active == from + step { active = from }
tabs[from] = tabs[from + step]
from += step
}
tabs[to] = moved
active = to
}
DrawTabs :: (frame: Session, viewport: Rectangle, grid: Grid) {
width := viewport.width - 42.0
labels: [8]string = .["Shell 1", "Shell 2", "Shell 3", "Shell 4", "Shell 5", "Shell 6", "Shell 7", "Shell 8"]
entries: [8]TabBar.Tab
for index: 0..count - 1 {
entries[index] = .{key=cast(u64)(100 + tabs[index].handle), label=labels[index], closeable=true}
}
if count > 0 && width > 0.0 {
props: TabBar.Props
props.key = 5
props.bounds = .{viewport.x, viewport.y, width, TabHeight}
props.selected_index = active
props.scale = 1.0
props.min_tab_width = 72
props.max_tab_width = 200
props.scroll_offset = tab_scroll
props.reorder_enabled = true
props.dragging = dragging
props.drag_from = drag_from
result := TabBar.Draw(frame, props, entries[:count])
tab_scroll = result.scroll_offset
dragging = result.dragging
drag_from = result.drag_from
if result.reordered_from >= 0 { MoveTab(result.reordered_from, result.reordered_to) }
if result.activated_index >= 0 && result.activated_index < count { active = result.activated_index }
if result.closed_index >= 0 { CloseTab(result.closed_index) }
}
add: Button.Props
add.key = 6
add.label = "+"
add.bounds = .{viewport.x + width + 4.0, viewport.y + 2.0, 36.0, TabHeight - 4.0}
add.disabled = count >= tabs.count
if Button.Draw(frame, add) != 0 { NewTab(grid) }
}
HandleShortcuts :: (key: s32, mods: s32, grid: Grid) -> bool {
control := (mods & KeyModifierControl) != 0
shift := (mods & KeyModifierShift) != 0
if !control { return false }
if key == #char "T" && shift { NewTab(grid); return true }
if key == #char "W" && shift { CloseTab(active); return true }
if key == KeyTab && count > 0 {
active = (active + (ifx shift then count - 1 else 1)) % count
return true
}
if key == #char "=" || key == #char "-" || key == #char "0" {
if key == #char "0" { font_size = DefaultFont }
else { font_size = Clamp(font_size + (ifx key == #char "=" then 1 else -1), 10, 32) }
return true
}
return false
}
Fill :: (frame: Session, node: s32, bounds: Rectangle, clip: Rectangle, color: Color) {
clipped := RectangleIntersection(bounds, clip)
if clipped.width > 0.0 && clipped.height > 0.0 {
Paint.PaintRoundedFill(frame, node, clipped, 0.0, 0, color)
}
}
DrawRow :: (frame: Session, node: s32, grid: Grid, words: []s32, row: s32,
selected: *Selection.TerminalPaneSelection, visible_row: s32,
background: Color, foreground: Color, theme: Colors.TerminalPaneColors, blink: bool) {
y := cast(s32)grid.bounds.y + row * grid.height
for col: 0..words.count / Screen.CellWords - 1 {
cell := Screen.ScreenRowCell(words, cast(s32)col)
if (cell.style & Style.WideContinuation) != 0 { continue }
fg := Colors.ResolveTerminalPaneColor(null, cell.foreground, foreground)
bg := Colors.ResolveTerminalPaneColor(null, cell.background, background)
if cell.hyperlink > 0 { fg = theme.link }
if (cell.style & Style.Inverse) != 0 { swap := fg; fg = bg; bg = swap }
x := cast(s32)grid.bounds.x + cast(s32)col * grid.width
bounds := Rectangle.{cast(float32)x, cast(float32)y, cast(float32)grid.width, cast(float32)grid.height}
marked := Selection.TerminalPaneSelectionContains(selected, visible_row, cast(s32)col) != 0
if marked {
fg = theme.selection_text; bg = theme.selection
}
if marked || cell.background >= 0 || (cell.style & Style.Inverse) != 0 {
Fill(frame, node, bounds, grid.bounds, bg)
}
if (cell.style & Style.Conceal) != 0 || ((cell.style & Style.Blink) != 0 && !blink) { continue }
Render.DrawTerminalPaneGlyphCell(frame, node, cell.codepoint, cell.combining, x, y, font_size, fg, grid.bounds)
if (cell.style & Style.Bold) != 0 {
Render.DrawTerminalPaneGlyphCell(frame, node, cell.codepoint, cell.combining, x + 1, y, font_size, fg, grid.bounds)
}
decoration := Colors.ResolveTerminalPaneColor(null, cell.underline, fg)
if (cell.style & Style.Underline) != 0 || cell.hyperlink > 0 {
Fill(frame, node, .{bounds.x, bounds.y + bounds.height - 3.0, bounds.width, 1.0}, grid.bounds, decoration)
}
if (cell.style & Style.Overline) != 0 {
Fill(frame, node, .{bounds.x, bounds.y + 1.0, bounds.width, 1.0}, grid.bounds, decoration)
}
if (cell.style & Style.Strike) != 0 {
Fill(frame, node, .{bounds.x, bounds.y + bounds.height / 2.0, bounds.width, 1.0}, grid.bounds, fg)
}
}
}
HandleSelection :: (frame: Session, tab: *Tab, grid: Grid, first: s32, key: s32, modifiers: s32) -> bool {
pointer := Input.PointerSample(frame)
row := first + Clamp(cast(s32)(pointer.y - grid.bounds.y) / grid.height, 0, grid.rows - 1)
col := Clamp(cast(s32)(pointer.x - grid.bounds.x) / grid.width, 0, grid.cols - 1)
selected := *tab.selection
if pointer.pressed && PointInBounds(pointer.x, pointer.y, grid.bounds) {
Selection.TerminalPaneSelectionBeginChar(selected, row, col)
}
if selected.dragging != 0 && (pointer.down || pointer.released) {
reversed := row < selected.anchor_row || (row == selected.anchor_row && col < selected.anchor_start_col)
selected.start_col = ifx reversed then selected.anchor_end_col else selected.anchor_start_col
selected.end_row = row
selected.end_col = ifx reversed then col else col + 1
}
if !pointer.down { selected.dragging = 0 }
if (modifiers & (KeyModifierControl | KeyModifierShift)) != (KeyModifierControl | KeyModifierShift) { return false }
if key == #char "V" { unused Screen.ScreenPaste(tab.handle); tab.scroll = 0; return true }
if key != #char "C" { return false }
if selected.active != 0 {
reversed := selected.start_row > selected.end_row ||
(selected.start_row == selected.end_row && selected.start_col > selected.end_col)
if reversed {
unused Screen.ScreenCopy(tab.handle, selected.end_row, selected.end_col, selected.start_row, selected.start_col)
} else {
unused Screen.ScreenCopy(tab.handle, selected.start_row, selected.start_col, selected.end_row, selected.end_col)
}
}
return true
}
#program_export
Frame :: (frame: Session, viewport: Rectangle) -> s32 {
grid := Layout(viewport)
if !started { NewTab(grid); started = true }
key := KeyboardTake(frame)
mods := KeyboardModifiers(frame)
shortcut := HandleShortcuts(key, mods, grid)
DrawTabs(frame, viewport, grid)
theme := Colors.GetTerminalPaneThemeColors(true)
surface: Box.Props
surface.key = 1
surface.bounds = grid.bounds
surface.fill = theme.background
node := Box.Draw(frame, surface)
if count == 0 {
Paint.PaintClippedLabel(frame, node, "Open a shell with + or Ctrl+Shift+T", cast(s32)grid.bounds.x,
cast(s32)grid.bounds.y, font_size, theme.text, grid.bounds)
return 0
}
for index: 0..count - 1 { unused Screen.ScreenPoll(tabs[index].handle) }
tab := *tabs[active]
state := Screen.ScreenRead(tab.handle)
if state.cols != grid.cols || state.rows != grid.rows {
if Screen.ScreenResize(tab.handle, grid.cols, grid.rows) { state = Screen.ScreenRead(tab.handle) }
Selection.TerminalPaneSelectionClear(*tab.selection)
}
max_scroll := Clamp(state.visible_lines - grid.rows, 0, state.visible_lines)
tab.scroll += cast(s32)(PointerWheelTake(frame, grid.bounds) * 3.0)
if (mods & KeyModifierShift) != 0 && (key == KeyPageUp || key == KeyPageDown) {
tab.scroll += ifx key == KeyPageUp then grid.rows else -grid.rows
shortcut = true
}
tab.scroll = Clamp(tab.scroll, 0, max_scroll)
first := max_scroll - tab.scroll
shortcut = HandleSelection(frame, tab, grid, first, key, mods) || shortcut
codepoints: [32]u32
used: s32
scalar := TypedCodepointTake(frame)
while scalar != 0 {
if used < codepoints.count { codepoints[used] = cast(u32)scalar; used += 1 }
scalar = TypedCodepointTake(frame)
}
if !shortcut && (key != 0 || used > 0) && Screen.ScreenInput(tab.handle, key, Keyboard.TerminalModifiers(mods), codepoints[:used]) {
tab.scroll = 0
Selection.TerminalPaneSelectionClear(*tab.selection)
}
bg := Colors.ResolveTerminalPaneColor(null, state.background, theme.background)
fg := Colors.ResolveTerminalPaneColor(null, state.foreground, theme.text)
Fill(frame, node, grid.bounds, grid.bounds, bg)
if state.cols <= 0 || state.cols > MaxCols { return 0 }
words: [MaxCols * Screen.CellWords]s32
row_words := words[:state.cols * Screen.CellWords]
first = max_scroll - tab.scroll
blink := Clock.Milliseconds() % 1000 < 550
for row: 0..grid.rows - 1 {
if first + row >= state.visible_lines || Screen.ScreenReadRow(tab.handle, first + row, row_words) != state.cols { break }
DrawRow(frame, node, grid, row_words, row, *tab.selection, first + row, bg, fg, theme, blink)
}
if state.cursor_visible && state.running && tab.scroll == 0 && blink {
x := grid.bounds.x + cast(float32)(state.cursor_col * grid.width)
y := grid.bounds.y + cast(float32)(state.cursor_row * grid.height)
if state.cursor_style == 2 { Fill(frame, node, .{x, y + cast(float32)grid.height - 2.0, cast(float32)grid.width, 2.0}, grid.bounds, theme.cursor) }
else { Fill(frame, node, .{x, y, 2.0, cast(float32)grid.height}, grid.bounds, theme.cursor) }
}
if !state.running {
Paint.PaintClippedLabel(frame, node, "Shell exited. Open another tab to start a new shell.", cast(s32)grid.bounds.x,
cast(s32)(grid.bounds.y + grid.bounds.height) - grid.height, font_size, theme.text, grid.bounds)
}
return 0
}
+35
View File
@@ -0,0 +1,35 @@
// Linux launcher for the Terminal bundle installed beside this executable.
Desktop :: #import "kryon/desktop_zx";
Host :: #import "terminal_screen_linux_host";
using Bundle :: #import "std/bundle_host";
using Bytes :: #import "std/byte_text_linux";
using CString :: #import "std/c_string";
#import "std/text_buffer"
libc :: #system_library "libc";
ReadLink :: (path: *u8, output: *u8, size: usize) -> isize #foreign libc "readlink";
BundlePath :: (path: []u8) -> string {
proc_path: [15]u8
if !CopyCString("/proc/self/exe", proc_path[:]) { return "" }
length := ReadLink(*proc_path[0], *path[0], cast(usize)path.count)
if length <= 0 || length >= cast(isize)path.count { return "" }
separator := cast(s32)length - 1
while separator >= 0 && path[separator] != 47 { separator -= 1 }
if separator < 0 || !CopyCString("Terminal.zx", path[separator+1:]) { return "" }
return TextUntilNul(path)
}
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
check := argc == 2 && TextFromCString(argv[1]) == "--check"
if argc != 1 && !check { print("Usage: terminal-zx-player [--check]\n"); return 2 }
path_bytes: [4096]u8
path := BundlePath(path_bytes[:])
if path == "" { print("Cannot locate Terminal.zx beside its player\n"); return 1 }
host: Host.ScreenHost
bindings: [Host.BindingCount]HostBinding
if !Host.FillBindings(*host, bindings[:]) { return 1 }
defer { Host.Dispose(*host) }
return Desktop.RunWithBindings(path, .{check=check}, bindings[:])
}
+18 -1
View File
@@ -151,6 +151,23 @@ capture_finish :: (terminal: *Terminal) {
terminal.capture_scrolled = false
}
// A capture newline separates rows; it is not a PTY line feed. tmux writes
// only attribute changes and trims each row's trailing blanks, so the last
// cell's colors stay current across the newline. Background color erase
// would then fill every newly entered row with them: one green tmux status
// or diff row painted the following rows green. Enter each row with default
// blank cells, then keep the carried attributes for the cells that follow.
capture_newline :: (terminal: *Terminal) {
fg := terminal.current_fg; bg := terminal.current_bg
underline := terminal.current_underline; style := terminal.current_style
hyperlink := terminal.current_hyperlink
reset_current_style(terminal); terminal.current_hyperlink = 0
terminal_feed(terminal, cast(*void)RawBytes("\r\n"), 2)
terminal.current_fg = fg; terminal.current_bg = bg
terminal.current_underline = underline; terminal.current_style = style
terminal.current_hyperlink = hyperlink
}
#scope_export
#program_export
terminal_feed_capture :: (terminal: *Terminal, data: *void, count: s32,
@@ -183,7 +200,7 @@ trim_final_linefeed: bool) -> bool {
}
if bytes[index] == 10 {
if index > start { terminal_feed(terminal, cast(*void)(*bytes[start]), index - start) }
terminal_feed(terminal, cast(*void)RawBytes("\r\n"), 2)
capture_newline(terminal)
start = index + 1
}
index += 1
+4 -1
View File
@@ -89,7 +89,10 @@ cols: s32, rows: s32) -> bool {
}
candidate.source = source; candidate.cols = cols; candidate.rows = rows
candidate.source_cols = source.cols; candidate.source_history = history
candidate.blank = terminal_blank_cell(source)
// Cells past a row's end are not written cells. Painting them with the
// parser's current SGR state turned a resized pane the color of its last
// captured cell, such as a green tmux status row. Pad in default colors.
candidate.blank = terminal_blank_cell(null)
for logical: 0..history - 1 {
soft := ifx reflow then terminal_visible_line_wrapped(source, logical) else 0
count := ifx reflow then viewport_source_end(source, logical, history, soft) else (ifx source.cols < cols then source.cols else cols)
+11 -10
View File
@@ -19,6 +19,7 @@ Clipboard :: #import "terminal_clipboard";
Text :: #import "std/byte_text_linux";
Transport :: #import "terminal_pty_linux";
CellStyle :: #import "terminal_cell_style";
#scope_export
MAX_COLS :: 240;
@@ -34,16 +35,16 @@ MAX_SIXEL_IMAGE_PIXELS :: 4194304;
MAX_SIXEL_TOTAL_PIXELS :: 8388608;
COLOR_DEFAULT :: -1;
COLOR_TRUE_RGB :: 0x01000000;
STYLE_BOLD :: 1;
STYLE_ITALIC :: 2;
STYLE_UNDERLINE :: 4;
STYLE_INVERSE :: 8;
STYLE_STRIKE :: 16;
STYLE_WIDE_CONT :: 32;
STYLE_FAINT :: 64;
STYLE_CONCEAL :: 128;
STYLE_BLINK :: 256;
STYLE_OVERLINE :: 512;
STYLE_BOLD :: CellStyle.Bold;
STYLE_ITALIC :: CellStyle.Italic;
STYLE_UNDERLINE :: CellStyle.Underline;
STYLE_INVERSE :: CellStyle.Inverse;
STYLE_STRIKE :: CellStyle.Strike;
STYLE_WIDE_CONT :: CellStyle.WideContinuation;
STYLE_FAINT :: CellStyle.Faint;
STYLE_CONCEAL :: CellStyle.Conceal;
STYLE_BLINK :: CellStyle.Blink;
STYLE_OVERLINE :: CellStyle.Overline;
MOD_SHIFT :: 1;
MOD_ALT :: 2;
MOD_CTRL :: 4;
+11
View File
@@ -0,0 +1,11 @@
// Cell style bits shared by the emulator and its renderers.
Bold :: 1;
Italic :: 2;
Underline :: 4;
Inverse :: 8;
Strike :: 16;
WideContinuation :: 32;
Faint :: 64;
Conceal :: 128;
Blink :: 256;
Overline :: 512;
+23 -1
View File
@@ -48,6 +48,18 @@ Store :: (buffer: *ClipboardBuffer, text: string, pending: bool) -> bool {
SetPrimary :: (text: string) -> bool {
if !CString.CopyCString(text, primary_bytes[:]) { return false }
primary_length = text.count
// Keep the local copy as the fallback for hosts without PRIMARY.
unused System.SystemPrimarySet(text)
return true
}
SyncPrimaryFromHost :: () -> bool {
if !System.SystemPrimaryAvailable() { return false }
{
text := System.SystemPrimaryText(primary_bytes[0:CLIPBOARD_BUFFER_SIZE - 1])
primary_length = text.count
}
primary_bytes[primary_length] = 0
return true
}
@@ -165,7 +177,10 @@ SetPrimarySelectionFromText :: (text: *u8) -> s32 {
}
#program_export
GetPrimarySelectionTextValue :: () -> *u8 { return *primary_bytes[0] }
GetPrimarySelectionTextValue :: () -> *u8 {
SyncPrimaryFromHost()
return *primary_bytes[0]
}
#program_export
CopySelectionTextToClipboard :: (buffer: *void, text: *u8) -> s32 {
@@ -201,6 +216,9 @@ FlushClipboardBufferToHost :: (buffer: *ClipboardBuffer) -> s32 {
#program_export
ClipboardSourceHasText :: (source: s32) -> s32 {
if source == CLIPBOARD_SOURCE_PRIMARY || source == CLIPBOARD_SOURCE_PRIMARY_OR_CLIPBOARD {
SyncPrimaryFromHost()
}
if source == CLIPBOARD_SOURCE_PRIMARY { return cast(s32)(primary_length > 0) }
if source == CLIPBOARD_SOURCE_PRIMARY_OR_CLIPBOARD && primary_length > 0 { return 1 }
return cast(s32)System.SystemClipboardHasText()
@@ -277,6 +295,9 @@ WriteClipboardTextPaste :: (buffer: *ClipboardBuffer, text: *u8,
WriteClipboardSourcePaste :: (buffer: *ClipboardBuffer, source: s32,
bracketed: s32, write_text: ClipboardPasteWriteFn, userdata: *void) -> s32 {
if buffer == null { return 0 }
if source == CLIPBOARD_SOURCE_PRIMARY || source == CLIPBOARD_SOURCE_PRIMARY_OR_CLIPBOARD {
SyncPrimaryFromHost()
}
if source != CLIPBOARD_SOURCE_PRIMARY &&
!(source == CLIPBOARD_SOURCE_PRIMARY_OR_CLIPBOARD && primary_length > 0) {
SyncClipboardBufferFromHost(buffer)
@@ -308,6 +329,7 @@ HandleClipboardOSC52 :: (buffer: *ClipboardBuffer, payload: *u8,
response: [4096]u8
source := cast(State.ClipboardSource)CLIPBOARD_SOURCE_CLIPBOARD
if primary && !system { source = cast(State.ClipboardSource)CLIPBOARD_SOURCE_PRIMARY }
if source == cast(State.ClipboardSource)CLIPBOARD_SOURCE_PRIMARY { SyncPrimaryFromHost() }
content := State.ClipboardRead(Snapshot(buffer), source).text
if targets.count > 32 { return 0 }
used: s64 = 5
+21 -5
View File
@@ -416,6 +416,11 @@ PumpTerminalPaneKeyboardInputFiltered :: (input: TerminalPaneInput,
blocked[key] = true; wrote = 1
} else { queued[key] = true }
}
// Kryon hands over Enter together with the text typed before it, which
// Enter commits, so that text reaches the shell first and rapidly typed
// lines stay apart. Any other key comes before the frame's text.
text_first := queued[257] && frame.codepoints.count > 0
if text_first && WriteFrameCodepoints(input, frame, blocked[:]) { wrote = 1 }
if queued[257] || (input.mode.application_keypad == 0 && queued[335]) {
if InputKey(input, TERMINAL_PANE_KEY_ENTER, frame.mods) != 0 { wrote = 1 }
}
@@ -457,20 +462,31 @@ PumpTerminalPaneKeyboardInputFiltered :: (input: TerminalPaneInput,
if down && (queued[key] || input.state.last_control_keys[key] == 0) {
if InputCodepoint(input, codepoint, frame.mods) != 0 { control_wrote = true }
}
input.state.last_control_keys[key] = ifx down then 1 else 0
// A press a shortcut consumed stays delivered until the key is
// released, so a held shortcut key never also types its control
// byte in a later frame.
input.state.last_control_keys[key] = ifx down || blocked[key] then 1 else 0
}
if control_wrote { return 1 }
} else if input.state != null {
for key: 0..511 { input.state.last_control_keys[key] = 0 }
}
for index: 0..cast(s32)frame.codepoints.count - 1 {
if CodepointFiltered(blocked[:], frame.codepoints[index]) { continue }
if InputCodepoint(input, frame.codepoints[index], frame.mods) != 0 { wrote = 1 }
}
if !text_first && WriteFrameCodepoints(input, frame, blocked[:]) { wrote = 1 }
return wrote
}
#scope_file
// Writes the frame's typed text, leaving out what a consumed shortcut typed.
WriteFrameCodepoints :: (input: TerminalPaneInput, frame: KeyboardFrame,
blocked: []bool) -> bool {
wrote: bool
for index: 0..cast(s32)frame.codepoints.count - 1 {
if CodepointFiltered(blocked, frame.codepoints[index]) { continue }
if InputCodepoint(input, frame.codepoints[index], frame.mods) != 0 { wrote = true }
}
return wrote
}
KeepTerminalKey :: (userdata: *void, key: s32, mods: s32) -> s32 {
unused userdata
unused key
+117 -24
View File
@@ -1,6 +1,7 @@
#scope_module
Engine :: #import "terminal";
Text :: #import "std/byte_text_linux";
PaneText :: #import "terminal_pane_text";
CellAt :: (terminal: *Engine.Terminal, view: *Engine.TerminalViewport, col: s32, row: s32) -> *Engine.Cell {
if view != null { return Engine.terminal_viewport_cell(view, col, row) }
@@ -10,14 +11,94 @@ Wrapped :: (terminal: *Engine.Terminal, view: *Engine.TerminalViewport, row: s32
if view != null { return Engine.terminal_viewport_line_wrapped(view, row) != 0 }
return Engine.terminal_visible_line_wrapped(terminal, row) != 0
}
ByteAt :: (terminal: *Engine.Terminal, view: *Engine.TerminalViewport, col: s32, row: s32) -> u8 {
CellHasText :: (terminal: *Engine.Terminal, view: *Engine.TerminalViewport,
col: s32, row: s32) -> bool {
cell := CellAt(terminal, view, col, row)
if cell == null || cell.codepoint <= cast(u32)32 || cell.codepoint >= cast(u32)127 { return 32 }
return cast(u8)cell.codepoint
return cell != null && (cell.style & Engine.STYLE_WIDE_CONT) == 0 &&
cell.codepoint > cast(u32)32
}
PreviousCell :: (terminal: *Engine.Terminal, view: *Engine.TerminalViewport,
cols: s32, col: *s32, row: *s32) -> bool {
if col == null || row == null { return false }
col.* -= 1
if col.* < 0 {
if row.* <= 0 || !Wrapped(terminal, view, row.* - 1) { return false }
row.* -= 1; col.* = cols - 1
}
while col.* >= 0 {
cell := CellAt(terminal, view, col.*, row.*)
if cell == null || (cell.style & Engine.STYLE_WIDE_CONT) == 0 { return true }
col.* -= 1
}
return false
}
NextCell :: (terminal: *Engine.Terminal, view: *Engine.TerminalViewport,
cols: s32, lines: s32, col: *s32, row: *s32) -> bool {
if col == null || row == null { return false }
col.* += 1
if col.* >= cols {
if row.* >= lines - 1 || !Wrapped(terminal, view, row.*) { return false }
row.* += 1; col.* = 0
}
while col.* < cols {
cell := CellAt(terminal, view, col.*, row.*)
if cell == null || (cell.style & Engine.STYLE_WIDE_CONT) == 0 { return true }
col.* += 1
}
if row.* >= lines - 1 || !Wrapped(terminal, view, row.*) { return false }
row.* += 1; col.* = 0
return true
}
AppendCell :: (cell: *Engine.Cell, out: []u8, used: *s32) -> bool {
if cell == null || used == null || cell.codepoint <= cast(u32)32 ||
(cell.style & Engine.STYLE_WIDE_CONT) != 0 { return false }
capacity: s32 = 2147483647
if out.count < 2147483647 { capacity = cast(s32)out.count }
if !PaneText.AppendTerminalPaneUTF8Codepoint(*out[0], capacity,
used, cell.codepoint) { return false }
if cell.combining != cast(u32)0 &&
!PaneText.AppendTerminalPaneUTF8Codepoint(*out[0], capacity,
used, cell.combining) { return false }
return true
}
Prefix :: (value: string, at: s32, prefix: string) -> bool {
return at >= 0 && cast(s64)at + prefix.count <= value.count && value[at:at + cast(s32)prefix.count] == prefix
}
EmailWord :: (byte: u8) -> bool {
return (byte >= #char "a" && byte <= #char "z") ||
(byte >= #char "A" && byte <= #char "Z") ||
(byte >= #char "0" && byte <= #char "9") || byte == #char "." ||
byte == #char "_" || byte == #char "%" || byte == #char "+" || byte == #char "-"
}
EmailAt :: (value: *u8, size: s32, pointer: s32, out: []u8) -> string {
begin := pointer; end := pointer + 1
while begin > 0 && EmailWord(value[begin - 1]) { begin -= 1 }
while end < size && EmailWord(value[end]) { end += 1 }
// The @ itself is not an EmailWord, so include the other half when the
// pointer lands on either side of the address.
if begin > 0 && value[begin - 1] == #char "@" {
begin -= 1
while begin > 0 && EmailWord(value[begin - 1]) { begin -= 1 }
} else if end < size && value[end] == #char "@" {
end += 1
while end < size && EmailWord(value[end]) { end += 1 }
}
at: s32 = -1; dots: s32
for index: begin..end - 1 {
if value[index] == #char "@" { if at >= 0 { return "" }; at = index }
else if at >= 0 && value[index] == #char "." { dots += 1 }
else if !EmailWord(value[index]) { return "" }
}
if at <= begin || at + 1 >= end || dots == 0 || value[end - 1] == #char "." { return "" }
length := end - begin
if cast(s64)length + 7 >= out.count { return "" }
address: [8192]u8
for index: 0..length - 1 { address[index] = value[begin + index] }
prefix := "mailto:"
for i: 0..6 { out[i] = prefix[i] }
for index: 0..length - 1 { out[index + 7] = address[index] }
return Text.TextFromBytes(out[0:cast(s64)length + 7])
}
#scope_export
// Resolves a cell in history/screen or a reflowed viewport. Returned text borrows
@@ -39,34 +120,46 @@ LinkAt :: (terminal: *Engine.Terminal, view: *Engine.TerminalViewport,
return Text.TextFromBytes(out[:value.count])
}
}
if ByteAt(terminal, view, col, row) == cast(u8)32 { return "" }
start_col := col; start_row := row; distance: s64
while distance < out.count {
c := start_col - 1; r := start_row
if c < 0 {
if r == 0 || !Wrapped(terminal, view, r - 1) { break }
r -= 1; c = cols - 1
// A wide glyph's continuation cell belongs to the same logical character.
if (cell.style & Engine.STYLE_WIDE_CONT) != 0 {
while col > 0 && (cell.style & Engine.STYLE_WIDE_CONT) != 0 {
col -= 1; cell = CellAt(terminal, view, col, row)
if cell == null { return "" }
}
if ByteAt(terminal, view, c, r) == cast(u8)32 { break }
start_col = c; start_row = r; distance += 1
}
if distance >= out.count { return "" }
if !CellHasText(terminal, view, col, row) { return "" }
start_col := col; start_row := row
while true {
c := start_col; r := start_row
if !PreviousCell(terminal, view, cols, *c, *r) ||
!CellHasText(terminal, view, c, r) { break }
start_col = c; start_row = r
}
size: s32; at: s32 = -1; c := start_col; r := start_row
while r < lines {
byte := ByteAt(terminal, view, c, r)
if byte == cast(u8)32 { break }
if cast(s64)size + 1 >= out.count { return "" }
current := CellAt(terminal, view, c, r)
if current == null || !CellHasText(terminal, view, c, r) { break }
if c == col && r == row { at = size }
out[size] = byte; size += 1; c += 1
if c >= cols {
if !Wrapped(terminal, view, r) { break }
c = 0; r += 1
}
if !AppendCell(current, out, *size) { return "" }
next_col := c; next_row := r
if !NextCell(terminal, view, cols, lines, *next_col, *next_row) { break }
c = next_col; r = next_row
}
if at < 0 { return "" }
value := Text.TextFromBytes(out[:size]); begin: s32 = -1
for i: 0..at { if Prefix(value, i, "https://") || Prefix(value, i, "http://") { begin = i; break } }
if begin < 0 { return "" }
out[size] = 0
begin: s32 = -1
{
token_view := Text.TextFromBytes(out[:size])
for i: 0..at {
if Prefix(token_view, i, "https://") || Prefix(token_view, i, "http://") { begin = i; break }
}
}
if begin < 0 {
token: [8192]u8
for index: 0..size - 1 { token[index] = out[index] }
return EmailAt(*token[0], size, at, out)
}
value := Text.TextFromBytes(out[:size])
end := begin; depth: s32
while end < size && value[end] != cast(u8)62 && value[end] != cast(u8)34 &&
value[end] != cast(u8)39 && value[end] != cast(u8)96 && value[end] != cast(u8)92 &&
+2 -2
View File
@@ -31,9 +31,9 @@ DrawTerminalPaneGlyphCell :: (session: Sessions.Session, node: s32,
bytes: [12]u8
length: s32
if codepoint == cast(u32)0 || codepoint == cast(u32)32 { return }
if !Text.AppendTerminalPaneUTF8Codepoint(*bytes[0], 12, *length, codepoint) { return }
if !Text.AppendCodepoint(bytes[:], *length, codepoint) { return }
if combining != cast(u32)0 {
Text.AppendTerminalPaneUTF8Codepoint(*bytes[0], 12, *length, combining)
Text.AppendCodepoint(bytes[:], *length, combining)
}
Paint.PaintClippedLabel(session, node, TextView(bytes[0:length]),
x, y, font_size, color, clip)
+14 -6
View File
@@ -1,8 +1,5 @@
#program_export
AppendTerminalPaneUTF8Codepoint :: (output: *u8, output_size: s32,
used: *s32, codepoint: u32) -> bool {
if output == null || used == null || output_size <= 0 ||
used.* < 0 || used.* >= output_size { return false }
AppendCodepoint :: (output: []u8, used: *s32, codepoint: u32) -> bool {
if used == null || used.* < 0 || used.* >= output.count { return false }
output[used.*] = 0
if codepoint == 0 || codepoint > 0x10ffff { return false }
@@ -14,7 +11,7 @@ AppendTerminalPaneUTF8Codepoint :: (output: *u8, output_size: s32,
} else if codepoint >= 0x80 {
width = 2
}
if used.* + width >= output_size { return false }
if used.* + width >= output.count { return false }
if width == 1 {
output[used.*] = cast(u8)codepoint
@@ -35,3 +32,14 @@ AppendTerminalPaneUTF8Codepoint :: (output: *u8, output_size: s32,
output[used.*] = 0
return true
}
#if !#defined(KRYON_ZX) {
Bytes :: #import "std/byte_text_linux";
#program_export
AppendTerminalPaneUTF8Codepoint :: (output: *u8, output_size: s32,
used: *s32, codepoint: u32) -> bool {
if output == null || output_size <= 0 { return false }
return AppendCodepoint(Bytes.BytesFromPointer(output, cast(u64)output_size), used, codepoint)
}
}
+11
View File
@@ -0,0 +1,11 @@
// Portable terminal I/O. Handles belong to the current bundle instance.
#scope_file
host_api :: #system_library "host_api";
#scope_export
PtyOpen :: (directory: string, shell: string, command: string, columns: s32, rows: s32) -> s32 #reads #foreign host_api;
// Returns bytes read, zero on timeout, or -1 when the session is closed.
PtyRead :: (handle: s32, output: []u8, wait_ms: s32) -> s32 #foreign host_api;
PtyWrite :: (handle: s32, input: []u8) -> s32 #reads #foreign host_api;
PtyResize :: (handle: s32, columns: s32, rows: s32) -> bool #foreign host_api;
PtyClose :: (handle: s32) -> bool #foreign host_api;
+26 -1
View File
@@ -95,6 +95,31 @@ IsBash :: (path: *u8) -> bool {
return value[start:] == "bash"
}
// A folder that exists but cannot be entered must not end the session before
// the shell starts: say so on the terminal and start in HOME, or else in /.
EnterFallback :: (cwd: *u8) {
error := ErrorPointer().*
reason := "\" cannot be entered"
if error == 13 { reason = "\": permission denied" }
else if error == 2 { reason = "\" does not exist" }
else if error == 20 { reason = "\" is not a folder" }
started := Environment("HOME")
if started == null || started[0] == 0 || ChangeDirectory(cast(*s8)started) != 0 {
started = cast(*u8)Bytes("/")
ChangeDirectory(Bytes("/"))
}
Notice("Terminal: working directory \"")
Notice(RawText(cwd))
Notice(reason)
Notice("; starting in ")
Notice(RawText(started))
Notice("\n")
}
Notice :: (text: string) {
if text.count > 0 { WriteHost(2, cast(*void)Bytes(text), cast(usize)text.count) }
}
RunChild :: (master: s32, cwd: *u8, shell: *u8, command: *u8) {
name := PTYName(master)
path: [256]u8
@@ -106,7 +131,7 @@ RunChild :: (master: s32, cwd: *u8, shell: *u8, command: *u8) {
Ioctl(slave, 0x540e, null)
if Duplicate(slave, 0) < 0 || Duplicate(slave, 1) < 0 || Duplicate(slave, 2) < 0 { Exit(127); return }
if slave > 2 { Close(slave) }
if cwd != null && cwd[0] != 0 && ChangeDirectory(cast(*s8)cwd) != 0 { Exit(127); return }
if cwd != null && cwd[0] != 0 && ChangeDirectory(cast(*s8)cwd) != 0 { EnterFallback(cwd) }
SetEnvironment(Bytes("TERM"), Bytes("xterm-256color"), 1)
SetEnvironment(Bytes("COLORTERM"), Bytes("truecolor"), 1)
SanitizePath()
+174
View File
@@ -0,0 +1,174 @@
using Bundle :: #import "std/bundle_host";
using Bytes :: #import "std/byte_text_linux";
using CString :: #import "std/c_string";
Pty :: #import "terminal_pty_linux";
#scope_file
libc :: #system_library "c";
PollFd :: struct { fd: s32; events: s16; returned: s16 }
Poll :: (descriptor: *PollFd, count: usize, wait_ms: s32) -> s32 #foreign libc "poll";
ChunkSize :: 4096;
MaxHandle :: 2147483647;
MaxWaitMs :: 100;
#scope_export
BindingCount :: 5;
Session :: struct { handle: s32; fd: s32; pid: s32 }
#scope_export
PtyHost :: struct {
sessions: [64]Session
next_handle: s32
module_name: [18]u8
binding_names: [BindingCount][10]u8
}
#scope_file
InRange :: (value: HostValue, low: s64, high: s64) -> bool {
return value.kind == cast(s32)HostValueKind.HostInteger && value.integer >= low && value.integer <= high
}
Geometry :: (args: *HostValue) -> bool {
return InRange(args[0], 1, 240) && InRange(args[1], 1, 120)
}
CopyText :: (value: HostValue, output: []u8) -> bool {
if value.kind != cast(s32)HostValueKind.HostString || value.length >= cast(usize)output.count {
return false
}
if value.length > 0 && value.data == null { return false }
for index: 0..cast(s32)value.length - 1 {
byte := value.data[index]
if byte == 0 { return false }
output[index] = byte
}
output[value.length] = 0
return true
}
Find :: (host: *PtyHost, handle: s32) -> *Session {
for index: 0..host.sessions.count - 1 {
if host.sessions[index].handle == handle { return *host.sessions[index] }
}
return null
}
CloseSession :: (session: *Session) {
Pty.TerminalPtyClose(session.fd)
if Pty.TerminalPtyWaitExit(session.pid, 0) == 0 {
Pty.TerminalPtySignal(session.pid, 1)
Pty.TerminalPtySignal(session.pid, 15)
if Pty.TerminalPtyWaitExit(session.pid, 200) == 0 {
Pty.TerminalPtySignal(session.pid, 9)
Pty.TerminalPtyWaitExit(session.pid, 500)
}
}
session.* = .{}
}
OpenSession :: (host: *PtyHost, args: *HostValue) -> s32 {
if !Geometry(*args[3]) || host.next_handle == MaxHandle { return -1 }
session := Find(host, 0)
if session == null { return -1 }
directory: [ChunkSize]u8
shell: [ChunkSize]u8
command: [ChunkSize]u8
if !CopyText(args[0], directory[:]) || !CopyText(args[1], shell[:]) || !CopyText(args[2], command[:]) {
return -1
}
pid: s32
fd := Pty.TerminalPtyOpen(*directory[0], *shell[0], *command[0], cast(s32)args[3].integer, cast(s32)args[4].integer, *pid)
if fd < 0 { return -1 }
host.next_handle += 1
session.* = .{host.next_handle, fd, pid}
return session.handle
}
ValidBuffer :: (buffer: HostValue) -> bool {
return buffer.kind == cast(s32)HostValueKind.HostSlice && buffer.length > 0 && buffer.length <= ChunkSize && buffer.elements != null
}
Read :: (session: *Session, buffer: HostValue, wait_ms: s32) -> s32 {
if session == null || !ValidBuffer(buffer) { return -1 }
if wait_ms > 0 {
descriptor: PollFd = .{session.fd, 1, 0}
if Poll(*descriptor, 1, wait_ms) <= 0 { return 0 }
}
bytes: [ChunkSize]u8
count := Pty.TerminalPtyRead(session.fd, cast(*void)(*bytes[0]), cast(s32)buffer.length)
for index: 0..count - 1 {
buffer.elements[index].kind = cast(s32)HostValueKind.HostUnsigned
buffer.elements[index].bits = cast(u64)bytes[index]
}
return count
}
Write :: (session: *Session, buffer: HostValue) -> s32 {
if session == null || !ValidBuffer(buffer) { return 0 }
bytes: [ChunkSize]u8
for index: 0..cast(s32)buffer.length - 1 {
element := buffer.elements[index]
if element.kind != cast(s32)HostValueKind.HostUnsigned || element.bits > 255 { return 0 }
bytes[index] = cast(u8)element.bits
}
return Pty.TerminalPtyWrite(session.fd, cast(*void)(*bytes[0]), cast(s32)buffer.length)
}
Call :: (context: *void, module_name: *u8, function_name: *u8, args: *HostValue, count: s32, result: *HostValue) -> s32 {
if TextFromCString(module_name) != "terminal_pty_host" { return 0 }
host := cast(*PtyHost)context
function := TextFromCString(function_name)
result.kind = cast(s32)HostValueKind.HostInteger
if function == "PtyOpen" && count == 5 {
result.integer = cast(s64)OpenSession(host, args)
return 1
}
if count < 1 || !InRange(args[0], 1, MaxHandle) { return 0 }
session := Find(host, cast(s32)args[0].integer)
if function == "PtyRead" && count == 3 && InRange(args[2], 0, MaxWaitMs) {
result.integer = cast(s64)Read(session, args[1], cast(s32)args[2].integer)
} else if function == "PtyWrite" && count == 2 {
result.integer = cast(s64)Write(session, args[1])
} else if function == "PtyResize" && count == 3 {
result.integer = 0
if session != null && Geometry(*args[1]) {
Pty.TerminalPtyResize(session.fd, cast(s32)args[1].integer, cast(s32)args[2].integer)
result.integer = 1
}
} else if function == "PtyClose" && count == 1 {
result.integer = 0
if session != null {
CloseSession(session)
result.integer = 1
}
} else {
return 0
}
return 1
}
#scope_export
FillBindings :: (host: *PtyHost, bindings: []HostBinding) -> bool {
if host == null || bindings.count != BindingCount { return false }
names: [BindingCount]string = .{"PtyOpen", "PtyRead", "PtyWrite", "PtyResize", "PtyClose"}
if !CopyCString("terminal_pty_host", host.module_name[:]) { return false }
for index: 0..bindings.count - 1 {
if !CopyCString(names[index], host.binding_names[index][:]) { return false }
binding: HostBinding
binding.module = *host.module_name[0]
binding.function = *host.binding_names[index][0]
binding.call = Call
binding.context = cast(*void)host
bindings[index] = binding
}
return true
}
Dispose :: (host: *PtyHost) {
for index: 0..host.sessions.count - 1 {
session := *host.sessions[index]
if session.handle != 0 { CloseSession(session) }
}
}
+63
View File
@@ -0,0 +1,63 @@
// A guest terminal renders the existing emulator's cells and drives its PTY.
#scope_file
host_api :: #system_library "host_api";
#scope_export
CellWords :: 7;
ScreenWords :: 10;
ScreenState :: struct {
cols: s32
rows: s32
visible_lines: s32
cursor_col: s32
cursor_row: s32
cursor_style: s32
cursor_visible: bool
running: bool
foreground: s32
background: s32
}
ScreenCell :: struct {
codepoint: u32
combining: u32
foreground: s32
background: s32
underline: s32
hyperlink: s32
style: s32
}
ScreenOpen :: (directory: string, shell: string, command: string, cols: s32, rows: s32) -> s32 #reads #foreign host_api;
ScreenPoll :: (handle: s32) -> s32 #foreign host_api;
ScreenResize :: (handle: s32, cols: s32, rows: s32) -> bool #foreign host_api;
ScreenClose :: (handle: s32) -> bool #foreign host_api;
ScreenWrite :: (handle: s32, text: string) -> s32 #reads #foreign host_api;
ScreenKey :: (handle: s32, key: s32, modifiers: s32) -> s32 #foreign host_api;
ScreenInput :: (handle: s32, key: s32, modifiers: s32, typed: []u32) -> bool #reads #foreign host_api;
ScreenPaste :: (handle: s32) -> bool #foreign host_api;
ScreenCopy :: (handle: s32, first_row: s32, first_col: s32, last_row: s32, last_col: s32) -> bool #foreign host_api;
#scope_file
ReadState :: (handle: s32, output: []s32) -> bool #foreign host_api;
ReadRow :: (handle: s32, row: s32, output: []s32) -> s32 #foreign host_api;
#scope_export
ScreenRead :: (handle: s32) -> ScreenState {
values: [ScreenWords]s32
if !ReadState(handle, values[:]) { return .{} }
return .{values[0], values[1], values[2], values[3], values[4], values[5],
values[6] != 0, values[7] != 0, values[8], values[9]}
}
ScreenReadRow :: (handle: s32, row: s32, output: []s32) -> s32 {
return ReadRow(handle, row, output)
}
ScreenRowCell :: (words: []s32, col: s32) -> ScreenCell {
if col < 0 || col >= words.count / CellWords { return .{} }
start := col * CellWords
return .{cast(u32)words[start], cast(u32)words[start+1], words[start+2],
words[start+3], words[start+4], words[start+5], words[start+6]}
}
+234
View File
@@ -0,0 +1,234 @@
// Keep the platform's terminal engine and PTY ownership on the native side.
using Bundle :: #import "std/bundle_host";
using Bytes :: #import "std/byte_text_linux";
using CString :: #import "std/c_string";
Engine :: #import "terminal";
Screen :: #import "terminal_screen_host";
Keys :: #import "terminal_pane_keys";
Clipboard :: #import "terminal_clipboard";
Selection :: #import "terminal_pane_selection";
SystemClipboard :: #import "kryon/system_clipboard";
#scope_file
MaxHandle :: 2147483647;
MaxText :: 4096;
libc :: #system_library "libc";
GetEnvironment :: (name: *u8) -> *u8 #foreign libc "getenv";
Session :: struct { handle: s32; terminal: Engine.Terminal }
#scope_export
BindingCount :: 11;
ScreenHost :: struct {
sessions: [8]Session
next_handle: s32
module_name: [21]u8
names: [BindingCount][13]u8
clipboard: Clipboard.ClipboardBuffer
clipboard_text: [Clipboard.CLIPBOARD_BUFFER_SIZE]u8
}
#scope_file
InRange :: (value: HostValue, low: s64, high: s64) -> bool {
return value.kind == cast(s32)HostValueKind.HostInteger &&
value.integer >= low && value.integer <= high
}
TextValid :: (value: HostValue, limit: s32) -> bool {
return value.kind == cast(s32)HostValueKind.HostString && value.length <= cast(usize)limit &&
(value.length == 0 || value.data != null)
}
CStringFor :: (value: HostValue, output: []u8) -> bool {
if !TextValid(value, cast(s32)output.count - 1) { return false }
length := cast(s32)value.length
for index: 0..length - 1 {
if value.data[index] == 0 { return false }
output[index] = value.data[index]
}
output[length] = 0
return true
}
Dimensions :: (cols: HostValue, rows: HostValue) -> bool {
return InRange(cols, 8, Engine.MAX_COLS) && InRange(rows, 4, Engine.MAX_ROWS)
}
Find :: (host: *ScreenHost, handle: s32) -> *Session {
for index: 0..host.sessions.count - 1 {
if host.sessions[index].handle == handle { return *host.sessions[index] }
}
return null
}
Open :: (host: *ScreenHost, args: *HostValue) -> s32 {
if host.next_handle == MaxHandle || !Dimensions(args[3], args[4]) { return 0 }
session := Find(host, 0)
if session == null { return 0 }
directory: [MaxText]u8
shell: [MaxText]u8
command: [MaxText]u8
if !CStringFor(args[0], directory[:]) || !CStringFor(args[1], shell[:]) ||
!CStringFor(args[2], command[:]) { return 0 }
start := *directory[0]
if directory[0] == 0 {
home: [5]u8
CopyCString("HOME", home[:])
start = GetEnvironment(*home[0])
}
Engine.terminal_init(*session.terminal)
if Engine.terminal_spawn(*session.terminal, start, *shell[0], *command[0],
cast(s32)args[3].integer, cast(s32)args[4].integer) == 0 {
Engine.terminal_close(*session.terminal)
return 0
}
host.next_handle += 1
session.handle = host.next_handle
return session.handle
}
Close :: (session: *Session) {
session.handle = 0
Engine.terminal_close(*session.terminal)
}
WriteInput :: (context: *void, bytes: *u8, count: s32) -> s32 {
return Engine.terminal_write(cast(*Engine.Terminal)context, cast(*void)bytes, count)
}
Input :: (term: *Engine.Terminal, key: s32, modifiers: s32, typed: HostValue) -> bool {
if typed.kind != cast(s32)HostValueKind.HostSlice || typed.length > 32 ||
TextFromCString(typed.type_name) != "[]u32" ||
(typed.length > 0 && typed.elements == null) { return false }
codepoints: [32]u32
length := cast(s32)typed.length
for index: 0..length - 1 {
scalar := typed.elements[index]
if scalar.kind != cast(s32)HostValueKind.HostUnsigned || scalar.bits == 0 || scalar.bits > 0x10ffff { return false }
codepoints[index] = cast(u32)scalar.bits
}
key_buffer: [1]s32 = .[key]
frame: Keys.KeyboardFrame
if key != 0 { frame.keys = key_buffer[:] }
frame.mods = modifiers
frame.codepoints = codepoints[:length]
state: Keys.TerminalPaneInputState
input: Keys.TerminalPaneInput
input.write_text = WriteInput
input.userdata = cast(*void)term
input.state = *state
input.mode = .{term.application_cursor_keys, term.application_keypad, term.modify_other_keys}
return Keys.PumpTerminalPaneKeyboardInput(input, frame) != 0
}
SelectionLine :: (context: *void, row: s32, output: *u8, size: s32) -> s32 {
Engine.terminal_visible_line(cast(*Engine.Terminal)context, row, output, size)
return 1
}
SelectionWrapped :: (context: *void, row: s32) -> s32 {
return Engine.terminal_visible_line_wrapped(cast(*Engine.Terminal)context, row)
}
Copy :: (host: *ScreenHost, term: *Engine.Terminal, args: *HostValue) -> bool {
lines := Engine.terminal_visible_line_count(term)
if !InRange(args[1], 0, lines - 1) || !InRange(args[2], 0, term.cols) ||
!InRange(args[3], args[1].integer, lines - 1) || !InRange(args[4], 0, term.cols) { return false }
selection: Selection.TerminalPaneSelection
Selection.TerminalPaneSelectionSetRange(*selection, Selection.TERMINAL_PANE_SELECTION_CHAR, 0,
cast(s32)args[1].integer, cast(s32)args[2].integer, cast(s32)args[3].integer, cast(s32)args[4].integer)
return Selection.TerminalPaneSelectionCopyToClipboard(*selection, SelectionLine,
SelectionWrapped, cast(*void)term, cast(*void)(*host.clipboard)) != 0
}
OutputValid :: (output: HostValue, length: s32) -> bool {
return output.kind == cast(s32)HostValueKind.HostSlice &&
output.length == cast(usize)length && output.elements != null &&
TextFromCString(output.type_name) == "[]s32"
}
State :: (term: *Engine.Terminal, output: HostValue) -> bool {
if !OutputValid(output, Screen.ScreenWords) { return false }
values: [Screen.ScreenWords]s32 = .[term.cols, term.rows, Engine.terminal_visible_line_count(term),
term.cursor_col, term.cursor_row, term.cursor_style, term.cursor_visible, term.running,
term.default_fg, term.default_bg]
for index: 0..values.count - 1 { output.elements[index].integer = cast(s64)values[index] }
return true
}
Row :: (term: *Engine.Terminal, index: s32, output: HostValue) -> s32 {
if index >= Engine.terminal_visible_line_count(term) ||
!OutputValid(output, term.cols * Screen.CellWords) { return 0 }
for col: 0..term.cols - 1 {
cell := Engine.terminal_visible_cell(term, col, index)
if cell == null { return 0 }
values: [Screen.CellWords]s32 = .[cast(s32)cell.codepoint, cast(s32)cell.combining,
cell.fg, cell.bg, cell.underline, cell.hyperlink, cast(s32)cell.style]
for word: 0..values.count - 1 {
output.elements[col * Screen.CellWords + word].integer = cast(s64)values[word]
}
}
return term.cols
}
Call :: (context: *void, module: *u8, name: *u8, args: *HostValue, count: s32, result: *HostValue) -> s32 {
if TextFromCString(module) != "terminal_screen_host" { return 0 }
host := cast(*ScreenHost)context
function := TextFromCString(name)
result.kind = cast(s32)HostValueKind.HostInteger
if function == "ScreenOpen" && count == 5 {
result.integer = cast(s64)Open(host, args)
return 1
}
if count == 0 || !InRange(args[0], 1, MaxHandle) { return 0 }
session := Find(host, cast(s32)args[0].integer)
if session == null { return 1 }
term := *session.terminal
if function == "ScreenClose" && count == 1 {
Close(session)
result.integer = 1
} else if function == "ScreenPoll" && count == 1 {
result.integer = cast(s64)Engine.terminal_poll_bytes(term)
} else if function == "ScreenResize" && count == 3 && Dimensions(args[1], args[2]) {
cols := cast(s32)args[1].integer
rows := cast(s32)args[2].integer
Engine.terminal_resize(term, cols, rows)
result.integer = cast(s64)(term.cols == cols && term.rows == rows)
} else if function == "ScreenKey" && count == 3 && InRange(args[1], 1, Engine.KEY_F24_CODE) && InRange(args[2], 0, 7) {
result.integer = cast(s64)Engine.terminal_send_key(term, cast(s32)args[1].integer, cast(s32)args[2].integer)
} else if function == "ScreenWrite" && count == 2 && TextValid(args[1], MaxText) {
result.integer = cast(s64)Engine.terminal_write(term, cast(*void)args[1].data, cast(s32)args[1].length)
} else if function == "ScreenInput" && count == 4 && InRange(args[1], 0, 511) && InRange(args[2], 0, 7) {
result.integer = cast(s64)Input(term, cast(s32)args[1].integer, cast(s32)args[2].integer, args[3])
} else if function == "ScreenPaste" && count == 1 {
value := SystemClipboard.SystemClipboardText(host.clipboard_text[:])
result.integer = cast(s64)Clipboard.PasteText(*host.clipboard, value, term.bracketed_paste,
WriteInput, cast(*void)term)
} else if function == "ScreenCopy" && count == 5 {
result.integer = cast(s64)Copy(host, term, args)
} else if function == "ReadState" && count == 2 {
result.integer = cast(s64)State(term, args[1])
} else if function == "ReadRow" && count == 3 && InRange(args[1], 0, MaxHandle) {
result.integer = cast(s64)Row(term, cast(s32)args[1].integer, args[2])
} else { return 0 }
return 1
}
#scope_export
FillBindings :: (host: *ScreenHost, bindings: []HostBinding) -> bool {
if host == null || bindings.count != BindingCount { return false }
names: [BindingCount]string = .["ScreenOpen", "ScreenClose", "ScreenPoll", "ScreenResize",
"ScreenKey", "ScreenWrite", "ReadState", "ReadRow", "ScreenInput", "ScreenPaste", "ScreenCopy"]
if !CopyCString("terminal_screen_host", host.module_name[:]) { return false }
for index: 0..bindings.count - 1 {
if !CopyCString(names[index], host.names[index][:]) { return false }
bindings[index] = .{module=*host.module_name[0], function=*host.names[index][0],
call=Call, context=cast(*void)host}
}
return true
}
Dispose :: (host: *ScreenHost) {
for index: 0..host.sessions.count - 1 {
if host.sessions[index].handle != 0 { Close(*host.sessions[index]) }
}
}
+6 -2
View File
@@ -11,7 +11,7 @@ case "$suite" in
*) echo "Unknown Terminal application suite: $suite" >&2; exit 2 ;;
esac
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS SESSION_MANAGER ENV BASH_ENV
export YUE_DESKTOP_RECOVERY=0
export HARMONY_DESKTOP_RECOVERY=0
ziran=${ZIRAN:-"$root/scripts/ziran.sh"}
lock_flags=
if test ! -f ziran.local.toml; then lock_flags=--locked; fi
@@ -20,6 +20,7 @@ work=$(mktemp -d "$root/build/ziran/$suite-test.XXXXXX")
trap 'rm -rf "$work"' EXIT HUP INT TERM
# Persistence fixtures must never read or replace the owner's saved tabs.
export XDG_CONFIG_HOME="$work/config" XDG_STATE_HOME="$work/state"
export KRYON_TEST_OPEN_URI_CAPTURE="$work/open-uri"
mkdir -p "$XDG_CONFIG_HOME" "$XDG_STATE_HOME/terminal"
printf 'active=0\n' > "$work/session.before"
cp "$work/session.before" "$XDG_STATE_HOME/terminal/session"
@@ -37,7 +38,10 @@ for form in source saved; do
input=$source
if test "$form" = saved; then input=$work/ir/$module.zir; fi
"$ziran" build --project $lock_flags --target=c --entry "$entry" \
--exe -o "$work/$form-c" "$input"
--no-main -o "$work/$form-c" "$input"
"${CC:-cc}" -std=c11 -O1 -I"$work/$form-c" "$work/$form-c"/*.c \
$(pkg-config --libs gtk+-3.0 x11 xcb) -lutil -ldl -lpthread -lm \
-o "$work/$form-c/$module"
(cd "$work/$form-c" && TERMINAL_TEST_SHELL="$work/shell" timeout --kill-after=2s 15s "./$module")
cmp "$work/session.before" "$XDG_STATE_HOME/terminal/session"
done
+1 -1
View File
@@ -16,7 +16,7 @@ esac
mkdir -p build/ziran
work=$(mktemp -d "$root/build/ziran/$suite-test.XXXXXX")
trap 'rm -rf "$work"' EXIT HUP INT TERM
# The imported fixture exports exactly Kryon's three native host symbols.
# The imported fixture exports Kryon's clipboard and PRIMARY host symbols.
entry=$module:main
source=tests/$module.zi
"$ziran" ir --project $lock_flags --entry "$entry" -o "$work/ir" "$source"
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS SESSION_MANAGER ENV BASH_ENV
export HARMONY_DESKTOP_RECOVERY=0
ziran=${ZIRAN:-"$root/scripts/ziran.sh"}
lock_flags=
if test ! -f ziran.local.toml; then lock_flags=--locked; fi
mkdir -p build/ziran
work=$(mktemp -d "$root/build/ziran/context-menu.XXXXXX")
trap 'rm -rf "$work"' EXIT HUP INT TERM
"$ziran" build --project $lock_flags --target=c --entry context_menu_test:main \
--exe -o "$work/c" tests/context_menu_test.zi
"$work/c/context_menu_test"
echo 'Terminal context menu matches the xfce4-terminal 1.1.4 structure and state fields'
+74
View File
@@ -0,0 +1,74 @@
Menu :: #import "app_context_menu";
State :: #import "app_state";
Session :: #import "app_session";
Commands :: #import "app_commands";
ClipboardHost :: #import "terminal_clipboard_host";
MenuWidget :: #import "kryon/context_menu";
Find :: (items: []MenuWidget.ContextMenuItem, label: string, parent: s32 = 0) -> s32 {
for index: 0..cast(s32)items.count - 1 {
if items[index].parent == parent && items[index].label == label { return index }
}
return -1
}
RootMatches :: (items: []MenuWidget.ContextMenuItem, expected: []string) -> bool {
at: s32
for item: items {
if item.parent != 0 { continue }
if at >= cast(s32)expected.count { return false }
if expected[at] == "---" {
if !item.separator { return false }
} else if item.separator || item.label != expected[at] { return false }
at += 1
}
return at == cast(s32)expected.count
}
#program_export
main :: () -> s32 {
app := State.Allocate(); if app == null { return 1 }
defer State.Dispose(app)
app.session_count = 1; app.active = 0; app.sessions[0].used = true
items: [57]MenuWidget.ContextMenuItem
count := Menu.BuildItems(app, *app.sessions[0], items[:])
root: [21]string = .{"Open Tab","Open Terminal","Open File Manager Here","---",
"Copy","Copy as HTML","---","Paste","Paste Selection","---",
"Show Menubar","Fullscreen","Read-Only","---","Send Signal","---","Zoom","---",
"Save Contents...","---","Preferences..."}
if count != 54 || !RootMatches(items[0:count], root[:]) { return 2 }
copy := Find(items[0:count], "Copy"); html := Find(items[0:count], "Copy as HTML")
paste_primary := Find(items[0:count], "Paste Selection")
if copy < 0 || html < 0 || paste_primary < 0 || !items[copy].disabled || !items[html].disabled ||
!items[paste_primary].disabled { return 3 }
menubar := Find(items[0:count], "Show Menubar")
fullscreen := Find(items[0:count], "Fullscreen")
readonly := Find(items[0:count], "Read-Only")
if menubar < 0 || fullscreen < 0 || readonly < 0 || !items[menubar].checkable ||
!items[menubar].checked || !items[fullscreen].checkable || items[fullscreen].checked ||
!items[readonly].checkable || items[readonly].checked { return 4 }
signals := Find(items[0:count], "Send Signal"); zoom := Find(items[0:count], "Zoom")
if signals < 0 || zoom < 0 || Find(items[0:count], "1 - HUP", items[signals].id) < 0 ||
Find(items[0:count], "30 - PWR", items[signals].id) < 0 { return 5 }
zoom_in := Find(items[0:count], "Zoom In", items[zoom].id)
zoom_out := Find(items[0:count], "Zoom Out", items[zoom].id)
normal := Find(items[0:count], "Normal Size", items[zoom].id)
if zoom_in < 0 || zoom_out < 0 || normal < 0 || items[zoom_in].accelerator != "Ctrl++" ||
items[zoom_out].accelerator != "Ctrl+-" || items[normal].accelerator != "Ctrl+0" { return 6 }
Session.CopyText(app.context_link[:], "mailto:[email protected]")
app.selection.active = 1; app.launch.fullscreen = true
active := *app.sessions[0]
active.read_only = true
count = Menu.BuildItems(app, active, items[:])
dynamic: [24]string = .{"Compose Email","Copy Email Address","---","Open Tab","Open Terminal",
"Open File Manager Here","---","Copy","Copy as HTML","---","Paste","Paste Selection","---",
"Show Menubar","Fullscreen","Read-Only","---","Send Signal","---","Zoom","---",
"Save Contents...","---","Preferences..."}
if count != 57 || !RootMatches(items[:], dynamic[:]) { return 7 }
copy = Find(items[:], "Copy"); html = Find(items[:], "Copy as HTML")
fullscreen = Find(items[:], "Fullscreen"); readonly = Find(items[:], "Read-Only")
if items[copy].disabled || items[html].disabled || !items[fullscreen].checked ||
!items[readonly].checked { return 8 }
return 0
}
+143
View File
@@ -0,0 +1,143 @@
"""Rendered xfce4-terminal 1.1.4 context-menu reference on private Xvfb."""
import os
from pathlib import Path
from difflib import SequenceMatcher
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import time
sys.dont_write_bytecode = True
from standalone_window_test import close_window
REFERENCE = (
'open tab', 'open terminal', 'open file manager here',
'copy', 'copy as html', 'paste', 'paste selection',
'show menubar', 'fullscreen', 'read-only', 'send signal', 'zoom',
'save contents', 'preferences',
)
def wait(predicate, message, seconds=8):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
value = predicate()
if value:
return value
time.sleep(.06)
raise AssertionError(message)
def normalized(text):
return re.sub(r'[^a-z0-9+.-]+', ' ', text.lower()).strip()
def in_order(text, phrases):
rows = tuple(filter(None, text.splitlines()))
at = 0
for phrase in phrases:
for index in range(at, len(rows)):
if phrase in rows[index] or SequenceMatcher(None, phrase, rows[index]).ratio() >= .72:
at = index + 1
break
else:
return False
return True
def screenshot_text(window, env, root):
image = root / 'context-menu.png'
subprocess.run(['import', '-window', window, '-resize', '400%', str(image)], env=env,
check=True, timeout=5, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
result = subprocess.run(['tesseract', str(image), 'stdout', '--psm', '4'],
env=dict(env, OMP_THREAD_LIMIT='1'), check=True, timeout=8,
text=True, capture_output=True)
return '\n'.join(normalized(line) for line in result.stdout.splitlines())
def main():
assert os.environ.get('TERMINAL_PRIVATE_XVFB') == '1'
assert os.environ['DISPLAY'].startswith(':')
assert os.environ.get('HARMONY_DESKTOP_RECOVERY') == '0'
for program in ('xdotool', 'import', 'tesseract'):
assert shutil.which(program), f'{program} is required for the rendered menu comparison'
binary = str(Path(sys.argv[1]).resolve())
Path('build/ziran').mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='terminal-context-menu-', dir='build/ziran') as directory:
root = Path(directory).resolve()
shell = root / 'shell'
shell.write_text('#!/bin/sh\nexec /bin/sh -c "$2"\n')
shell.chmod(0o700)
child = root / 'child.py'
ready = root / 'ready'
child.write_text(
'import os,sys,tty\n'
'tty.setraw(0)\n'
'open(sys.argv[1],"wb").close()\n'
'while os.read(0,1024): pass\n')
env = dict(os.environ, XDG_CONFIG_HOME=str(root / 'config'),
XDG_STATE_HOME=str(root / 'state'), SDL_VIDEODRIVER='x11',
LP_NUM_THREADS='1', OMP_NUM_THREADS='1')
def xdo(*args):
return subprocess.run(['xdotool', *map(str, args)], env=env, text=True,
capture_output=True, check=True, timeout=5).stdout.strip()
with (root / 'window.log').open('w') as log:
command = 'python3 ' + shlex.quote(str(child)) + ' ' + shlex.quote(str(ready))
app = subprocess.Popen([
binary, '--hide-menubar', '--hide-toolbar', '--geometry', '80x34',
'--shell', str(shell), '-e', command,
], env=env, stdout=log, stderr=log)
try:
def find_window():
found = subprocess.run(
['xdotool', 'search', '--onlyvisible', '--pid', str(app.pid)],
env=env, capture_output=True, text=True)
lines = found.stdout.splitlines()
return lines[-1] if found.returncode == 0 and lines and ready.exists() else None
window = wait(find_window, 'Terminal context-menu fixture did not open')
assert int(xdo('getwindowpid', window)) == app.pid
xdo('windowfocus', '--sync', window)
time.sleep(.3)
xdo('mousemove', '--window', window, 60, 100)
xdo('mousedown', '3'); time.sleep(.15); xdo('mouseup', '3')
# Each capture is read until the expected rows appear, so a frame
# taken before the menu or submenu is painted is not judged.
def rendered(phrases):
def read():
text = screenshot_text(window, env, root)
return text if in_order(text, phrases) else None
return read
text = wait(rendered(REFERENCE), 'Context menu was not rendered')
assert in_order(text, REFERENCE), repr(text)
assert 'open link' not in text and 'compose email' not in text
# The reference Zoom row is 335 units below the panel top and
# is 26 units tall. Hovering it must render the three reference
# submenu actions and their accelerator labels.
xdo('mousemove', '--window', window, 120, 448)
zoom = wait(rendered(('zoom in', 'zoom out', 'normal size')),
'Zoom submenu was not rendered')
assert in_order(zoom, ('zoom in', 'zoom out', 'normal size')), zoom
# OCR reads the monospaced "Ctrl" as "ctr1" at some sizes.
assert len(re.findall(r'ctr[l1i]', zoom)) >= 3, zoom
close_window(window, app.pid, env)
assert app.wait(timeout=5) == 0
finally:
if app.poll() is None:
app.terminate()
app.wait(timeout=5)
print('Terminal rendered context menu and Zoom submenu match the captured xfce4-terminal 1.1.4 reference')
if __name__ == '__main__':
main()
+1 -1
View File
@@ -65,7 +65,7 @@ def main():
'KRYON_CAPTURE_PATH', 'ENV', 'BASH_ENV'):
env.pop(key, None)
env.update(XDG_CONFIG_HOME=str(root / 'config'), XDG_STATE_HOME=str(root / 'state'),
SDL_VIDEODRIVER='x11', YUE_DESKTOP_RECOVERY='0',
SDL_VIDEODRIVER='x11', HARMONY_DESKTOP_RECOVERY='0',
LP_NUM_THREADS='1', OMP_NUM_THREADS='1')
apps, windows, logs, inputs = [], [], [], []
+9 -3
View File
@@ -144,6 +144,10 @@ def main():
time.sleep(.2)
probe = subprocess.run(['xclip','-selection','clipboard','-target','image/png','-out'],env=env,capture_output=True,timeout=3)
assert probe.stdout==png, (probe.returncode,probe.stderr)
image_before = incoming.stat().st_size
xdo('keydown','ctrl','shift'); time.sleep(.1); xdo('key','v'); time.sleep(.2); xdo('keyup','shift','ctrl')
time.sleep(.2)
assert incoming.stat().st_size == image_before, 'Ctrl+Shift+V must never paste an image'
xdo('keydown','ctrl'); time.sleep(.1); xdo('key','v'); time.sleep(.2); xdo('keyup','ctrl')
data = wait(lambda: incoming.read_bytes(),'PNG paste never reached the PTY')
assert b'\x16' not in data, data
@@ -155,8 +159,10 @@ def main():
env=env,stdin=subprocess.PIPE,stdout=log,stderr=log)
clips.append(clip); clip.stdin.write(text.encode()); clip.stdin.close(); time.sleep(.2)
xdo('keydown','ctrl'); time.sleep(.1); xdo('key','v'); time.sleep(.2); xdo('keyup','ctrl')
time.sleep(.2)
assert incoming.stat().st_size==before, 'Ctrl+V must not paste text'
data = wait(lambda: incoming.read_bytes() if incoming.stat().st_size>before else None,
'Ctrl+V text fallback lost text')
assert data[before:].replace(b'\x1b[200~',b'').replace(b'\x1b[201~',b'')==text.encode()
before = len(data)
xdo('keydown','ctrl','shift'); time.sleep(.1); xdo('key','v'); time.sleep(.2); xdo('keyup','shift','ctrl')
data = wait(lambda: incoming.read_bytes() if incoming.stat().st_size>before else None,'Shift paste lost text')
assert data[before:].replace(b'\x1b[200~',b'').replace(b'\x1b[201~',b'')==text.encode()
@@ -165,7 +171,7 @@ def main():
dropped = incoming.read_bytes()[before:]
assert shlex.split(dropped.replace(b'\x1b[200~',b'').replace(b'\x1b[201~',b'').decode()) == [str(image)], dropped
assert b'\r' not in dropped and b'\n' not in dropped, 'Drop submitted a command'
print('Local native image input: Ctrl+V pastes PNG, Ctrl+Shift+V pastes text, Xdnd preserves the path; no command submitted')
print('Local native image input: Ctrl+V pastes PNG or text fallback, Ctrl+Shift+V stays text-only, Xdnd preserves the path; no command submitted')
close_window(window,app.pid,env); app.wait(timeout=5)
assert app.returncode==0, (root/'window.log').read_text()
except BaseException:
+7 -4
View File
@@ -40,12 +40,13 @@ def main():
"KRYON_CAPTURE_PATH", "ENV", "BASH_ENV", "TMUX"):
env.pop(key, None)
env.update(XDG_CONFIG_HOME=str(work / "config"), XDG_STATE_HOME=str(work / "state"),
XDG_RUNTIME_DIR=str(runtime), SDL_VIDEODRIVER="x11", YUE_DESKTOP_RECOVERY="0",
XDG_RUNTIME_DIR=str(runtime), SDL_VIDEODRIVER="x11", HARMONY_DESKTOP_RECOVERY="0",
KTREM_TARGET_FPS="15", KTREM_ACTIVE_FPS="30", KTREM_PTY_BURST_MS="0",
LP_NUM_THREADS="1", OMP_NUM_THREADS="1")
# Isolate the legacy runtime's singleton lock as well as the display.
# A failing old executable can only replace a window from this fixture.
socket = str(work / "tmux.sock")
# Keep the socket private even when the runner checkout has a long path.
socket = "tmux.sock"
sessions = ("terminal-test-window-first", "terminal-test-window-second")
outputs = [work / (name + ".bytes") for name in sessions]
apps = []
@@ -53,7 +54,8 @@ def main():
server_started = False
def tmux(*arguments):
return run(["tmux", "-S", socket, "-f", "/dev/null", *arguments], env).stdout.strip()
return run(["tmux", "-S", socket, "-f", "/dev/null", *arguments], env,
cwd=work).stdout.strip()
def attached(name):
return tmux("display-message", "-p", "-t", "=" + name + ":", "#{session_attached}")
@@ -62,7 +64,8 @@ def main():
log = (work / (name + "-" + str(len(apps)) + ".log")).open("w")
logs.append(log)
app = subprocess.Popen([binary, "--disable-server", "--dynamic-title-mode=ignore",
"--title", name, "--shell", "/bin/sh", "--execute",
"--title", name, "--working-directory", str(work),
"--shell", "/bin/sh", "--execute",
"/usr/bin/tmux", "-S", socket, "attach-session", "-t", "=" + name],
env=env, stdout=log, stderr=subprocess.STDOUT)
apps.append(app)
+86 -25
View File
@@ -1,4 +1,6 @@
"""Actual SDL pointer/modifier routing and OS opener on verified private Xvfb."""
from csv import DictReader
from io import StringIO
import os
from pathlib import Path
import shlex
@@ -20,34 +22,60 @@ def wait(predicate, message):
raise AssertionError(message)
def menu_label_center(window, label, image, env):
# Look up the row in the private Xvfb window. Its position depends on
# the host's display scale and where the panel fits inside the window.
enlargement = 3
subprocess.run(['import', '-window', window, '-resize', f'{enlargement * 100}%', str(image)],
env=env, check=True, timeout=5, capture_output=True)
output = subprocess.run(['tesseract', str(image), 'stdout', '--psm', '11', 'tsv'],
env=dict(env, OMP_THREAD_LIMIT='1'), check=True, timeout=8,
text=True, capture_output=True).stdout
lines = {}
for word in DictReader(StringIO(output), delimiter='\t'):
if word['level'] != '5' or not word.get('text', '').strip():
continue
line = (word['block_num'], word['par_num'], word['line_num'])
lines.setdefault(line, []).append(word)
for words in lines.values():
if ' '.join(word['text'].lower() for word in words) == label:
first = words[0]
return ((int(first['left']) + int(first['width']) // 2) // enlargement,
(int(first['top']) + int(first['height']) // 2) // enlargement)
return None
def main():
assert os.environ.get('TERMINAL_PRIVATE_XVFB') == '1'
assert os.environ['DISPLAY'].startswith(':')
assert os.environ.get('YUE_DESKTOP_RECOVERY') == '0'
assert os.environ.get('HARMONY_DESKTOP_RECOVERY') == '0'
binary = str(Path(sys.argv[1]).resolve())
Path('work').mkdir(exist_ok=True)
with tempfile.TemporaryDirectory(prefix='link-window-', dir='work') as directory:
Path('backup/tests').mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='link-window-', dir='backup/tests') as directory:
root = Path(directory).resolve()
opener = root / 'xdg-open'
opened = root / 'opened'
opener.write_text('#!/bin/sh\nprintf "%s\\n" "$1" >> "$TERMINAL_LINK_RECEIPT"\n')
opener.chmod(0o700)
shell = root / 'shell'
shell.write_text('#!/bin/sh\nexec /bin/sh -c "$2"\n'); shell.chmod(0o700)
url = 'https://example.org/a(b)?q=1#part'
target = 'https://example.org/hidden'
email = '[email protected]'
wrapped = ('https://auth.openai.com/oauth/authorize?response_type=code&client_id=app&'
'redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback&scope=openid&'
'state=state-value-0123456789abcdef&codex_cli_simplified_flow=true')
child = root / 'child.py'; incoming = root / 'input'
child.write_text('import os,tty\ntty.setraw(0)\nos.write(1,' + repr(
(url + '.\r\n\x1b]8;;' + target + '\x07label\x1b]8;;\x07\r\n\x1b[?1000h\x1b[?1006h').encode()) + ')\n'
(wrapped + '\r\n' + url + '.\r\n\x1b]8;;' + target +
'\x07label\x1b]8;;\x07\r\n' + email +
'\r\n\x1b[?1000h\x1b[?1006h').encode()) + ')\n'
'with open(' + repr(str(incoming)) + ', "wb", buffering=0) as log:\n'
' while True:\n data=os.read(0,1024)\n if not data: break\n log.write(data)\n')
env = dict(os.environ, PATH=str(root) + ':' + os.environ['PATH'], TERMINAL_LINK_RECEIPT=str(opened),
env = dict(os.environ, KRYON_TEST_OPEN_URI_CAPTURE=str(opened),
XDG_CONFIG_HOME=str(root / 'config'), XDG_STATE_HOME=str(root / 'state'),
SDL_VIDEODRIVER='x11', LP_NUM_THREADS='1', OMP_NUM_THREADS='1')
def xdo(*args):
return subprocess.run(['xdotool', *map(str, args)], env=env, text=True, capture_output=True, check=True, timeout=5).stdout.strip()
with (root / 'window.log').open('w') as log:
app = subprocess.Popen([binary, '--hide-menubar', '--hide-toolbar', '--geometry', '40x8', '--shell', str(shell),
app = subprocess.Popen([binary, '--hide-menubar', '--hide-toolbar', '--geometry', '56x8', '--shell', str(shell),
'-e', 'python3 ' + shlex.quote(str(child))], env=env, stdout=log, stderr=log)
try:
def find():
@@ -56,36 +84,69 @@ def main():
window = wait(find, 'Terminal window and raw child')
assert int(xdo('getwindowpid', window)) == app.pid
geometry = dict(line.split('=', 1) for line in xdo('getwindowgeometry', '--shell', window).splitlines())
cell = int(geometry['WIDTH']) / 40; line = int(geometry['HEIGHT']) / 8
def click(modifier, row, before_focus=False, unfocused=False):
cell = int(geometry['WIDTH']) / 56; line = int(geometry['HEIGHT']) / 8
def click(modifier, row, column=2.5, before_focus=False, unfocused=False):
if before_focus or unfocused:
xdo('windowfocus', '0')
xdo('keydown', modifier)
if not unfocused:
xdo('windowfocus', '--sync', window)
xdo('mousemove', '--window', window, int(cell * 2.5), int(line * (row + .5)))
xdo('mousemove', '--window', window, int(cell * column), int(line * (row + .5)))
time.sleep(.1)
xdo('mousedown', '1'); time.sleep(.1); xdo('mouseup', '1')
xdo('keyup', modifier)
click('Alt_L', 0, True)
wait(lambda: opened.exists(), 'Alt-click visible URL opens')
assert opened.read_text().splitlines() == [url]
click('Alt_R', 1)
wait(lambda: len(opened.read_text().splitlines()) == 2, 'Right Alt-click OSC 8 opens')
assert opened.read_text().splitlines() == [url, target]
click('Control_L', 0)
wait(lambda: len(opened.read_text().splitlines()) == 3, 'Ctrl-click compatibility')
assert opened.read_text().splitlines() == [url, target, url]
click('Alt_L', 0, unfocused=True)
wait(lambda: len(opened.read_text().splitlines()) == 4, 'Unfocused/embedded Alt-click opens')
assert opened.read_text().splitlines() == [url, target, url, url]
click('Alt_L', 4, before_focus=True)
wait(lambda: opened.exists() and opened.read_text() == url, 'Alt-click visible URL opens')
click('Alt_R', 5)
wait(lambda: opened.read_text() == target, 'Right Alt-click OSC 8 opens')
click('Alt_L', 6)
wait(lambda: opened.read_text() == 'mailto:' + email, 'Alt-click email composes mail')
click('Alt_L', 0)
wait(lambda: opened.read_text() == wrapped, 'Alt-click wrapped URL opens from first row')
click('Alt_R', 2)
wait(lambda: opened.read_text() == wrapped, 'Alt-click wrapped URL opens from continuation row')
click('Alt_L', 3)
wait(lambda: opened.read_text() == wrapped, 'Alt-click wrapped URL opens after state split')
click('Control_L', 4)
wait(lambda: opened.read_text() == url, 'Ctrl-click compatibility')
click('Alt_L', 4, unfocused=True)
wait(lambda: opened.read_text() == url, 'Unfocused/embedded Alt-click opens')
# The wrapped continuation resolves identically through the
# context menu's independent Copy Link and Open Link actions.
# The child tracks the mouse, so a plain right-click is its own;
# Shift bypasses mouse reporting and opens the menu, as in
# xfce4-terminal. The unfocused click above left focus elsewhere,
# and a private display has no window manager to restore it.
def choose_context_link(label):
xdo('windowfocus', '--sync', window)
xdo('mousemove', '--window', window, int(cell * 2.5), int(line * 2.5))
xdo('keydown', 'Shift_L')
try:
xdo('mousedown', '3'); time.sleep(.1); xdo('mouseup', '3')
# Keep Shift down until the release has reached a frame.
x, y = wait(lambda: menu_label_center(window, label, root / 'menu.png', env),
f'Terminal context menu renders {label!r}')
finally:
xdo('keyup', 'Shift_L')
xdo('mousemove', '--window', window, x, y)
time.sleep(.1)
xdo('mousedown', '1'); time.sleep(.12); xdo('mouseup', '1')
choose_context_link('copy link address')
wait(lambda: subprocess.run(['xclip', '-selection', 'clipboard', '-o'], env=env,
capture_output=True).stdout == wrapped.encode(),
'Context-menu Copy Link preserves the exact wrapped OAuth URL')
opened.write_text('sentinel')
choose_context_link('open link')
wait(lambda: opened.read_text() == wrapped,
'Context-menu Open Link preserves the exact wrapped OAuth URL')
time.sleep(.2)
assert incoming.read_bytes() == b'', 'Link gestures must not send half a mouse click'
close_window(window, app.pid, env); app.wait(timeout=5)
finally:
if app.poll() is None:
app.terminate(); app.wait(timeout=5)
print('Terminal native SDL Alt/Ctrl URL and OSC 8 link opening passed on private Xvfb')
print('Terminal native Alt/Ctrl opens HTTP, OSC 8, email, and wrapped links through Kryon without leaking mouse input')
if __name__ == '__main__':
+47 -28
View File
@@ -5,6 +5,16 @@ root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS ENV BASH_ENV
ziran=${ZIRAN:-"$root/scripts/ziran.sh"}
locked=${TERMINAL_PACKAGE_LOCKED:-0}
if test "$locked" = 1 && test -f ziran.local.toml; then
echo 'Terminal: the locked package test requires a checkout without local overrides.' >&2
exit 1
fi
if ! git_root=$(git rev-parse --show-toplevel 2>/dev/null) || test "$git_root" != "$root"; then
echo 'Terminal: the package consumer test requires the actual Terminal Git checkout.' >&2
exit 1
fi
revision=$(git rev-parse --verify HEAD)
lock_flags=
if test ! -f ziran.local.toml; then lock_flags=--locked; fi
compiler=$("$ziran" pkg path ziran $lock_flags)/build/bin/ziran
@@ -15,42 +25,51 @@ trap 'rm -rf "$work"' EXIT HUP INT TERM
mkdir -p "$work/src"
cp tests/package_consumer.zi "$work/src/consumer.zi"
cp tests/terminal_pane_widget_host.zi tests/terminal_clipboard_host.zi "$work/src/"
cat > "$work/ziran.toml" <<'MANIFEST'
[package]
name = "terminal_consumer"
entry = "src/consumer.zi"
module_roots = ["src"]
[toolchain]
git = "https://github.com/ziranlang/ziran.git"
ref = "master"
[dependencies.kryon]
git = "https://github.com/kryonlabs/kryon.git"
ref = "master"
MANIFEST
python3 - "$work/ziran.local.toml" "$root" "$compiler" "$kryon" <<'PY'
python3 - "$work" "$root" "$compiler" "$kryon" "$revision" "$locked" <<'PYTEST'
import json
import pathlib
import sys
path, terminal, compiler, kryon = sys.argv[1:]
toolchain = str(pathlib.Path(compiler).parents[2])
pathlib.Path(path).write_text('[overrides]\n' + ''.join(
f'{name} = {json.dumps(value)}\n'
for name, value in [('ziran', toolchain), ('terminal', terminal), ('kryon', kryon)]))
PY
import tomllib
work, terminal, compiler, kryon, revision, locked = sys.argv[1:]
work = pathlib.Path(work)
terminal = pathlib.Path(terminal)
manifest = tomllib.loads((terminal / 'ziran.toml').read_text())
with (work / 'ziran.toml').open('w') as output:
output.write('[package]\nname = "terminal_consumer"\n'
'entry = "src/consumer.zi"\nmodule_roots = ["src"]\n')
for section, source in (
('toolchain', manifest['toolchain']),
('dependencies.kryon', manifest['dependencies']['kryon']),
('dependencies.terminal', {'git': 'https://git.waozi.xyz/kryonlabs/terminal.git', 'ref': revision}),
):
output.write(f'\n[{section}]\n'
f'git = {json.dumps(source["git"])}\n'
f'ref = {json.dumps(source["ref"])}\n')
if locked != '1':
toolchain = str(pathlib.Path(compiler).parents[2])
(work / 'ziran.local.toml').write_text('[overrides]\n' + ''.join(
f'{name} = {json.dumps(value)}\n'
for name, value in [('ziran', toolchain), ('terminal', str(terminal)), ('kryon', kryon)]))
PYTEST
cd "$work"
"$compiler" add https://github.com/kryonlabs/terminal.git --name terminal
consumer_flags=
if test "${TERMINAL_PACKAGE_LOCKED:-0}" = 1; then
# Test committed Git objects rather than local work in progress.
rm ziran.local.toml
if test "$locked" = 1; then
"$compiler" lock
consumer_flags=--locked
else
# This fixture tests the working sources and their already-resolved dependencies.
"$compiler" lock --offline
fi
python3 - <<'PY'
python3 - "$revision" "$locked" <<'PY'
import json
lock = json.load(open('ziran.lock'))
print('terminal consumer dependency:', next(p['commit'] for p in lock['packages'] if p['name'] == 'terminal'))
import sys
with open('ziran.lock') as source:
lock = json.load(source)
resolved = next(p['commit'] for p in lock['packages'] if p['name'] == 'terminal')
if sys.argv[2] == '1' and resolved != sys.argv[1]:
raise SystemExit('Terminal consumer did not resolve the checked-out release commit')
print('terminal consumer dependency:', resolved)
PY
"$compiler" check --project $consumer_flags src/consumer.zi
printf '%s\n' '#import "terminal/terminal_pane_render"' > src/private.zi
+133 -15
View File
@@ -1,4 +1,4 @@
"""Right-click copy of a dragged selection in the real window on private Xvfb."""
"""PRIMARY publication, right-click copy and xfce-style menu on private Xvfb."""
import os
from pathlib import Path
import shlex
@@ -10,7 +10,13 @@ import time
from standalone_window_test import close_window
COLUMNS, ROWS, TEXT_ROW = 40, 8, 3
# The 21-row xfce4-terminal menu is taller than this window. Kryon keeps menus
# inside the window, pinned to its top, so the window needs 10 rows for the
# Copy row (about 160 units down) to be reachable.
COLUMNS, ROWS, TEXT_ROW = 56, 10, 4
OAUTH = ('https://auth.openai.com/oauth/authorize?response_type=code&client_id=app&'
'redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback&scope=openid&'
'state=state-value-0123456789abcdef&codex_cli_simplified_flow=true')
def wait(predicate, message, seconds=8):
@@ -44,7 +50,7 @@ def selection(env, name):
def main():
assert os.environ.get('TERMINAL_PRIVATE_XVFB') == '1'
assert os.environ['DISPLAY'].startswith(':')
assert os.environ.get('YUE_DESKTOP_RECOVERY') == '0'
assert os.environ.get('HARMONY_DESKTOP_RECOVERY') == '0'
binary = str(Path(sys.argv[1]).resolve())
Path('build/ziran').mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='terminal-selection-copy-', dir='build/ziran') as directory:
@@ -53,7 +59,7 @@ def main():
shell.write_text('#!/bin/sh\nexec /bin/sh -c "$2"\n'); shell.chmod(0o700)
child = root / 'child.py'; incoming = root / 'input'
child.write_text('import os,tty\ntty.setraw(0)\nos.write(1,' + repr(
b'\r\n' * TEXT_ROW + b'alpha beta gamma\r\n') + ')\n'
OAUTH.encode() + b'\r\nalpha beta gamma\r\n') + ')\n'
'with open(' + repr(str(incoming)) + ', "wb", buffering=0) as log:\n'
' while True:\n data=os.read(0,1024)\n if not data: break\n log.write(data)\n')
env = dict(os.environ, XDG_CONFIG_HOME=str(root / 'config'), XDG_STATE_HOME=str(root / 'state'),
@@ -62,10 +68,15 @@ def main():
def xdo(*args):
return subprocess.run(['xdotool', *map(str, args)], env=env, text=True, capture_output=True,
check=True, timeout=5).stdout.strip()
def shift_right_click():
xdo('keydown', 'Shift_L'); xdo('mousedown', '3'); time.sleep(.1)
xdo('mouseup', '3'); xdo('keyup', 'Shift_L'); time.sleep(.2)
with (root / 'window.log').open('w') as log:
app = subprocess.Popen([binary, '--hide-menubar', '--hide-toolbar', '--geometry', f'{COLUMNS}x{ROWS}',
'--shell', str(shell), '-e', 'python3 ' + shlex.quote(str(child))],
env=env, stdout=log, stderr=log)
owners = []
try:
def find():
result = subprocess.run(['xdotool', 'search', '--onlyvisible', '--pid', str(app.pid)],
@@ -74,7 +85,7 @@ def main():
window = wait(find, 'Terminal window and raw child')
assert int(xdo('getwindowpid', window)) == app.pid
geometry = dict(line.split('=', 1) for line in xdo('getwindowgeometry', '--shell', window).splitlines())
cell = int(geometry['WIDTH']) / COLUMNS; line = int(geometry['HEIGHT']) / ROWS
width = int(geometry['WIDTH']); cell = width / COLUMNS; line = int(geometry['HEIGHT']) / ROWS
y = int(line * (TEXT_ROW + .5))
xdo('windowfocus', '--sync', window)
xdo('mousemove', '--window', window, int(cell * 20), int(line * 6.5))
@@ -84,7 +95,60 @@ def main():
first = window_rows(window, env, 0, TEXT_ROW)
return first if first == window_rows(window, env, 0, TEXT_ROW) else None
baseline = wait(stable, 'Stable text rows')
assert selection(env, 'clipboard') != 'beta'
owner = subprocess.Popen(['xclip','-quiet','-selection','clipboard','-in'],env=env,
stdin=subprocess.PIPE,stdout=log,stderr=log)
owners.append(owner); owner.stdin.write(b'clipboard sentinel'); owner.stdin.close(); time.sleep(.2)
# Select all four visual rows of one logical OAuth line. At 56
# columns the wrap splits 1455 and later the state value.
xdo('mousemove', '--window', window, int(cell * .5), int(line * .5))
xdo('mousedown', '1')
for row, column in ((0, 55.5), (1, 55.5), (2, 55.5), (3, 43.5)):
time.sleep(.06)
xdo('mousemove', '--window', window, int(cell * column), int(line * (row + .5)))
time.sleep(.1); xdo('mouseup', '1')
wait(lambda: selection(env, 'primary') == OAUTH,
lambda: f'Wrapped OAuth PRIMARY differs: {selection(env, "primary")!r}')
xdo('keydown', 'Control_L'); xdo('keydown', 'Shift_L'); xdo('key', 'c')
xdo('keyup', 'Shift_L'); xdo('keyup', 'Control_L')
wait(lambda: selection(env, 'clipboard') == OAUTH,
'Keyboard copy did not preserve the exact wrapped OAuth URL')
# Shift+right-click opens the link-aware menu on a selection.
# Copy is the first row after the link actions and open rows.
# Each menu copy starts from a fresh owner, so its check waits
# for that copy instead of passing on the previous one.
owner = subprocess.Popen(['xclip','-quiet','-selection','clipboard','-in'],env=env,
stdin=subprocess.PIPE,stdout=log,stderr=log)
owners.append(owner); owner.stdin.write(b'copy sentinel'); owner.stdin.close(); time.sleep(.2)
assert selection(env, 'clipboard') == 'copy sentinel'
xdo('mousemove', '--window', window, int(cell * 2.5), int(line * 2.5))
shift_right_click()
xdo('mousemove', '--window', window, int(cell * 2.5) + 60, 160)
xdo('mousedown', '1'); time.sleep(.12); xdo('mouseup', '1')
wait(lambda: selection(env, 'clipboard') == OAUTH,
'Shift+right-click menu Copy did not preserve the exact wrapped OAuth selection')
# A plain click leaves no chosen selection, so right-click opens
# the menu. Copy Link Address is row two in the link-aware menu.
xdo('mousemove', '--window', window, int(cell * 20), int(line * 6.5))
xdo('mousedown', '1'); time.sleep(.12); xdo('mouseup', '1'); time.sleep(.6)
owner = subprocess.Popen(['xclip','-quiet','-selection','clipboard','-in'],env=env,
stdin=subprocess.PIPE,stdout=log,stderr=log)
owners.append(owner); owner.stdin.write(b'link sentinel'); owner.stdin.close(); time.sleep(.2)
assert selection(env, 'clipboard') == 'link sentinel'
xdo('mousemove', '--window', window, int(cell * 2.5), int(line * 2.5))
xdo('mousedown', '3'); time.sleep(.1); xdo('mouseup', '3'); time.sleep(.2)
assert selection(env, 'clipboard') == 'link sentinel', 'Right-click after a plain click copied'
xdo('mousemove', '--window', window, int(cell * 2.5) + 60, 43)
xdo('mousedown', '1'); time.sleep(.12); xdo('mouseup', '1')
wait(lambda: selection(env, 'clipboard') == OAUTH,
'Context-menu Copy Link changed the wrapped OAuth URL')
owner = subprocess.Popen(['xclip','-quiet','-selection','clipboard','-in'],env=env,
stdin=subprocess.PIPE,stdout=log,stderr=log)
owners.append(owner); owner.stdin.write(b'clipboard sentinel'); owner.stdin.close(); time.sleep(.2)
xdo('mousemove', '--window', window, int(cell * 6.5), y); time.sleep(.1)
xdo('mousedown', '1')
@@ -92,23 +156,77 @@ def main():
time.sleep(.05); xdo('mousemove', '--window', window, int(cell * (column + .5)), y)
time.sleep(.1); xdo('mouseup', '1')
wait(lambda: window_rows(window, env, 0, TEXT_ROW) != baseline, 'Dragged selection is highlighted')
assert selection(env, 'clipboard') != 'beta', 'Selecting alone must not replace the clipboard'
wait(lambda: selection(env, 'primary') == 'beta',
lambda: f'Selection did not publish PRIMARY: {selection(env, "primary")!r}')
assert selection(env, 'clipboard') == 'clipboard sentinel', 'Selecting alone replaced CLIPBOARD'
# Right-click on a selection copies it to CLIPBOARD, clears its highlight, keeps
# PRIMARY and opens no menu: typed text still reaches the shell.
xdo('mousedown', '3'); time.sleep(.1); xdo('mouseup', '3')
started = time.monotonic()
wait(lambda: selection(env, 'clipboard') == 'beta',
lambda: f'Right-click copies exactly beta, got {selection(env, "clipboard")!r}', 2)
lambda: f'Right-click did not copy exactly beta: {selection(env, "clipboard")!r}', 2)
assert selection(env, 'primary') == 'beta', 'Right-click cleared PRIMARY selection'
wait(lambda: window_rows(window, env, 0, TEXT_ROW) == baseline,
'Right-click clears the visible selection without opening a menu', 2)
cleared = time.monotonic() - started
time.sleep(.6)
assert window_rows(window, env, 0, TEXT_ROW) == baseline, 'Selection stays cleared'
assert incoming.read_bytes() == b'', 'Right-click copy must not write to the child'
'Right-click left highlighted cells after copying')
before = incoming.stat().st_size
xdo('type', 'z')
data = wait(lambda: incoming.read_bytes() if incoming.stat().st_size > before else None,
'Right-click on a selection opened a menu that took the keyboard')
assert data[before:] == b'z', data[before:]
# Re-select before testing the independent HTML action; a menu
# activation must not make that action depend on stale UI state.
time.sleep(.5)
owner = subprocess.Popen(['xclip','-quiet','-selection','primary','-in'],env=env,
stdin=subprocess.PIPE,stdout=log,stderr=log)
owners.append(owner); owner.stdin.write(b'primary sentinel'); owner.stdin.close(); time.sleep(.2)
assert selection(env, 'primary') == 'primary sentinel'
xdo('mousemove', '--window', window, int(cell * 6.5), y)
xdo('mousedown', '1')
for column in (7, 8, 9):
time.sleep(.05); xdo('mousemove', '--window', window, int(cell * (column + .5)), y)
time.sleep(.1); xdo('mouseup', '1')
wait(lambda: selection(env, 'primary') == 'beta', 'Second selection did not publish PRIMARY')
# Copy as HTML, from the Shift+right-click menu, owns both safe
# plain text and escaped HTML.
xdo('mousemove', '--window', window, int(cell * 8), y)
shift_right_click()
xdo('mousemove', '--window', window, int(cell * 8) + 60, 130)
xdo('mousedown', '1'); time.sleep(.12); xdo('mouseup', '1')
def clipboard_html():
result = subprocess.run(['xclip','-selection','clipboard','-target','text/html','-out'],
env=env,capture_output=True,timeout=5)
return result.stdout if result.returncode == 0 else None
html = wait(clipboard_html, 'Copy as HTML did not offer text/html')
assert html == b'<pre>beta</pre>', html
assert selection(env, 'clipboard') == 'beta'
# An external PRIMARY owner is used by middle-click and
# Shift+Insert; neither falls back to CLIPBOARD.
owner = subprocess.Popen(['xclip','-quiet','-selection','primary','-in'],env=env,
stdin=subprocess.PIPE,stdout=log,stderr=log)
owners.append(owner); owner.stdin.write(b'external primary'); owner.stdin.close(); time.sleep(.2)
assert selection(env, 'primary') == 'external primary'
before = incoming.stat().st_size
xdo('mousemove', '--window', window, int(cell * 20), int(line * 6.5))
xdo('mousedown', '2'); time.sleep(.12); xdo('mouseup', '2')
data = wait(lambda: incoming.read_bytes() if incoming.stat().st_size > before else None,
'Middle-click did not paste external PRIMARY')
assert data[before:].replace(b'\x1b[200~',b'').replace(b'\x1b[201~',b'') == b'external primary'
before = len(data)
xdo('keydown','shift'); xdo('key','Insert'); xdo('keyup','shift')
data = wait(lambda: incoming.read_bytes() if incoming.stat().st_size > before else None,
'Shift+Insert did not paste PRIMARY')
assert data[before:].replace(b'\x1b[200~',b'').replace(b'\x1b[201~',b'') == b'external primary'
close_window(window, app.pid, env); app.wait(timeout=5)
finally:
for owner in owners:
if owner.poll() is None: owner.terminate()
owner.wait(timeout=5)
if app.poll() is None:
app.terminate(); app.wait(timeout=5)
print(f'Terminal right-click copied the dragged selection and cleared it in {cleared:.2f}s on private Xvfb')
print('Terminal publishes PRIMARY, copies a selection on right-click, opens the menu without one or with Shift, serves plain+HTML menu copies, and pastes external PRIMARY only')
if __name__ == '__main__':
+2 -4
View File
@@ -10,16 +10,14 @@ if test ! -f ziran.local.toml; then lock_flags=--locked; fi
mkdir -p build/ziran
work=$(mktemp -d "$root/build/ziran/standalone-test.XXXXXX")
trap 'rm -rf "$work"' EXIT HUP INT TERM
archive=${RAYLIB_A:-"$root/build/linux-$(uname -m)/raylib/raylib/libraylib.a"}
test -f "$archive"
"$ziran" ir --project $lock_flags --entry app_main:main -o "$work/ir" src/app/app_main.zi
for form in source saved; do
input=src/app/app_main.zi
if test "$form" = saved; then input=$work/ir/app_main.zir; fi
output=$work/$form-c
ZIRAN="$ziran" RAYLIB_A="$archive" sh scripts/build.sh c "$output" "$input"
ZIRAN="$ziran" sh scripts/build.sh c "$output" "$input"
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER \
LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24' \
HARMONY_DESKTOP_RECOVERY=0 LP_NUM_THREADS=1 OMP_NUM_THREADS=1 xvfb-run -a -s '-screen 0 1024x768x24' \
env TERMINAL_PRIVATE_XVFB=1 python3 tests/standalone_window_test.py "$output/bin/terminal"
done
echo 'Terminal executable source and saved IR passed real C window and child-process checks'
+26 -4
View File
@@ -157,16 +157,38 @@ def main():
while time.monotonic() < deadline and output.read_bytes() != b"Ziran":
time.sleep(0.05)
assert output.read_bytes() == b"Ziran", (output.read_bytes(), log.read_text())
run(["xdotool", "key", "Return"], env)
deadline = time.monotonic() + 3
while time.monotonic() < deadline and output.read_bytes() != b"Ziran\r":
time.sleep(0.05)
assert output.read_bytes() == b"Ziran\r", (
"Physical Return did not reach the terminal child as carriage return",
output.read_bytes(), log.read_text())
# Several editing keys can arrive in one desktop poll. Every
# queued key must get its own UI frame without waiting for an
# unrelated later event to wake the window again.
run(["xdotool", "key", "--delay", "0", "Left", "Right", "Return"], env)
expected = b"Ziran\r\x1b[D\x1b[C\r"
deadline = time.monotonic() + 0.3
while time.monotonic() < deadline and output.read_bytes() != expected:
time.sleep(0.01)
assert output.read_bytes() == expected, (
"A batched editing key remained queued after the input frames",
output.read_bytes(), log.read_text())
typed = len(expected)
run(["xset", "r", "rate", "250", "12"], env)
run(["xdotool", "keydown", "ctrl", "keydown", "a"], env)
time.sleep(0.15)
early = output.read_bytes()[5:]
early = output.read_bytes()[typed:]
assert early == b"\x01", ("Held key flooded the child", early)
time.sleep(0.6)
run(["xdotool", "keyup", "a", "keyup", "ctrl"], env)
time.sleep(0.15)
repeated = output.read_bytes()[5:]
assert 2 <= len(repeated) <= 12 and set(repeated) == {1}, repeated
repeated = output.read_bytes()[typed:]
# Xvfb may coalesce or catch up repeat events around a slower
# saved-IR startup. The delay check above rejects pre-repeat
# flooding; here every delivered event must be the held key.
assert 2 <= len(repeated) <= 24 and set(repeated) == {1}, repeated
before = output.read_bytes()
# A modifier tap and shortcut can arrive during one frame.
# Neither may discard the following menu shortcut.
@@ -187,7 +209,7 @@ def main():
except subprocess.TimeoutExpired:
app.kill()
app.wait(timeout=3)
print("Terminal executable: CLI, real graphics, child input, held/repeated keys, menu ownership and owned-window close passed")
print("Terminal executable: CLI, real graphics, child text/Return and batched key input, held/repeated keys, menu ownership and owned-window close passed")
if __name__ == "__main__":
+41 -18
View File
@@ -24,10 +24,11 @@ UISessions :: #import "kryon/session";
Frame :: #import "kryon/Frame";
Input :: #import "kryon/tree_input";
using Geometry :: #import "kryon/geometry";
Fields :: #import "kryon/text_input_props";
Fields :: #import "kryon/text_field";
Context :: #import "app_context_menu";
MenuWidget :: #import "kryon/context_menu";
Menu :: #import "app_menu";
Widgets :: #import "kryon/Widgets";
Widgets :: #import "kryon/menu";
Tree :: #import "kryon/tree";
File :: #import "std/file_linux";
@@ -385,7 +386,7 @@ CheckSearchDialog :: () -> bool {
CheckPromptStorage :: () -> bool {
output: [8]u8
Session.CopyText(output[:], "abcd")
edit: Fields.TextFieldEdit
edit: Fields.Edit
edit.changed = true; edit.start = 1; edit.end = 2
edit.replacement = Value(output[:])[0:3]
if !Dialog.ApplyEdit(output[:], edit) || Value(output[:]) != "aabccd" { return Failure("Borrowed prompt edit") }
@@ -417,6 +418,22 @@ ClickKey :: (frame: UISessions.Session, key: u64) -> bool {
}
return false
}
// Rows are found by label in the menu Terminal builds, so the checks follow
// the xfce4-terminal structure instead of fixed pixel offsets.
ContextRowKey :: (app: *State.State, label: string) -> u64 {
items: [57]MenuWidget.ContextMenuItem
count := Context.BuildItems(app, *app.sessions[app.active], items[:])
for index: 0..count - 1 {
if items[index].parent == 0 && !items[index].separator && items[index].label == label {
return MenuWidget.ContextMenuRowKey(cast(u64)1300, index)
}
}
return cast(u64)0
}
ClickContext :: (frame: UISessions.Session, app: *State.State, label: string) -> bool {
key := ContextRowKey(app, label)
return key != cast(u64)0 && ClickKey(frame, key)
}
CheckContextMenu :: () -> bool {
app := Application()
if app == null { return false }
@@ -429,15 +446,15 @@ CheckContextMenu :: () -> bool {
app.session_count = 1; app.active = 0
app.context_menu_x = 20; app.context_menu_y = 20; app.context_menu_open = true
if !DrawContext(frame, app) { return false }
Click(frame, 40.0, 63.0)
if !DrawContext(frame, app) || !app.context_menu_open || app.session_count != 1 {
return Failure("Context menu disabled last-tab close")
}
Host.HostClipboardReset("keep clipboard")
Click(frame, 40.0, 98.0)
if !DrawContext(frame, app) || !app.context_menu_open || Host.HostClipboardText() != "keep clipboard" {
if !ClickContext(frame, app, "Copy") || !DrawContext(frame, app) || !app.context_menu_open ||
Host.HostClipboardText() != "keep clipboard" {
return Failure("Context menu disabled copy")
}
if !ClickContext(frame, app, "Copy as HTML") || !DrawContext(frame, app) || !app.context_menu_open ||
Host.HostClipboardText() != "keep clipboard" {
return Failure("Context menu disabled copy as HTML")
}
Input.TypedCodepointSend(frame, #char "x")
Input.KeyboardSend(frame, Input.KeyEscape)
if !DrawContext(frame, app) || app.context_menu_open || Input.TypedCodepointTake(frame) != 0 {
@@ -445,15 +462,21 @@ CheckContextMenu :: () -> bool {
}
app.context_menu_open = true
if !DrawContext(frame, app) { return false }
Click(frame, 40.0, 37.0)
if !DrawContext(frame, app) || app.context_menu_open || app.session_count != 2 || app.active != 1 {
return Failure("Context menu new tab")
if !ClickContext(frame, app, "Open Tab") || !DrawContext(frame, app) || app.context_menu_open ||
app.session_count != 2 || app.active != 1 {
return Failure("Context menu open tab")
}
app.context_menu_open = true
if !DrawContext(frame, app) { return false }
Click(frame, 40.0, 63.0)
if !DrawContext(frame, app) || app.context_menu_open || app.session_count != 1 {
return Failure("Context menu close tab")
if !ClickContext(frame, app, "Read-Only") || !DrawContext(frame, app) || app.context_menu_open ||
!app.sessions[1].read_only || app.sessions[0].read_only {
return Failure("Context menu read-only check")
}
app.context_menu_open = true
if !DrawContext(frame, app) { return false }
if !ClickContext(frame, app, "Read-Only") || !DrawContext(frame, app) || app.context_menu_open ||
app.sessions[1].read_only {
return Failure("Context menu read-only uncheck")
}
app.context_menu_open = true
if !DrawContext(frame, app) { return false }
@@ -461,9 +484,9 @@ CheckContextMenu :: () -> bool {
if !DrawContext(frame, app) || app.context_menu_open { return Failure("Context menu outside dismissal") }
app.context_menu_open = true
if !DrawContext(frame, app) { return false }
Click(frame, 40.0, 210.0)
if !DrawContext(frame, app) || app.context_menu_open || !app.search_visible || !app.search_focused {
return Failure("Context menu Find command")
if !ClickContext(frame, app, "Preferences...") || !DrawContext(frame, app) || app.context_menu_open ||
app.menu.open_index != 3 || !app.menu.focused {
return Failure("Context menu Preferences command")
}
return true
}
+1 -1
View File
@@ -4,7 +4,7 @@ set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS ENV BASH_ENV
export YUE_DESKTOP_RECOVERY=0
export HARMONY_DESKTOP_RECOVERY=0
work="$root/build/ziran/capture-cost"
mkdir -p "$work"
exec 9>"$work/check.lock"
+1
View File
@@ -1,6 +1,7 @@
// Linux diagnostic for Harmony's detached capture/reflow sequence. Timed
// stages are inclusive native wall/thread CPU costs, not full interaction.
Engine :: #import "terminal";
ClipboardHost :: #import "terminal_clipboard_host";
Timer :: #import "std/timer_linux";
Text :: #import "std/byte_text_linux";
#import "std/text"
+1
View File
@@ -1,6 +1,7 @@
// A remote page owns only its requested history capacity. Default captures
// keep their established limit, and failed replacements keep complete state.
#import "terminal"
ClipboardHost :: #import "terminal_clipboard_host";
Text :: #import "std/byte_text_linux"
libc :: #system_library "c";
CompareRaw :: (a: *void, b: *void, count: usize) -> s32 #foreign libc "memcmp";
+1
View File
@@ -1,6 +1,7 @@
// Balanced current-engine comparison; both modes use identical capture and
// reflow code. Only detached-storage reset differs, with no extra cache.
Engine :: #import "terminal";
ClipboardHost :: #import "terminal_clipboard_host";
Cost :: #import "terminal_capture_cost_probe";
libc :: #system_library "c";
ReleaseCorpus :: (bytes: *void) #foreign libc "free";
+1 -1
View File
@@ -3,7 +3,7 @@ set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS ENV BASH_ENV
export YUE_DESKTOP_RECOVERY=0
export HARMONY_DESKTOP_RECOVERY=0
work="$root/build/ziran/capture-storage"
mkdir -p "$work"
exec 9>"$work/check.lock"
+1
View File
@@ -1,6 +1,7 @@
// Storage reuse must behave exactly like a newly allocated detached engine,
// including full-parser controls, later PTY feeds and source/view reflow.
#import "terminal";
ClipboardHost :: #import "terminal_clipboard_host";
Capture :: #import "terminal_capture_test";
libc :: #system_library "c";
CompareRaw :: (left: *void, right: *void, count: usize) -> s32 #foreign libc "memcmp";
+35 -1
View File
@@ -1,6 +1,7 @@
// Compare the complete emulator state to the original normalized replay,
// including history rings, blank styles, delayed wrapping and later feeds.
#import "terminal";
ClipboardHost :: #import "terminal_clipboard_host";
Text :: #import "std/byte_text_linux";
#import "std/text"
@@ -14,12 +15,23 @@ Bytes :: (value: string) -> *u8 {
Feed :: (terminal: *Terminal, value: string) {
terminal_feed(terminal, cast(*void)Bytes(value), cast(s32)value.count)
}
// A captured row starts blank in default colors; the attributes carried
// across its newline apply only to the cells written after it.
Newline :: (terminal: *Terminal) {
fg := terminal.current_fg; bg := terminal.current_bg; underline := terminal.current_underline
style := terminal.current_style; hyperlink := terminal.current_hyperlink
terminal.current_fg = COLOR_DEFAULT; terminal.current_bg = COLOR_DEFAULT
terminal.current_underline = COLOR_DEFAULT; terminal.current_style = 0; terminal.current_hyperlink = 0
Feed(terminal, "\r\n")
terminal.current_fg = fg; terminal.current_bg = bg; terminal.current_underline = underline
terminal.current_style = style; terminal.current_hyperlink = hyperlink
}
Replay :: (terminal: *Terminal, value: string, trim: bool) {
end := cast(s32)value.count
if trim && end > 0 && value[end - 1] == 10 { end -= 1 }
start: s32
for index: 0..end - 1 {
if value[index] == 10 { Feed(terminal, value[start:index]); Feed(terminal, "\r\n"); start = index + 1 }
if value[index] == 10 { Feed(terminal, value[start:index]); Newline(terminal); start = index + 1 }
}
Feed(terminal, value[start:end])
}
@@ -176,6 +188,28 @@ main :: () -> s32 {
}
}
}
// tmux capture-pane -e keeps a row's final attributes across its newline
// and trims trailing blanks. A green row must not paint the next rows.
for size: 0..cast(s32)1 {
green: Vec(u8)
rows: s32 = ifx size == 0 then 6 else 60
for row: 0..rows - 1 { BuilderPrint(*green, "row %\n", row) }
BuilderPrint(*green, "a\x1b[42mgreen line\n\x1b[49mafter\n\x1b[30m\x1b[42m[status]\nkept\x1b[49m plain\n")
value := BuilderFinish(green)
defer { Release(value) }
colors: Terminal; terminal_init(*colors); terminal_resize(*colors, 40, 8)
ok := terminal_feed_capture(*colors, cast(*void)Bytes(value), cast(s32)value.count, true)
after := terminal_visible_line_count(*colors) - 3
for col: 5..cast(s32)39 { ok = ok && terminal_visible_cell(*colors, col, after).bg == COLOR_DEFAULT }
ok = ok && terminal_visible_cell(*colors, 20, after - 1).bg == COLOR_DEFAULT
for col: 8..cast(s32)39 { ok = ok && terminal_visible_cell(*colors, col, after + 1).bg == COLOR_DEFAULT }
// Unchanged attributes continue: tmux emits nothing for them.
kept := terminal_visible_cell(*colors, 0, after + 2)
ok = ok && kept.bg == 2 && kept.fg == 0 && terminal_visible_cell(*colors, 30, after + 2).bg == COLOR_DEFAULT
ok = ok && terminal_visible_cell(*colors, 1, after - 1).bg == 2 && terminal_visible_cell(*colors, 0, after + 1).bg == 2
terminal_close(*colors)
if !ok { print("Captured row colors leaked across newlines: %\n", rows); return 1 }
}
detached: Terminal; terminal_init(*detached); terminal_resize(*detached, 80, 24)
if !terminal_feed_capture(*detached, null, 0, true) ||
terminal_feed_capture(*detached, null, 1, false) ||
+28
View File
@@ -6,6 +6,8 @@ available: bool = true;
reject_write: bool;
read_count: s32;
write_count: s32;
primary: [262144]u8;
primary_length: s64;
HostClipboardReset :: (text: string) {
for index: cast(s64)0..text.count - 1 { stored[index] = text[index] }
@@ -18,6 +20,12 @@ HostClipboardReset :: (text: string) {
HostClipboardText :: () -> string { return TextView(stored[0:stored_length]) }
HostPrimaryReset :: (text: string) {
for index: cast(s64)0..text.count - 1 { primary[index] = text[index] }
primary_length = text.count
available = true
}
#program_export
SystemClipboardOpenHost :: () -> s32 {
read_count += 1
@@ -39,3 +47,23 @@ SystemClipboardWriteHost :: (text: string) -> bool {
write_count += 1
return true
}
#program_export
SystemPrimaryOpenHost :: () -> s32 {
if !available { return -1 }
return cast(s32)primary_length
}
#program_export
SystemPrimaryByteHost :: (index: s32) -> s32 {
if !available || index < 0 || cast(s64)index >= primary_length { return -1 }
return cast(s32)primary[index]
}
#program_export
SystemPrimaryWriteHost :: (text: string) -> bool {
if !available || text.count >= primary.count { return false }
for index: cast(s64)0..text.count - 1 { primary[index] = text[index] }
primary_length = text.count
return true
}
+5
View File
@@ -162,6 +162,11 @@ Cases :: () -> s32 {
Reset()
if WriteClipboardSourcePaste(*clipboard, CLIPBOARD_SOURCE_PRIMARY_OR_CLIPBOARD, 0, WriteInput, null) != 1 ||
Captured() != "primary" { return 26 }
Host.HostPrimaryReset("external primary")
Reset()
if WriteClipboardSourcePaste(*clipboard, CLIPBOARD_SOURCE_PRIMARY, 0, WriteInput, null) != 1 ||
Captured() != "external primary" ||
!Query("p;?", "\x1b]52;p;ZXh0ZXJuYWwgcHJpbWFyeQ==\a") { return 32 }
SetPrimarySelectionFromText(null)
Reset()
if WriteClipboardSourcePaste(*clipboard, CLIPBOARD_SOURCE_PRIMARY_OR_CLIPBOARD, 0, WriteInput, null) != 1 ||
+1
View File
@@ -1,5 +1,6 @@
// Bulk transport chunks must match the parser's byte-at-a-time semantics.
#import "terminal";
ClipboardHost :: #import "terminal_clipboard_host";
Text :: #import "std/byte_text_linux";
Bytes :: (text: string) -> *u8 {
+36 -13
View File
@@ -3,7 +3,7 @@ Sessions :: #import "app_sessions";
Session :: #import "app_session";
Input :: #import "app_input";
Menu :: #import "app_menu";
Menus :: #import "kryon/menu_props";
Menus :: #import "kryon/menu";
Engine :: #import "terminal";
Keys :: #import "terminal_pane_keys";
Types :: #import "terminal_pane_profile_types";
@@ -107,8 +107,9 @@ CheckKeyboard :: () -> bool {
app.config.delete_binding = Types.TERMINAL_PANE_KEY_BINDING_ASCII_DELETE
if SendKey(app, UI.KeyDelete).wrote != 1 || !Observe(terminal, "\x7f") { return Failure("Configured Delete binding") }
Host.HostClipboardReset("insert paste")
Data.SetPrimarySelectionFromText(Bytes("insert primary"))
SendKey(app, UI.KeyInsert, Keys.TERMINAL_PANE_MOD_CTRL | Keys.TERMINAL_PANE_MOD_SHIFT)
if !Observe(terminal, "insert paste") { return Failure("Shift-Insert paste takes priority over Control-Insert copy") }
if !Observe(terminal, "insert primary") { return Failure("Shift-Insert uses PRIMARY despite Control") }
terminal.focus_reporting = 1
frame = Device(); frame.focused = false
Input.Handle(app, frame, false)
@@ -170,7 +171,7 @@ CheckPointerProtocols :: () -> bool {
Data.SetPrimarySelectionFromText(Bytes(""))
frame.wheel = 0.0; frame.middle = .{true, true, true}
Input.Handle(app, frame, false)
if !Observe(terminal, "system paste") { return Failure("Middle-button clipboard fallback") }
if !NoBytes(terminal) { return Failure("Middle-button must not fall back to CLIPBOARD") }
Data.SetPrimarySelectionFromText(Bytes("primary paste"))
Input.Handle(app, frame, false)
if !Observe(terminal, "primary paste") { return Failure("Middle-button primary preference") }
@@ -200,25 +201,44 @@ CheckSelectionAndScroll :: () -> bool {
}
Host.HostClipboardReset("")
copy_frame := Device(); copy_frame.right = .{true, true, true}
terminal.mouse_mode = 1000
Input.Handle(app, copy_frame, false)
terminal.mouse_mode = 0
if app.context_menu_open || Host.HostClipboardText() != "beta" || Host.write_count != 1 || app.selection.active != 0 || app.selection.dragging != 0 {
return Failure("Right-click copies selection without opening menu")
Clipboard.FlushToHost(*app.sessions[0])
if app.context_menu_open { return Failure("Right-click on a selection opened the menu") }
if Host.HostClipboardText() != "beta" { return Failure("Right-click on a selection did not copy it to CLIPBOARD") }
if Host.write_count != 1 || app.selection.active != 0 || app.selection.dragging != 0 {
return Failure("Right-click on a selection must copy once and clear the selection")
}
Select.TerminalPaneSelectionBeginChar(*app.selection, 6, 2)
app.selection.dragging = 0
// Shift+right-click opens the menu instead, so its actions still work on
// a selection, and it neither copies nor clears it.
frame.now = 1.2
Input.Handle(app, frame, false)
Host.HostClipboardReset("kept")
Input.Handle(app, copy_frame, false)
if app.context_menu_open || Host.HostClipboardText() != "kept" || Host.write_count != 0 || app.selection.active == 0 {
return Failure("Right-click keeps a selection that copied nothing")
shifted := copy_frame; shifted.keyboard.mods = Keys.TERMINAL_PANE_MOD_SHIFT
Input.Handle(app, shifted, false)
Clipboard.FlushToHost(*app.sessions[0])
if !app.context_menu_open || Host.HostClipboardText() != "kept" || Host.write_count != 0 ||
app.selection.active == 0 {
return Failure("Shift+right-click opens the menu and keeps the selection and clipboard")
}
app.context_menu_open = false
app.selection.active = 0
frame.now = 1.3
Input.Handle(app, frame, false)
if Clipboard.CollectSelection(app, output[:]) == 0 || Text.TextFromCString(*output[0]) != "alpha beta gamma" {
return Failure("Triple-click line selection")
}
// A plain click selects only the cell under it; right-click then still
// opens the menu and copies nothing.
app.selection.active = 0
click := Device(); click.left = .{true, true, true}; click.now = 5.0
Input.Handle(app, click, false)
Host.HostClipboardReset("kept")
Input.Handle(app, copy_frame, false)
Clipboard.FlushToHost(*app.sessions[0])
if !app.context_menu_open || Host.HostClipboardText() != "kept" || Host.write_count != 0 {
return Failure("Right-click after a plain click opens the menu and copies nothing")
}
app.context_menu_open = false
app.selection.active = 0
for index: 0..29 { Feed(terminal, "\r\nmore") }
frame = Device(); frame.wheel = 1000000.0
@@ -254,7 +274,10 @@ CheckSelectionAndScroll :: () -> bool {
Feed(terminal, "\x1b[2J\x1b[Hhttps://example.org")
frame.left = .{true, true, false}
terminal.mouse_mode = 1000; terminal.mouse_sgr = 1
if Input.Handle(app, frame, false).hyperlink != "https://example.org" { return Failure("Alt-click visible URL in reporting TUI") }
visible_link := Input.Handle(app, frame, false)
if visible_link.hyperlink != "https://example.org" || !visible_link.link_hovered {
return Failure("Alt-click and hover visible URL in reporting TUI")
}
frame.left = .{false, false, true}
if Input.Handle(app, frame, false).hyperlink != "" || !NoBytes(terminal) { return Failure("Link click leaked a half mouse event") }
// Embedded hosts can deliver an Alt-click before X focus transfers.
+26
View File
@@ -137,6 +137,31 @@ SessionChecks :: () -> bool {
return ok
}
// Kryon's desktop input take hands over Enter together with the text typed
// before it. Two lines typed within one frame each must reach the shell as
// their own line, text before Enter.
TypedLineChecks :: () -> bool {
session := Sessions.SessionOpen()
if !Sessions.SessionValid(session) { return false }
Input.KeyboardModifiersSend(session, 0)
mode: TerminalPaneKeyMode
state: TerminalPaneInputState
input := MakeTerminalPaneInput(mode, Writer, null, *state)
key: [1]s32
text: [32]u32
ResetWrites()
lines: [2]string = .["ls", "pwd"]
ok := true
for line: 0..1 {
for at: 0..cast(s32)lines[line].count - 1 { Input.TypedCodepointSend(session, cast(s32)lines[line][at]) }
Input.KeyboardSend(session, Input.KeyEnter)
frame := Keyboard.CaptureKeyboardFrame(session, key[:], text[:])
ok = ok && PumpTerminalPaneKeyboardInput(input, frame) == 1
}
Sessions.SessionClose(session)
return ok && SameBytes(*received[0], received_length, "ls\rpwd\r")
}
#program_export
main :: () -> s32 {
mode: TerminalPaneKeyMode
@@ -194,6 +219,7 @@ main :: () -> s32 {
}
if !InputChecks() { print("input routing failed\n"); return 11 }
if !SessionChecks() { print("Kryon session input failed\n"); return 12 }
if !TypedLineChecks() { print("text typed before Enter reached the shell after it\n"); return 13 }
print("Terminal keyboard protocol, bounds, callbacks and Kryon input passed (% capacity checks)\n", checks)
return 0
}
+18 -2
View File
@@ -3,7 +3,7 @@ Host :: #import "terminal_clipboard_host";
#import "terminal_pane_selection"
SelectionFixture :: struct {
lines: [4][64]u8
lines: [4][256]u8
wrapped: [4]s32
count: s32
}
@@ -56,7 +56,7 @@ main :: () -> s32 {
InitClipboardBuffer(*clipboard, null)
Host.HostClipboardReset("")
selection: TerminalPaneSelection
text: [256]u8
text: [512]u8
match: TerminalPaneSearchMatch
controller: TerminalPaneSearchController
scroll_offset: s32 = 99
@@ -146,5 +146,21 @@ main :: () -> s32 {
if TerminalPaneSearchLines(FixtureLineText, cast(*void)*fixture, 4,
*text[0], 0, 0, -1, 1, *match) != 1 || match.row != 3 ||
match.col != 6 { return 16 }
oauth := "https://auth.openai.com/oauth/authorize?response_type=code&client_id=app&redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback&scope=openid&state=state-value-0123456789abcdef&codex_cli_simplified_flow=true"
Fill(*fixture.lines[0][0], oauth[0:56])
Fill(*fixture.lines[1][0], oauth[56:112])
Fill(*fixture.lines[2][0], oauth[112:168])
Fill(*fixture.lines[3][0], oauth[168:])
fixture.wrapped[0] = 1; fixture.wrapped[1] = 1; fixture.wrapped[2] = 1
TerminalPaneSelectionSetRange(*selection, TERMINAL_PANE_SELECTION_CHAR,
0, 0, 0, 3, cast(s32)oauth.count - 168)
if TerminalPaneSelectionCollectText(*selection, FixtureLineText,
FixtureWrapped, cast(*void)*fixture, *text[0], 512) != 1 ||
!Same(*text[0], oauth) { return 17 }
fixture.wrapped[1] = 0
hard := "https://auth.openai.com/oauth/authorize?response_type=code&client_id=app&redirect_uri=http%3A%2F%2Flocalhost%3A1\n455%2Fauth%2Fcallback&scope=openid&state=state-value-0123456789abcdef&codex_cli_simplified_flow=true"
if TerminalPaneSelectionCollectText(*selection, FixtureLineText,
FixtureWrapped, cast(*void)*fixture, *text[0], 512) != 1 ||
!Same(*text[0], hard) { return 18 }
return 0
}
+37 -1
View File
@@ -358,7 +358,7 @@ TestLinks :: () -> bool {
Engine.terminal_resize(*terminal, 20, 4)
url := "https://example.org/a(b)?next=https://example.net#part"
Feed(*terminal, "Open ("); Feed(*terminal, url); Feed(*terminal, "). tail")
bytes: [128]u8
bytes: [8192]u8
for i: 0..cast(s32)url.count - 1 {
at := 6 + i
if Pane.TerminalPaneLinkAt(*terminal, null, at % 20, at / 20, bytes[:]) != url { print("wrapped link cell %\n", i); return false }
@@ -380,6 +380,42 @@ TestLinks :: () -> bool {
if Pane.TerminalPaneLinkAt(*terminal, null, -1, row, bytes[:]) != "" { return false }
Feed(*terminal, "\x1b[2J\x1b[Hhttps://\r\nexample.org")
if Pane.TerminalPaneLinkAt(*terminal, null, 2, row, bytes[:]) != "" { return false }
Feed(*terminal, "\x1b[2J\x1b[Hmail [email protected] now")
row = Engine.terminal_visible_line_count(*terminal) - terminal.rows
if Pane.TerminalPaneLinkAt(*terminal, null, 8, row, bytes[:]) !=
"mailto:[email protected]" { return false }
Feed(*terminal, "\r\nnext\r\nnext\r\nnext\r\nnext")
if Pane.TerminalPaneLinkAt(*terminal, null, 12, row, bytes[:]) !=
"mailto:[email protected]" { return false }
oauth := "https://auth.openai.com/oauth/authorize?response_type=code&client_id=app&redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback&scope=openid&state=state-value-0123456789abcdef&codex_cli_simplified_flow=true"
oauth_terminal: Engine.Terminal; Engine.terminal_init(*oauth_terminal)
defer Engine.terminal_close(*oauth_terminal)
Engine.terminal_resize(*oauth_terminal, 56, 6)
Feed(*oauth_terminal, oauth)
// Column 56 splits 1455 after its first digit and splits the state value.
for i: 0..cast(s32)oauth.count - 1 {
if Pane.TerminalPaneLinkAt(*oauth_terminal, null, i % 56, i / 56,
bytes[:]) != oauth { print("OAuth wrapped link cell %\n", i); return false }
}
unicode := "https://example.org/café/界?q=%E2%9C%93"
unicode_terminal: Engine.Terminal; Engine.terminal_init(*unicode_terminal)
defer Engine.terminal_close(*unicode_terminal)
Engine.terminal_resize(*unicode_terminal, 20, 4)
Feed(*unicode_terminal, unicode)
if Pane.TerminalPaneLinkAt(*unicode_terminal, null, 0, 0, bytes[:]) != unicode {
print("Unicode link first row failed\n"); return false
}
if Pane.TerminalPaneLinkAt(*unicode_terminal, null, 5, 1, bytes[:]) != unicode {
print("Unicode link wide cell failed\n"); return false
}
if Pane.TerminalPaneLinkAt(*unicode_terminal, null, 6, 1, bytes[:]) != unicode {
print("Unicode link continuation failed\n"); return false
}
hard_terminal: Engine.Terminal; Engine.terminal_init(*hard_terminal)
defer Engine.terminal_close(*hard_terminal)
Engine.terminal_resize(*hard_terminal, 64, 3)
Feed(*hard_terminal, "https://auth.openai.com/oauth/authorize?\r\nstate=hard-break")
if Pane.TerminalPaneLinkAt(*hard_terminal, null, 2, 1, bytes[:]) != "" { return false }
return true
}
+27
View File
@@ -0,0 +1,27 @@
using Bundle :: #import "std/bundle_host";
PtyHost :: #import "terminal_pty_linux_host";
main :: (argc: s32, argv: **u8) -> s32 {
if argc != 2 { return 2 }
bundle := OpenBundle(argv[1])
if bundle == null { return 2 }
defer CloseBundle(bundle)
host: PtyHost.PtyHost
defer PtyHost.Dispose(*host)
bindings: [PtyHost.BindingCount]HostBinding
if !PtyHost.FillBindings(*host, bindings[:]) { return 2 }
instance := InstantiateBundle(bundle, *bindings[0], cast(u64)bindings.count)
if instance == null { return 2 }
defer CloseBundleInstance(instance)
status: s64 = -1
has_status: s32
ran := RunBundleInstance(instance, *status, *has_status)
if ran == 0 || has_status == 0 || status != 0 {
print("PTY ZX test failed (ran=%, result=%, status=%)\n", ran, has_status, status)
return 1
}
print("ZX PTY started the shell, read its prompt, wrote input, resized, and closed.\n")
return 0
}
+30
View File
@@ -0,0 +1,30 @@
Pty :: #import "terminal_pty_host";
WaitFor :: (handle: s32, pattern: string) -> bool {
buffer: [128]u8
matched: s32
for attempt: 0..49 {
unused attempt
count := Pty.PtyRead(handle, buffer[:], 20)
if count < 0 { return false }
for index: 0..count - 1 {
if buffer[index] == pattern[matched] { matched += 1 }
else { matched = 0 }
if matched == pattern.count { return true }
}
}
return false
}
main :: () -> s32 {
handle := Pty.PtyOpen("/", "/bin/sh", "printf 'READY:'; read word; printf 'GOT:%s\\n' \"$word\"; stty size", 40, 8)
if handle <= 0 { return 1 }
if !WaitFor(handle, "READY:") { return 2 }
if !Pty.PtyResize(handle, 75, 17) { return 3 }
input: [6]u8 = .{115, 104, 101, 108, 108, 10}
if Pty.PtyWrite(handle, input[:]) != 6 { return 4 }
if !WaitFor(handle, "GOT:shell\r\n17 75") { return 5 }
if !Pty.PtyClose(handle) { return 6 }
if Pty.PtyResize(handle, 40, 8) { return 7 }
return 0
}
+37
View File
@@ -0,0 +1,37 @@
using Bundle :: #import "std/bundle_host";
using Timer :: #import "std/timer_linux";
Screen :: #import "terminal_screen_linux_host";
#import "terminal_clipboard_host";
main :: (argc: s32, argv: **u8) -> s32 {
if argc != 2 { return 2 }
bundle := OpenBundle(argv[1])
if bundle == null { return 2 }
defer CloseBundle(bundle)
host: Screen.ScreenHost
defer Screen.Dispose(*host)
bindings: [Screen.BindingCount]HostBinding
if !Screen.FillBindings(*host, bindings[:]) { return 2 }
instance := InstantiateBundle(bundle, *bindings[0], cast(u64)bindings.count)
if instance == null { return 2 }
defer CloseBundleInstance(instance)
for attempt: 0..99 {
unused attempt
status: s64 = -1
has_status: s32
if RunBundleInstance(instance, *status, *has_status) == 0 || has_status == 0 { return 1 }
if status == 0 {
print("Terminal ZX guest read a styled emulator cell, resized the emulator and read shell output.\n")
return 0
}
if status != -1 {
print("Terminal screen ZX test returned %\n", status)
return 1
}
if !SleepMilliseconds(20) { return 1 }
}
print("Terminal screen ZX test timed out waiting for shell output.\n")
return 1
}
+33
View File
@@ -0,0 +1,33 @@
Screen :: #import "terminal_screen_host";
handle: s32;
phase: s32;
main :: () -> s32 {
if phase == 0 {
handle = Screen.ScreenOpen("/", "/bin/sh",
"printf '\\033[31mR\\033[0m'; read word; printf '\\033[2;1H%s' \"$word\"", 40, 8)
if handle <= 0 { return 1 }
phase = 1
}
unused Screen.ScreenPoll(handle)
screen := Screen.ScreenRead(handle)
if screen.cols < 40 || screen.rows < 8 { return 2 }
words: [75 * Screen.CellWords]s32
if phase == 1 {
if Screen.ScreenReadRow(handle, 0, words[:screen.cols * Screen.CellWords]) != screen.cols { return 3 }
cell := Screen.ScreenRowCell(words[:], 0)
if cell.codepoint != cast(u32)82 { return -1 }
if cell.foreground != 1 { return 4 }
if !Screen.ScreenResize(handle, 75, 17) { return 5 }
if Screen.ScreenWrite(handle, "ZX") != 2 || Screen.ScreenKey(handle, 1, 0) <= 0 { return 6 }
phase = 2
return -1
}
if screen.cols != 75 || screen.rows != 17 { return 7 }
if Screen.ScreenReadRow(handle, 1, words[:]) != 75 { return 8 }
if Screen.ScreenRowCell(words[:], 0).codepoint != cast(u32)90 ||
Screen.ScreenRowCell(words[:], 1).codepoint != cast(u32)88 { return -1 }
if !Screen.ScreenClose(handle) || Screen.ScreenRead(handle).cols != 0 { return 9 }
return 0
}
+7
View File
@@ -20,6 +20,13 @@ MeasureGlyphLineHeight :: (font: s32, typeface: string) -> s32 {
unused font; unused typeface
return 12
}
// The tests draw no picture cursors; the desktop raster decodes them in the app.
#program_export
CursorPictureHost :: (asset_path: string, width: s32, height: s32,
pixels: []u32, premultiplied: bool) -> bool {
unused asset_path; unused width; unused height; unused pixels; unused premultiplied
return false
}
#program_export
RasterText :: (value: string, x: s32, y: s32, font: s32, color: Color) {
unused x; unused y; unused font; unused color
+44
View File
@@ -393,6 +393,49 @@ CheckTabReordering :: () -> bool {
return true
}
// Menu-bar dropdowns and submenus paint above the tabs and terminal pane
// (owner, 2026-11-12: an opened submenu was hidden under the pane).
PaintIndex :: (frame: Frames.Session, value: string) -> s32 {
for index: 0..Paint.PendingPaintCount(frame) - 1 {
if Paint.PendingPaintAt(frame, index).value == value { return cast(s32)index }
}
return -1
}
LastPanePaint :: (frame: Frames.Session, node: s32) -> s32 {
last: s32 = -1
for index: 0..Paint.PendingPaintCount(frame) - 1 {
if Paint.PendingPaintAt(frame, index).node == node { last = cast(s32)index }
}
return last
}
CheckMenuAbovePane :: () -> bool {
frame := Frames.SessionOpen(); defer Frame.CloseSession(frame)
app := Application(); if app == null { return false }; defer State.Dispose(app)
app.launch.show_menubar = true
Feed(*app.sessions[0].terminal, "pane text")
bounds := Rectangle.{0.0, 0.0, 480.0, 320.0}
menus: [2]string = .["Zoom In", "Underline"]
for row: 0..1 {
label := menus[row]
app.menu.open_index = cast(s32)(2 + row); app.menu.top_index = app.menu.open_index
app.menu.focused = true; app.menu.depth = cast(s32)row
if row == 1 { app.menu.selected[0] = 13 }
result: View.ViewResult
for step: 0..3 {
result = Begin(frame, app, bounds, cast(float64)step)
if step < 3 && !Finish(frame) { return Failure("menu frame") }
}
item := PaintIndex(frame, label); pane := LastPanePaint(frame, result.node)
if item < 0 || pane < 0 || item <= pane {
ReportTree(frame); unused Finish(frame)
print("Terminal view: % paints at %, pane last paints at %\n", label, item, pane)
return Failure("menu panel paints under the terminal pane")
}
if !Finish(frame) { return Failure("menu frame end") }
}
return true
}
#program_export
main :: () -> s32 {
if !CheckCells() { return 1 }
@@ -402,6 +445,7 @@ main :: () -> s32 {
if !CheckLargeGrid() { return 5 }
if !CheckTabReordering() { return 6 }
if !CheckCursorBlink() { return 7 }
if !CheckMenuAbovePane() { return 8 }
print("Terminal view rendering and retained interaction passed\n")
return 0
}
+1
View File
@@ -1,6 +1,7 @@
// Complete physical-page projection retains every meaningful source cell,
// including history created only by narrowing or shortening the viewer.
#import "terminal"
ClipboardHost :: #import "terminal_clipboard_host";
Text :: #import "std/byte_text_linux"
libc :: #system_library "c";
CompareRaw :: (a: *void, b: *void, count: usize) -> s32 #foreign libc "memcmp";
+1 -1
View File
@@ -3,7 +3,7 @@ set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS ENV BASH_ENV
export YUE_DESKTOP_RECOVERY=0
export HARMONY_DESKTOP_RECOVERY=0
work="$root/build/ziran/viewport"
mkdir -p "$work"
exec 9>"$work/check.lock"
+1
View File
@@ -1,6 +1,7 @@
// Compare the read-only projection with the complete established resize,
// including every retained history cell, rather than checking index internals.
#import "terminal";
ClipboardHost :: #import "terminal_clipboard_host";
Capture :: #import "terminal_capture_test";
Text :: #import "std/byte_text_linux";
libc :: #system_library "c";
+313
View File
@@ -0,0 +1,313 @@
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
app=$(CDPATH= cd -- "$(dirname -- "$1")" && pwd)/$(basename -- "$1")
test -x "$app"
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS SESSION_MANAGER
mkdir -p "$root/build/ziran"
work=$(mktemp -d "$root/build/ziran/thunar-terminal-test.XXXXXX")
xvfb_pid=
private_display=
start_private_display() {
display_number=$(( $$ % 5000 + 100 ))
while test -e "/tmp/.X$display_number-lock"; do display_number=$((display_number + 1)); done
Xvfb ":$display_number" -screen 0 640x480x24 -nolisten tcp -ac &
xvfb_pid=$!
deadline=$(( $(date +%s) + 5 ))
while test "$(date +%s)" -lt "$deadline"; do
test -S "/tmp/.X11-unix/X$display_number" && break
sleep 0.1
done
test -S "/tmp/.X11-unix/X$display_number"
private_display=":$display_number"
export PRIVATE_DISPLAY="$private_display"
}
close_private_display() {
test -n "$xvfb_pid" || return 0
kill "$xvfb_pid" 2>/dev/null || true
wait "$xvfb_pid" 2>/dev/null || true
xvfb_pid=
}
launch_pids=
outside=
stop_launches() {
for pid in $launch_pids; do kill "$pid" 2>/dev/null || :; done
launch_pids=
}
trap 'stop_launches; close_private_display; rm -rf "$work" ${outside:+"$outside"}' EXIT HUP INT TERM
prefix=$work/prefix
install -d "$prefix/bin" "$prefix/share/applications" "$prefix/share/xfce4/helpers" "$work/config/xfce4" "$work/data" "$work/runtime"
install -m 644 data/terminal-helper.desktop "$prefix/share/xfce4/helpers/terminal.desktop"
{
printf '%s\n' '[Desktop Entry]' 'Type=Application' 'Name=Terminal'
printf '%s\n' 'Comment=Kryon terminal emulator' "Exec=$prefix/bin/terminal"
printf '%s\n' 'Icon=utilities-terminal' 'Terminal=false' 'Categories=System;TerminalEmulator;'
printf '%s\n' 'Keywords=terminal;shell;' 'StartupNotify=true'
} > "$prefix/share/applications/terminal.desktop"
if command -v desktop-file-validate >/dev/null 2>&1; then desktop-file-validate "$prefix/share/applications/terminal.desktop"; fi
rg -q '^Type=X-XFCE-Helper$' "$prefix/share/xfce4/helpers/terminal.desktop"
rg -q '^X-XFCE-Category=TerminalEmulator$' "$prefix/share/xfce4/helpers/terminal.desktop"
rg -q '^X-XFCE-Binaries=terminal;$' "$prefix/share/xfce4/helpers/terminal.desktop"
# Terminal starts in HOME unless told otherwise, so the helper names the folder
# Exo starts it in.
rg -q '^X-XFCE-Commands=%B --working-directory=\.;$' "$prefix/share/xfce4/helpers/terminal.desktop"
# Exo splits a launch parameter into words, so it follows -x as in xfce4-terminal.
rg -q '^X-XFCE-CommandsWithParameter=%B --working-directory=\. -x %s;$' "$prefix/share/xfce4/helpers/terminal.desktop"
record_script=$work/record-launch
cat > "$record_script" <<'RECORD'
#!/bin/sh
printf '%s\0' "$@" > "$TERMINAL_RECORD_ARGV"
pwd > "$TERMINAL_RECORD_CWD"
RECORD
chmod 755 "$record_script"
install -m 755 "$record_script" "$prefix/bin/terminal"
printf '%s\n' 'TerminalEmulator=terminal' > "$work/config/xfce4/helpers.rc"
export XDG_CONFIG_HOME="$work/config"
export XDG_DATA_HOME="$work/data"
# Keep the standard MIME database and GTK icon data when XDG_DATA_DIRS is unset.
export XDG_DATA_DIRS="$prefix/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
export XDG_RUNTIME_DIR="$work/runtime"
export PATH="$prefix/bin:$PATH"
export HOME="$work"
export HARMONY_DESKTOP_RECOVERY=0
export LP_NUM_THREADS=1 OMP_NUM_THREADS=1
launch_count=0
check_exo_directory() {
directory=$1
launch_count=$((launch_count + 1))
argv_record=$work/argv.$launch_count
cwd_record=$work/cwd.$launch_count
export TERMINAL_RECORD_ARGV="$argv_record"
export TERMINAL_RECORD_CWD="$cwd_record"
status=0
start_private_display
# A desktop session's PATH: the installed prefix first, then the system.
# Exo 4.20 hands the launch to xfce4-mime-helper and returns before the
# helper starts Terminal; with only the prefix on PATH it cannot find that
# helper and starts the binary without the helper's arguments.
full_path=$PATH
PATH="$prefix/bin:$full_path"
export PATH
DISPLAY="$private_display" /usr/bin/timeout --kill-after=2s 10s /usr/bin/exo-open --working-directory "$directory" --launch TerminalEmulator || status=$?
PATH="$full_path"
export PATH
deadline=$(( $(date +%s) + 8 ))
while test "$(date +%s)" -lt "$deadline" && ! test -s "$cwd_record"; do sleep 0.1; done
close_private_display
test "$status" -eq 0
test -f "$argv_record"
test -f "$cwd_record"
test "$(cat "$cwd_record")" = "$(cd "$directory" && pwd)"
tr '\0' '\n' < "$argv_record" | rg -qx -- '--working-directory=\.'
}
install -d "$work/ordinary-directory" "$work/Thunar Selected Dir"
check_exo_directory "$work/ordinary-directory"
check_exo_directory "$work/Thunar Selected Dir"
actual_directory="$work/Canonical Terminal Selected Dir"
actual_record=$work/canonical-cwd
install -d "$actual_directory"
actual_script=$work/check-canonical-cwd
cat > "$actual_script" <<CHECK
#!/bin/sh
set -eu
terminal="$app"
directory="$actual_directory"
record="$actual_record"
"\$terminal" --working-directory "\$directory" --disable-server --hold --command "pwd > '\$record'; sleep 0.2" &
pid=\$!
deadline=\$(( \$(date +%s) + 8 ))
while test \$(date +%s) -lt \$deadline; do
test -f "\$record" && break
sleep 0.2
done
test -f "\$record"
test "\$(cat "\$record")" = "\$directory"
kill "\$pid" 2>/dev/null || :
wait "\$pid" 2>/dev/null || :
CHECK
chmod 755 "$actual_script"
status=0
start_private_display
DISPLAY="$private_display" timeout --kill-after=2s 12s "$actual_script" || status=$?
close_private_display
test "$status" -eq 0
# The real Terminal through Exo, as Thunar's default Open Terminal Here action
# launches it: the shell must start in the selected folder, not in HOME.
install -m 755 "$app" "$prefix/bin/terminal"
exo_directory="$work/Exo Real Selected Dir"
exo_record=$work/exo-real-cwd
install -d "$exo_directory"
status=0
start_private_display
DISPLAY="$private_display" /usr/bin/timeout --kill-after=2s 10s /usr/bin/exo-open \
--working-directory "$exo_directory" --launch TerminalEmulator "sh -c 'pwd > $exo_record'" || status=$?
deadline=$(( $(date +%s) + 8 ))
while test "$(date +%s)" -lt "$deadline" && ! test -s "$exo_record"; do sleep 0.2; done
close_private_display
test "$status" -eq 0
test -s "$exo_record"
test "$(cat "$exo_record")" = "$exo_directory"
# Thunar's right-click Open Terminal Here is a custom action, and Thunar puts
# %f in already shell-quoted. Real Thunar runs on the private display with a
# private bus that activates no services; accelerators trigger its actions.
# The Terminal wrapper records Thunar's argv, and the shell records where it
# started and which Terminal started it, then stays running like a shell.
real_app=$(readlink -f "$app")
record_dir=$work/launch-record
install -d "$record_dir" "$work/config/Thunar"
cat > "$prefix/bin/terminal" <<WRAP
#!/bin/sh
printf '%s\0' "\$@" > "$record_dir/argv"
exec "$real_app" "\$@"
WRAP
chmod 755 "$prefix/bin/terminal"
record_shell=$work/record-shell
cat > "$record_shell" <<SHELL
#!/bin/sh
{ pwd -P; echo "\$PPID"; echo "\$\$"; } > "$record_dir/shell.tmp"
mv "$record_dir/shell.tmp" "$record_dir/shell"
exec sleep 60
SHELL
chmod 755 "$record_shell"
# The reported failure: the window opened, its shell never started, and the
# window closed within a second. The shell must start in the expected folder
# and its Terminal must still be open afterwards.
expect_open_terminal() {
running_before=$launch_pids
expected=$(cd "$1" && pwd -P)
deadline=$(( $(date +%s) + 10 ))
while test "$(date +%s)" -lt "$deadline" && ! test -s "$record_dir/shell"; do sleep 0.1; done
if ! test -s "$record_dir/shell"; then
echo "Terminal closed before its shell started; expected $expected" >&2
return 1
fi
shell_cwd=$(sed -n 1p "$record_dir/shell")
terminal_pid=$(sed -n 2p "$record_dir/shell")
shell_pid=$(sed -n 3p "$record_dir/shell")
launch_pids="$launch_pids $shell_pid $terminal_pid"
test "$shell_cwd" = "$expected" || { echo "shell started in $shell_cwd, expected $expected" >&2; return 1; }
test "$(readlink -f "/proc/$terminal_pid/exe")" = "$real_app"
sleep 1.5
kill -0 "$terminal_pid" 2>/dev/null || { echo "Terminal closed after starting in $expected" >&2; return 1; }
# Ending its shell ends the Terminal.
kill "$shell_pid" 2>/dev/null || :
deadline=$(( $(date +%s) + 5 ))
while test "$(date +%s)" -lt "$deadline" && kill -0 "$terminal_pid" 2>/dev/null; do sleep 0.1; done
kill "$terminal_pid" 2>/dev/null || :
launch_pids=$running_before
rm -f "$record_dir/shell"
}
recorded_argv() { tr '\0' '\n' < "$record_dir/argv"; }
# The selected folder is outside HOME and its name has spaces.
outside=$(mktemp -d "$root/build/ziran/Thunar Outside Home.XXXXXX")
thunar_directory="$outside/Selected Project Dir"
install -d "$thunar_directory"
cat > "$work/config/Thunar/uca.xml" <<UCA
<?xml version="1.0" encoding="UTF-8"?>
<actions>
<action><icon>utilities-terminal</icon><name>Open Terminal Here</name><unique-id>terminal-direct</unique-id>
<command>$prefix/bin/terminal --working-directory=%f</command><description>Terminal</description>
<range></range><patterns>*</patterns><startup-notify/><directories/></action>
<action><icon>utilities-terminal</icon><name>Open Terminal Here (Exo)</name><unique-id>terminal-exo</unique-id>
<command>exo-open --working-directory %f --launch TerminalEmulator</command><description>Terminal</description>
<range></range><patterns>*</patterns><startup-notify/><directories/></action>
<action><icon>utilities-terminal</icon><name>Open Terminal Here (quoted)</name><unique-id>terminal-quoted</unique-id>
<command>$prefix/bin/terminal --working-directory=&quot;%f&quot;</command><description>Terminal</description>
<range></range><patterns>*</patterns><startup-notify/><directories/></action>
</actions>
UCA
cat > "$work/config/Thunar/accels.scm" <<'ACCELS'
(gtk_accel_path "<Actions>/ThunarActions/uca-action-terminal-direct" "<Primary><Alt>t")
(gtk_accel_path "<Actions>/ThunarActions/uca-action-terminal-exo" "<Primary><Alt>e")
(gtk_accel_path "<Actions>/ThunarActions/uca-action-terminal-quoted" "<Primary><Alt>q")
ACCELS
cat > "$work/bus.conf" <<'BUS'
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>session</type>
<listen>unix:tmpdir=/tmp</listen>
<auth>EXTERNAL</auth>
<policy context="default">
<allow send_destination="*" eavesdrop="true"/>
<allow eavesdrop="true"/>
<allow own="*"/>
</policy>
</busconfig>
BUS
start_private_display
DISPLAY="$private_display" SHELL="$record_shell" NO_AT_BRIDGE=1 GIO_USE_VFS=local GIO_USE_VOLUME_MONITOR=unix \
dbus-run-session --config-file="$work/bus.conf" -- thunar "$thunar_directory" > "$work/thunar.log" 2>&1 &
thunar_session=$!
launch_pids="$thunar_session"
thunar_window=$(DISPLAY="$private_display" timeout 15s xdotool search --sync --onlyvisible --class Thunar | head -n 1)
if [ -z "$thunar_window" ]; then
printf '%s\n' 'Thunar did not open a window on the private display.' >&2
tail -n 20 "$work/thunar.log" >&2
exit 1
fi
thunar_pid=$(DISPLAY="$private_display" xdotool getwindowpid "$thunar_window")
launch_pids="$thunar_pid $thunar_session"
thunar_action() {
DISPLAY="$private_display" xdotool windowfocus --sync "$thunar_window"
sleep 0.5
DISPLAY="$private_display" xdotool key "$1"
}
# Open Terminal Here as installed on the desktop: Thunar quotes %f itself.
thunar_action ctrl+alt+t
expect_open_terminal "$thunar_directory"
test "$(recorded_argv)" = "--working-directory=$thunar_directory"
# Thunar's default action goes through Exo and the TerminalEmulator helper.
thunar_action ctrl+alt+e
expect_open_terminal "$thunar_directory"
test "$(recorded_argv)" = "--working-directory=."
# Quoting %f again hands Terminal the quotes as part of the path. Terminal
# says so and starts in HOME instead of closing.
thunar_action ctrl+alt+q
expect_open_terminal "$HOME"
test "$(recorded_argv)" = "--working-directory='$thunar_directory'"
rg -qF "Terminal: working directory \"'$thunar_directory'\" does not exist; starting in $HOME" "$work/thunar.log"
stop_launches
wait "$thunar_session" 2>/dev/null || :
close_private_display
# An existing folder outside HOME, with spaces, opens as it is, without notice.
start_private_display
DISPLAY="$private_display" SHELL="$record_shell" "$app" "--working-directory=$thunar_directory" 2> "$work/direct.err" &
direct_pid=$!
launch_pids=$direct_pid
expect_open_terminal "$thunar_directory"
wait "$direct_pid" 2>/dev/null || :
launch_pids=
close_private_display
if rg -q 'Terminal: working directory' "$work/direct.err"; then
echo "An existing folder fell back: $(cat "$work/direct.err")" >&2
exit 1
fi
# A folder that is missing, a file, or a folder Terminal may not enter starts
# the shell in HOME and leaves the window open.
missing_directory="$work/Missing Selected Dir"
selected_file="$work/Selected File.txt"
: > "$selected_file"
check_fallback() {
start_private_display
DISPLAY="$private_display" SHELL="$record_shell" "$app" "--working-directory=$1" 2> "$work/fallback.err" &
direct_pid=$!
launch_pids=$direct_pid
expect_open_terminal "$HOME"
wait "$direct_pid" 2>/dev/null || :
launch_pids=
close_private_display
}
check_fallback "$missing_directory"
rg -qF "Terminal: working directory \"$missing_directory\" does not exist; starting in $HOME" "$work/fallback.err"
check_fallback "$selected_file"
rg -qF "Terminal: working directory \"$selected_file\" is not a folder; starting in $HOME" "$work/fallback.err"
if test "$(id -u)" -ne 0; then
locked_directory="$work/Locked Selected Dir"
install -d -m 000 "$locked_directory"
check_fallback "$locked_directory"
fi
echo 'Thunar Exo working-directory, real Terminal through Exo and canonical Terminal working-directory passed'
echo 'Thunar Open Terminal Here (custom action, Exo helper, quoted path) and working-directory fallback passed'
+1 -1
View File
@@ -3,7 +3,7 @@ set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS ENV BASH_ENV
export YUE_DESKTOP_RECOVERY=0
export HARMONY_DESKTOP_RECOVERY=0
ziran=${ZIRAN:-"$root/scripts/ziran.sh"}
lock_flags=
if test ! -f ziran.local.toml; then lock_flags=--locked; fi
+84
View File
@@ -0,0 +1,84 @@
"""Exercise two independent shells through the linked Terminal ZX window."""
import os
import subprocess
import sys
import tempfile
import time
from pathlib import Path
def xdotool(*args):
return subprocess.run(["xdotool", *args], check=True, text=True, capture_output=True, timeout=10).stdout
def wait_for(player, operation, message):
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
if player.poll() is not None:
raise AssertionError(f"Terminal ZX player exited with status {player.returncode}")
result = operation()
if result:
return result
time.sleep(0.1)
raise AssertionError(message)
def visible_window(player):
try:
return xdotool("search", "--onlyvisible", "--pid", str(player.pid)).splitlines()[0]
except (subprocess.CalledProcessError, IndexError):
return None
def shell_command(text):
xdotool("type", "--clearmodifiers", "--delay", "32", text)
xdotool("key", "Return")
def check_output(player, path, expected):
wait_for(player, lambda: path.exists() and path.read_text() == expected,
f"Expected {path.name} to contain {expected!r}")
assert os.environ.get("TERMINAL_PRIVATE_XVFB") == "1", "Use make zx-window-test"
binary = Path(sys.argv[1]).resolve(strict=True)
with tempfile.TemporaryDirectory(prefix="terminal-zx-window.", dir=binary.parent) as scratch:
output = Path(scratch)
environment = dict(os.environ, TERMINAL_ZX_TEST_DIR=scratch)
player = subprocess.Popen([binary], env=environment)
try:
window = wait_for(player, lambda: visible_window(player), "Terminal ZX window did not open")
xdotool("windowfocus", "--sync", window)
shell_command('tab=first; echo "$tab" >"$TERMINAL_ZX_TEST_DIR/first"')
check_output(player, output / "first", "first\n")
xdotool("key", "ctrl+shift+t")
time.sleep(0.3)
xdotool("windowsize", window, "760", "475")
shell_command('echo "${tab-second}" >"$TERMINAL_ZX_TEST_DIR/second"')
check_output(player, output / "second", "second\n")
xdotool("key", "ctrl+Tab")
time.sleep(0.3)
shell_command('echo "$tab" >"$TERMINAL_ZX_TEST_DIR/return"')
check_output(player, output / "return", "first\n")
xdotool("key", "ctrl+shift+w")
time.sleep(0.3)
shell_command('echo "${tab-remaining}" >"$TERMINAL_ZX_TEST_DIR/remaining"')
check_output(player, output / "remaining", "remaining\n")
xdotool("type", "--delay", "32", "false")
xdotool("key", "ctrl+c")
time.sleep(0.3)
shell_command('echo ready >"$TERMINAL_ZX_TEST_DIR/ready"')
check_output(player, output / "ready", "ready\n")
shell_command("exit")
finally:
player.terminate()
try:
player.wait(timeout=5)
except subprocess.TimeoutExpired:
player.kill()
player.wait()
print("Terminal ZX accepted PTY input, resize, tab switching, and Ctrl+C in a private window")
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")"
version=$(sed -n 's/^## \[\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)\] - [0-9-]*$/\1/p' CHANGELOG.md | head -n 1)
if [ -z "$version" ]; then
printf '%s\n' 'Terminal: add a dated numeric release to CHANGELOG.md first.' >&2
exit 1
fi
printf '%s\n' "$version" > VERSION
+56 -65
View File
@@ -10,6 +10,14 @@
"source": true,
"url": "https://github.com/libsndfile/libsamplerate.git"
},
{
"commit": "3017f0d1cc56975aa29c600a1f55a62e1193cf7b",
"dependencies": {},
"id": "p115fee450ee07367",
"name": "image-codec",
"ref": "3017f0d1cc56975aa29c600a1f55a62e1193cf7b",
"url": "https://git.waozi.xyz/ziranlang/image-codec.git"
},
{
"commit": "829a65d769d935c4852f8159e964312c0957260a",
"dependencies": {},
@@ -19,6 +27,15 @@
"source": true,
"url": "https://github.com/libsdl-org/SDL.git"
},
{
"commit": "39f7540d193ccaa2096e1115df608da8116b32b7",
"dependencies": {"audio": "pf832f0842a94daad", "avif": "p6abd95e3b55e2350", "image_codec": "p115fee450ee07367", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db", "libwebp": "p3b3c785a0e17e605", "sdl3": "p16cd0434af3dff7b", "webp": "p4cdce4edaaf93e67"},
"dependency_refs": {"audio": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2", "avif": "786871ec1d54fde303611a428ef31735bbdcc71d", "image_codec": "3017f0d1cc56975aa29c600a1f55a62e1193cf7b", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "6581dfa03711a96d219becd964860543b24b1f4f"},
"id": "p2e0dd54cbe9b9fb2",
"name": "kryon",
"ref": "39f7540d193ccaa2096e1115df608da8116b32b7",
"url": "https://git.waozi.xyz/kryonlabs/kryon.git"
},
{
"commit": "1844042d1ca751e62e61df7617dba19c98588339",
"dependencies": {},
@@ -28,6 +45,15 @@
"source": true,
"url": "https://github.com/webmproject/libwebp.git"
},
{
"commit": "6581dfa03711a96d219becd964860543b24b1f4f",
"dependencies": {"image_codec": "p115fee450ee07367", "libwebp": "p3b3c785a0e17e605"},
"dependency_refs": {"image_codec": "3017f0d1cc56975aa29c600a1f55a62e1193cf7b", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339"},
"id": "p4cdce4edaaf93e67",
"name": "webp",
"ref": "6581dfa03711a96d219becd964860543b24b1f4f",
"url": "https://git.waozi.xyz/ziranlang/webp.git"
},
{
"commit": "1aadfad932c98c069a1204261b1856f81f3bc199",
"dependencies": {},
@@ -38,21 +64,13 @@
"url": "https://github.com/AOMediaCodec/libavif.git"
},
{
"commit": "bd278217e2bac754d868b3d6502eac4257658d4b",
"dependencies": {"dav1d": "pb24767b9eb34d961", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa"},
"dependency_refs": {"dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937"},
"id": "p5d7d12505a42f7b3",
"name": "av1",
"ref": "bd278217e2bac754d868b3d6502eac4257658d4b",
"url": "https://github.com/ziranlang/av1.git"
},
{
"commit": "360553150917f352e49e1beb78917370792ccaef",
"dependencies": {},
"id": "p69c0e968ae5735d9",
"name": "image-codec",
"ref": "360553150917f352e49e1beb78917370792ccaef",
"url": "https://github.com/ziranlang/image-codec.git"
"commit": "786871ec1d54fde303611a428ef31735bbdcc71d",
"dependencies": {"av1": "pe81dfca5d80a5526", "dav1d": "pb24767b9eb34d961", "image_codec": "p115fee450ee07367", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db"},
"dependency_refs": {"av1": "bed54d12dc5a8cf8e6a514b2a49d3592d6cecb65", "dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "3017f0d1cc56975aa29c600a1f55a62e1193cf7b", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199"},
"id": "p6abd95e3b55e2350",
"name": "avif",
"ref": "786871ec1d54fde303611a428ef31735bbdcc71d",
"url": "https://git.waozi.xyz/ziranlang/avif.git"
},
{
"commit": "b141d9c45db236335351c8a4b2a14b3ade27c937",
@@ -63,33 +81,6 @@
"source": true,
"url": "https://aomedia.googlesource.com/aom"
},
{
"commit": "f84c162594e518cb306bfd0ce41783ad55b6c730",
"dependencies": {"av1": "p5d7d12505a42f7b3", "dav1d": "pb24767b9eb34d961", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db"},
"dependency_refs": {"av1": "bd278217e2bac754d868b3d6502eac4257658d4b", "dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199"},
"id": "p872d871f84f2284f",
"name": "avif",
"ref": "f84c162594e518cb306bfd0ce41783ad55b6c730",
"url": "https://github.com/ziranlang/avif.git"
},
{
"commit": "a7211b650821a914c8571e39c2e458ace1a0c7a7",
"dependencies": {"audio": "pd258d453b63edc1f", "avif": "p872d871f84f2284f", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db", "libwebp": "p3b3c785a0e17e605", "raylib": "pcc7aa76725f2fb2f", "sdl3": "p16cd0434af3dff7b", "webp": "pa068bd09450b2a80"},
"dependency_refs": {"audio": "f5eed1e6c817997d51508f9c3c7b948a0bb4ad0b", "avif": "f84c162594e518cb306bfd0ce41783ad55b6c730", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "raylib": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "02145a00a1f0df2a111da04a75f3fef260883897"},
"id": "p95ee34f8b47b4393",
"name": "kryon",
"ref": "master",
"url": "https://github.com/kryonlabs/kryon.git"
},
{
"commit": "02145a00a1f0df2a111da04a75f3fef260883897",
"dependencies": {"image_codec": "p69c0e968ae5735d9", "libwebp": "p3b3c785a0e17e605"},
"dependency_refs": {"image_codec": "360553150917f352e49e1beb78917370792ccaef", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339"},
"id": "pa068bd09450b2a80",
"name": "webp",
"ref": "02145a00a1f0df2a111da04a75f3fef260883897",
"url": "https://github.com/ziranlang/webp.git"
},
{
"commit": "54706fc6bc0cdecab7e9593974a4039cc038fca7",
"dependencies": {},
@@ -99,24 +90,6 @@
"source": true,
"url": "https://github.com/videolan/dav1d.git"
},
{
"commit": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
"dependencies": {},
"id": "pcc7aa76725f2fb2f",
"name": "raylib",
"ref": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
"source": true,
"url": "https://github.com/raysan5/raylib.git"
},
{
"commit": "f5eed1e6c817997d51508f9c3c7b948a0bb4ad0b",
"dependencies": {"libopus": "pe1fe9bbe80bf1d6d", "libsamplerate": "p0dd67588478f9a3e"},
"dependency_refs": {"libopus": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6", "libsamplerate": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7"},
"id": "pd258d453b63edc1f",
"name": "audio",
"ref": "f5eed1e6c817997d51508f9c3c7b948a0bb4ad0b",
"url": "https://github.com/ziranlang/audio.git"
},
{
"commit": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6",
"dependencies": {},
@@ -125,16 +98,34 @@
"ref": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6",
"source": true,
"url": "https://github.com/xiph/opus.git"
},
{
"commit": "bed54d12dc5a8cf8e6a514b2a49d3592d6cecb65",
"dependencies": {"dav1d": "pb24767b9eb34d961", "image_codec": "p115fee450ee07367", "libaom": "p74ab3cb6eb3b86fa"},
"dependency_refs": {"dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "3017f0d1cc56975aa29c600a1f55a62e1193cf7b", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937"},
"id": "pe81dfca5d80a5526",
"name": "av1",
"ref": "bed54d12dc5a8cf8e6a514b2a49d3592d6cecb65",
"url": "https://git.waozi.xyz/ziranlang/av1.git"
},
{
"commit": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2",
"dependencies": {"libopus": "pe1fe9bbe80bf1d6d", "libsamplerate": "p0dd67588478f9a3e"},
"dependency_refs": {"libopus": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6", "libsamplerate": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7"},
"id": "pf832f0842a94daad",
"name": "audio",
"ref": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2",
"url": "https://git.waozi.xyz/ziranlang/audio.git"
}
],
"root": {
"dependencies": {"kryon": "p95ee34f8b47b4393"},
"dependency_refs": {"kryon": "master"},
"dependencies": {"kryon": "p2e0dd54cbe9b9fb2"},
"dependency_refs": {"kryon": "39f7540d193ccaa2096e1115df608da8116b32b7"},
"name": "terminal"
},
"toolchain": {
"commit": "126266c4a6b5a7579a59de412f2ef9fcddedfd1c",
"ref": "master",
"url": "https://github.com/ziranlang/ziran.git"
"commit": "1b7608b82eb204a2882457d503bbf31062d4eefb",
"ref": "1b7608b82eb204a2882457d503bbf31062d4eefb",
"url": "https://git.waozi.xyz/ziranlang/ziran.git"
}
}
+4 -4
View File
@@ -4,12 +4,12 @@ entry = "src/app/app_main.zi"
module_roots = ["src", "src/app", "src/terminal_pane", "tests", "benchmarks"]
[toolchain]
git = "https://github.com/ziranlang/ziran.git"
ref = "master"
git = "https://git.waozi.xyz/ziranlang/ziran.git"
ref = "1b7608b82eb204a2882457d503bbf31062d4eefb"
[dependencies.kryon]
git = "https://github.com/kryonlabs/kryon.git"
ref = "master"
git = "https://git.waozi.xyz/kryonlabs/kryon.git"
ref = "39f7540d193ccaa2096e1115df608da8116b32b7"
[exports]
app_host = "src/app/app_host.zi"