asekii-term
asekii-term
The terminal and render layers of the Asekii framework for Crystal:
Asekii::Terminal— a kitty-protocol terminal session: raw mode, feature detection, input parsing, key and mouse gestures, clipboard, graphics, notifications, drag and drop, colors, pointer shapes, title and progress, multiplexer passthrough.Asekii::Render— a layered, damage-tracked render engine: planes, themed paints with roles, blend spaces, box strokes drawn as kitty images, sprites and inline pictures, diffed SGR output.- Common primitives —
Asekii::Raster(PNG decode/encode, scaling, sixel, iTerm),Asekii::KittyGraphics,Asekii::ColorSyntax,Asekii::UnicodePlaceholder,Asekii::Clock,Asekii::Rect(x,y,width,height;Rect.edges(left, top, right, bottom),left/top/right/bottom,includes?,&intersection),Asekii::Zlib(pack(data) : Bytes, orpack(data) { |packed| }to borrow the pooled buffer without copying).
Grapheme segmentation and cell width come from termwidth.
Installation
dependencies:
asekii-term:
github: shpeckman/asekii-term
Requires Crystal >= 1.21.0.
require "asekii-term"
require "asekii-term/terminal"
require "asekii-term/render"
The first line loads both layers. The other two load one layer each, and the render layer does not depend on the terminal layer.
Quick start
require "asekii-term"
config = Asekii::Terminal::Config.new
config.shortcut("quit", 'q', Asekii::Event::Mods::Ctrl)
Asekii::Terminal.open(config) do |term|
ui = Asekii::Render::Compositor.new
ui.sync = true
frame = Bytewire.new
term.refresh
while event = term.events.receive?
case event
when Asekii::Event::Resize
next unless event.cols > 0 && event.rows > 0
ui.resize(event.cols, event.rows)
ui.cell_pixels(event.width // event.cols, event.height // event.rows)
when Asekii::Event::Binding
break if event.name == "quit"
end
ui.root.erase
ui.root.put(1, 1, "hello, world", fg: :accent, attrs: Asekii::Render::Attr::Bold)
frame.reset
ui.render(frame)
term.write(frame.written)
end
end
Terminal.open closes the session and restores the terminal when the block exits. refresh emits an initial Resize when the terminal lacks in-band resize reports.
Terminal
Session
| Member | Purpose |
|---|---|
Terminal.open(config, input, output) { |term| } |
Open, yield, always close. |
Terminal.new(config, input, output) |
Open without a block; call close yourself. |
close, closed? |
Restore the terminal and stop the fibers. |
suspend, resume, refresh |
Leave/re-enter raw mode and the alternate screen; re-measure the window. |
Terminal.restore, .suspend, .resume, .refresh |
The same, applied to every open session. |
features : Feature |
Detected modes: Keyboard, Resize, Motion, Pixels, Focus, Visibility, ColorScheme, Paste. |
supports?(mode) |
DECRQM probe for any private mode. |
events : Channel(Event::Input) |
All input and derived events. |
print, <<, write(bytes), submit(wire) { |error| } |
Output. submit reports completion of a Bytewire frame. |
When signals is on, the session installs handlers for INT, TERM, HUP and QUIT (restore, then exit), TSTP/CONT (suspend/resume) and WINCH (refresh). Ctrl+Z suspends the process when job_control is on.
Config
Asekii::Terminal::Config is a struct of properties:
| Group | Properties |
|---|---|
| Session | alternate_screen, job_control, detect, signals, enter, leave, app_name, clock |
| Events | derived (Derived flags: TextInput, KeyCommand, KeyGesture, Binding, MouseGesture, Lock, TypingMetric; default All) |
| Protocols | clipboard (Auto/Kitty/Osc52), notifications (Auto/Kitty/Osc9/Osc777), multiplexer (Auto/None/Tmux/Screen) |
| Ids | clipboard_id, dnd_id |
| Buffers | event_buffer, event_backlog |
| Timeouts | query_timeout, clipboard_timeout, transfer_timeout, busy_retries, busy_delay |
| Keys | hold_after, hold_repeats, multi_tap_window, sequence_timeout |
| Mouse | click_radius, click_window, multi_click_window, long_press_after, hover_radius, hover_dwell_after, scroll_window, scroll_pause, swipe_velocity |
Bindings are added with chainable methods. A key is a Char, an Event::Named or a raw code:
config
.shortcut("save", 's', Asekii::Event::Mods::Ctrl)
.chord("both", 'j', 'k')
.sequence("goto-top", 'g', 'g')
Event::Shortcut.parse("ctrl+shift+p") parses a shortcut spec.
Events
Raw events (Event::Raw):
| Event | Fields |
|---|---|
Key |
code, action (Press/Repeat/Release), mods, shifted, base, text; helpers named, char, modifier?, command?, stroke |
Mouse |
action (Press/Release/Drag/Hover/Scroll/Leave), button, mods, x, y (pixels), col, row |
Resize |
rows, cols, height, width |
Focus, Visibility, ColorScheme |
gained, visible, dark |
Paste |
mimes, primary, password, text |
Notification |
kind (Activated/Button/Closed), id, button, untracked |
Drop, Drag |
drag-and-drop progress |
Ack |
kitty graphics reply: image, number, placement, message, ok? |
Resume |
the session came back from suspension |
Derived events (in Event::Input). Config#derived selects which kinds are emitted. Raw events are always emitted, and the work behind disabled kinds is skipped; for example, derived = Derived::TextInput | Derived::Binding turns off all mouse gesture tracking.
| Event | Meaning |
|---|---|
TextInput |
Text produced by a key. |
KeyCommand |
A key with a command modifier or without text. |
KeyGesture |
Activate, AutoRepeat, Tap, MultiTap, HoldStart, HoldEnd, HoldReached, ModifierTap. |
Binding |
A configured Chord, Sequence or Shortcut fired; name. |
MouseGesture |
Click, DragStart, DragMove, DragEnd, Enter, HoverDwell, HoverEnd, Motion, Scroll, Swipe, Chord, LongPress; count, dx, dy, velocity, direction. |
Lock |
Caps Lock or Num Lock changed. |
TypingMetric |
Dwell, latency and overlap of a released key. |
Queries
Queries block for up to limit, which defaults to query_timeout, and return nil when no reply arrives in time.
attributes,identity(name, version and device),window_size,cell_sizequery_color_scheme,query_visibility(the answer arrives as an event)image_protocolreturnsKitty,Sixel,ItermorNone;supports_graphics?,supports_indexed?,supports_sixel?,probe_media,mediumnotify_protocol,notification_support,notifications_alivednd_support,supports_dnd?colors(*keys),confirm_color,legacy_colors?pointer(which : PointerQuery),pointer_support(*shapes : PointerShape)clipboard_protocol,clipboard_mimes
Clipboard
term.copy("text")
term.clipboard_write({"text/html" => html, "text/plain" => text}, aliases: {"text/plain" => ["UTF8_STRING"]})
term.clipboard_read("text/plain").try(&.text)
term.clipboard_read(paste_event, "image/png", into: file)
copy(text, primary:, limit:), clipboard_write(items, aliases:, primary:, limit:) and clipboard_mimes(primary:, limit:) take their options by name. Kitty clipboard (OSC 5522) is used when the terminal supports it; otherwise OSC 52 (text only). Writes retry on EBUSY.
Graphics
alias Kitty = Asekii::Terminal::Kitty
pixels = Asekii::Terminal::Pixels.png(File.read("logo.png").to_slice)
term.send(Kitty::Image.new(pixels, id: 1, placement: Asekii::Terminal::Placement.new(columns: 10, rows: 5)))
term.send(Kitty::Place.new(id: 1, placement: Asekii::Terminal::Placement.new(x: 4, y: 2)))
term.send(Kitty::Delete.new(:id, id: 1, free: true))
wire = Bytewire.new
term.encode(wire, Kitty::Frame.new(pixels, id: 1, edit: 1, quiet: :all))
Kitty::Animate.new(id: 1, state: :loop).encode(wire)
- Commands (
Kitty::Command):Image,Frame,Place,Delete(targetScope),Animate,Compose. Each is a record with named-only fields, defaulting toquiet: :none.term.send(command, limit)transmits under the graphics lock. ForImage,Frame,PlaceandComposeit returns theEvent::Ackwhen anidornumberis set andquietisNone.DeleteandAnimatenever wait.term.encode(wire, command)andterm.encode(command) : Stringencode with the terminal's probed medium.command.encode(wire)andcommand.encodeencode with direct transmission.
Pixels:png(data),rgba(data, width:, height:),rgb(data, width:, height:),at(path, medium:, format:, …),temp,shared. Large direct payloads move to shared memory or temp files onceprobe_mediahas found a working medium.Placement: named-only placement keys (id,x,y,width,height,offset_x,offset_y,columns,rows,z,hold_cursor,placeholder,parent,parent_placement,shift_x,shift_y).- Unicode placeholders:
Terminal.placeholder(id, columns:, rows:, placement:, compact:). - Other protocols:
sixel(pixels, columns:, rows:),sixel_code,inline_image,inline_image_code(iTerm).
Notifications
id = term.notify("Build finished", "All specs green", buttons: ["Open"], urgency: Asekii::Terminal::Urgency::Low)
term.close_notification(id)
notify also takes a full Notice record. It falls back to OSC 9 or OSC 777 on terminals without kitty notifications.
Drag and drop
- Drops:
accept_drops(*mimes),drop_reply,drop_data(index, entry:, into:, limit:),drop_entry(handle:, index:, into:, limit:),drop_save(destination, index:, entry:),drop_close,drop_finish,stop_drops. - Drags:
offer_drags,drag_offer,drag_presend,drag_image(data, number:, format:, width:, height:, opacity:),drag_text(text, number:, numerator:, denominator:, opacity:),drag_entry(data, index:, flag:, parent:, child:),drag_show,drag_start,drag_data,drag_files,drag_path,drag_fail,drag_abort,drag_cancel,stop_drags.
Colors, pointer, indicators
- Colors:
color(key, value),dynamic_color,reset_color,push_colors,pop_colors;colors(*keys)returns aColorReport(colors,unknown). Keys are palette indices or names such as"foreground".Terminal::Color.parseacceptsrgb:,#hex,rgbi:and X11 names, each with an optional@alpha. - Pointer:
pointer=(PointerShape),push_pointer,pop_pointer,reset_pointer. - Indicators:
title=,reset_title,progress(value, state),clear_progress,bell. The title and progress are restored on suspend and close. multiplexerreports the passthrough in use. Inside tmux or screen, kitty-specific sequences are wrapped automatically.
Render
Compositor and planes
ui = Asekii::Render::Compositor.new
ui.resize(cols, rows)
panel = ui.plane(30, 10, x: 2, y: 1)
panel.fill(bg: :surface_raised)
panel.put(1, 0, "Title", fg: :text, attrs: Asekii::Render::Attr::Bold)
panel.put(1, 2, "docs", fg: :accent, link: "https://example.com")
panel.stroke(0, 0, Asekii::Render::Stroke.new(Asekii::Render::Stroke::Piece::TopLeft, round: true))
wire = Bytewire.new
ui.render(wire)
- Compositor:
render(wire | io),render : String,resize,invalidate,root,plane,at,transmit,paint(painter),drop_paint,enter/leave. - Compositor settings:
sync,inline,blend,images,cell_pixels,exact_borders,indexed_tiles,cursor_shape,cursor_blink,hide_cursor. - Parallel work:
workersandbandscompose large damaged regions in parallel bands.offloadmoves stroke-image encoding off the render fiber. - Plane drawing:
put,fill,stroke,image(unicode placeholders),erase,scroll,base,fg=,bg=. - Plane layout:
move,resize,on_resize,reparent,opacity=,visible=,clip=,bounds=(Rect?)in screen cells;window : Rectis the visible area after parent clipping and bounds. - Plane stacking:
to_top,to_bottom,raise_one,lower_one,above,below. - Plane extras:
cursor,hide_cursor,sprite,inline_picture,dispose. - Sprite (a kitty image placement or inline picture tied to a plane):
move,resize,clip=(Rect?),hidden=,picture=,dispose;live : Sprite::Spot?is its current on-screen spot. - Only damaged rows are composed, and only cells that changed are written.
Paints and roles
Paint arguments are typed PaintLike (Shade | Tuple(Shade, Float64)), where a Shade is one of:
Paintvalues- palette indices (
Int32) "#rrggbb","rgb:...":default,:foreground,:background,:none- role names such as
:surface,:text,:accent Blend,Adjust,ContrastandLayeredspecs
The tuple form is {shade, alpha}.
A spec passed to a plane (fg:, bg:, line:, fg=, bg=) is interned into that compositor's pile, as is every link: URI. Before a frame, when a pile's pools have doubled past 1024 entries, the compositor drops the entries no cell references any more and redraws. Animating a Blend amount every frame is therefore safe. Specs nested inside other specs or theme roles use the process-wide Specs table, whose size is bounded by your code. Pile-local paints (Paint::Kind::Local) are only meaningful inside their own pile.
Core roles: surface, text, surface_raised, text_muted, border, accent, selection, error, warning, success, surface_sunken, surface_overlay, hover, focus, on_accent, info, shadow. Any other symbol creates a custom role.
Attributes (Attr flags): Bold, Dim, Italic, Underline and its double, curly, dotted and dashed variants, Blink, Reverse, Conceal, Strike, Overline, HighContrast.
Themes
themes = ui.themes
themes.define(:night, base16: colors16, fg: 0xd0d0d0, bg: 0x101010) do |theme|
theme.role(:accent, 0x7aa2f7)
theme.role(:border, theme.mix(:text, :surface, 0.7))
theme.role(:hover, theme.lighten(:surface, 0.05))
end
themes.define(:day, base16: light16)
themes.pair(:night, :day)
themes.transition(:day, 400.milliseconds, Asekii::Render::Easing::Out)
- Palette sources: the terminal's own palette, a 256-color palette generated from base16, or an explicit 256-color palette.
- Settings:
depth(Ansi16,Indexed256,TrueColor; detected fromCOLORTERM/TERM),space(Linear,Lab,Oklab),contrast_model(Wcag,Apca),delivery(Auto,Push,Local),mode(Auto,Dark,Light),snap,extend_palette. - Host:
themes.host = Asekii::TerminalHost.new(term, ui)connects the themes to a terminal and compositor. Palette pushes go into the compositor's outbox, palette surveys and transition ticks run on fibers, and their results are applied at the start of the nextrender. They callui.pile.touch, so setui.pile.notifyto wake your render loop. Without a host,Themesstays local: no palette queries, no pushes, no animated transitions. - Custom hosts include
Themes::Hostand implementoutput(&),running?,survey(done)andtick(every, step) : -> Nil. They may overridenow,theme_changed(name)andpalette_changed. themes.revisioncounts palette and role changes; a compositor redraws when it sees a new revision.
Utilities
| Module | Contents |
|---|---|
TextLayout |
width, cluster_width, clusters, wrap, truncate, expand_tabs, column, index, fit_tail, offset. Every width-dependent function takes segmenter:; pass ui.segmenter to measure with a compositor's profile. |
ColorSpace |
sRGB, linear, Lab, Oklab, Oklch conversion; mix, contrast, apca, luminance |
Palette |
stock, generate, mix, nearest, nearest_chroma, light? |
Stroke |
Box-drawing shapes: pieces, arms, bends, nodes, fades, caps, line styles (Light, Heavy, Double, Dashed, Dotted), fills and tones |
Bitmap |
RGBA canvas: fill, blend, line, disc, arc, crop, changes, regions, shift (rectangles are Asekii::Rect) |
Graphemes |
Grapheme interning and the default width profile=; Compositor#profile= overrides it for one compositor |
Raster
raster = Asekii::Raster.png(bytes) || raise "bad png"
small = raster.scale(64, 32)
sixel = small.to_sixel
png = small.to_png
- Constructors:
Raster.rgba,Raster.rgb,Raster.png(all bit depths and color types, with Adam7 interlacing). - Methods:
crop,scale(premultiplied triangle filter),to_png,to_sixel/sixel(wire)(median-cut, 255 colors),Raster.iterm.
License
MIT
asekii-term
- 0
- 0
- 0
- 0
- 3
- 28 days ago
- October 20, 2026
MIT License
Mon, 26 Oct 2026 02:49:57 GMT