Heydrun's scripting
A .hex script is a small, sandboxed program that reacts to chat events, talks to the network, draws UI, and calls HTTP/JSON. The interpreter (parser + backend + view renderer) ships inside the APK; features ship as .hex scripts that the engine loads. The scripts that come with Heydrun are imgpaste.hex, translate.hex and whoisfilter.hex; the poker table below is an example of a script that draws a screen.
Scripts can show things, get someone's attention in ways they can see, hear or feel, change what's read aloud, and draw screens that work for sighted people and screen reader users alike. Accessible scripts shows how, with complete examples; §16 sums it up.
Implementations: (HexParser, HexScriptBackend, HexView, ScriptSurface, ScriptEngine, HexDroidScriptHost)
1. File anatomy
A script is a flat list of two things:
- event handlers
on <EVENT> {... } - aliases (named subroutines / slash-commands)
alias <name> {... }
; comments run from a semicolon to end of line
on LOAD {
set %greeted 0
}
alias hello {
echo $chan Hello, $1!
}
Comments: everything from the first ; on a line to the newline is stripped before parsing. There are no block comments. Because stripping cuts at the first ;, a value containing a literal ; cannot be written inline with a trailing comment on the same line.
Whitespace is not significant beyond separating tokens; { / } group bodies and may span lines. Statements are separated by newlines or by | on one line. eg: (poker_deal | return).
2. Values, variables, arguments
Everything is fundamentally a string; numbers are strings that parse as numbers, and there are two structured types (list, map) produced by functions.
Globals %name
Persist for the lifetime of the engine (across events), shared by all scripts in the one engine instance. Set with set, read as %name.
set %count 0
inc %count ; +1
dec %count ; -1
unset %count
Because there is a single engine per app,
%globals are not per-network or per-buffer, a value set while on one server is visible on another. They are not per-script either: two scripts that bothset %epoverwrite each other, and the lastLOADto run wins. Prefix a script's globals (%img_ep,%tr_ep) and keep scratch values in locals.
inc, dec and unset take the variable name (inc %count), not its value.
Locals set -l
set -l %name <value> writes a variable that lives only for the current handler or alias call (and any foreach item variable is local the same way). Locals shadow globals of the same name while the call runs, then vanish. Use them for scratch values inside an alias so two scripts don't collide on a shared %global.
Fields $field (read-only context)
Populated per event/handler:
| field | meaning |
|---|---|
$network | network id the event is on |
$buffer, $chan, $target | the buffer/channel (all three alias the same value) |
$text | the message text (TEXT/ACTION/INPUT/NOTICE/HIGHLIGHT), the part, quit, kick or disconnect reason, what would be said (SPEAK), or on / off (DND) |
$nick | sender's nick (when present); for KICK the kicker, for NICK the old nick, for TYPING who's typing |
$me | your current nick |
$isme | "true" / "false": the event is about you (your line from another client in TEXT, your own line being read in SPEAK, your own join, part, quit or nick change, or your being kicked) |
$isprivate | "true" for a private message or notice (and in HIGHLIGHT, TYPING and SPEAK, a query), "false" in a channel |
$iscmd | INPUT only: "true" when the line is a /command |
$victim | KICK: who was kicked; MODE: whose status changed |
$mode | MODE only: the change, such as +v or -o |
$newnick | NICK only: the new nick |
$account | JOIN only: the joiner's services account, when the server reports it |
$isserver | NOTICE only: "true" for a server notice |
$url | URL only: the link |
Signals carry their own extra fields (e.g. HTTP callbacks add $httpok, $httpstatus, $httpbody - see §10).
These read the same in any handler:
| identifier | value |
|---|---|
$ctime | the current Unix time, in seconds |
$ticks | milliseconds from a steady clock, for measuring intervals; only differences between readings mean anything |
$time | the local time as HH:mm:ss |
$screen.landscape / $screen.tv | 1 or 0 |
$screen.width / $screen.height | the display size in dp, for choosing a view layout |
$screen.reader | 1 while a screen reader using explore by touch, such as TalkBack, is on, otherwise 0 |
$screen.dnd | 1 while Heydrun's Do not disturb is on, otherwise 0 |
$screen.motion | 0 when the phone's Remove animations is on, otherwise 1 |
Positional arguments $0 $1 $2...
Handlers and aliases receive arguments:
$0the number of arguments (not the text). Use$1-for the whole argument string.$Nthe Nth argument (1-based)$N-argument N through the end, space-joined (e.g.$2-)$N-Marguments N through M, space-joined
For alias, the args are what followed the command. For SIGNAL: handlers, the args are whatever was passed to signal/timer/http.* as trailing context.
Escaping
Write a literal dollar with $$ and a literal percent with %%. A lone sigil that is not followed by a name character is also taken literally, so 50% and cost $5 today survive as written, and % means modulo inside $calc(...) rather than being read as an empty variable. (A sigil is only an expression when a letter, digit or _ follows it.)
3. Events
Register with on <EVENT> {... }. Event names are case-insensitive.
| event | fires when | notes |
|---|---|---|
LOAD | after every (re)load of the scripts | set up globals, register sidebar launchers here |
TEXT | an incoming chat line arrives | can transform or suppress it (see below). Not for lines you send from this device (that's INPUT); your own lines from another client, such as through a bouncer, arrive with $isme true |
ACTION | like TEXT but for /me actions | |
INPUT | you press send in the input box, before the line is processed | can transform/suppress it; /commands included ($iscmd). Lines sent by scripts, buttons and menus don't trigger it |
NUMERIC | a server line is about to be printed | $code is the numeric; can transform or suppress it |
JOIN | someone joins a channel, you included | $nick, $chan, $account |
PART | someone leaves a channel | $text is the part message |
QUIT | someone disconnects from the network | $text is the quit message; $chan is empty |
KICK | someone is kicked | $nick kicked $victim; $text is the reason; $isme when it's you |
MODE | someone's channel status changes (op, voice, ...), once per change | $mode e.g. +v, $victim whose status, $nick who set it |
OP DEOP VOICE DEVOICE HELP DEHELP | the matching status change, alongside MODE | $victim (also $opnick $vnick $hnick), $nick who set it |
BAN / UNBAN | a ban is set or removed | $banmask, $nick who set it |
RAWMODE | any channel MODE line, once | $text e.g. +bv *!*@host alice |
TOPIC | the topic changes | $text is the new topic |
INVITE | you're invited | $nick invited you to $chan; echo $chan would open that buffer, so use echo -a |
CTCP | a CTCP request (not /me) | $text e.g. VERSION or PING 1234; Heydrun still answers the ones it knows |
CTCPREPLY | a reply to a CTCP you sent | $text is the command and reply |
SNOTICE | a server notice, alongside NOTICE | |
NOTIFY / UNOTIFY | someone on your /monitor list comes online / goes offline | $nick |
APPACTIVE | the app comes to the front / goes to the background | $appactive is true / false |
FILERCVD / FILESENT | a DCC transfer finishes | $filename; received files also $filesize, $path |
NICK | someone changes nick | $nick is the old nick, $newnick the new |
NOTICE | a notice arrives (service replies included) | $nick, $text, $isprivate, $isserver; a private notice has no $chan; ignored nicks never reach scripts |
CONNECT | registration completes on a network | identify or join channels here |
DISCONNECT | a connection that was up closes | $text is the reason; a failed connect attempt doesn't count |
SPEAK | a line in the buffer on screen is about to be read aloud | $text is what would be said, $nick the sender (empty for events and alerts), $isme true for your own line; can rewrite or halt it. Encrypted lines only while Scripts can read encrypted messages is on |
HIGHLIGHT | a live line from someone else mentions you, or a private message arrives, in any buffer | $nick, $text, $chan (for a private message, the query), $isprivate. Not for history or your own lines; encrypted lines only while Scripts can read encrypted messages is on. Runs whether Heydrun is open or not |
TYPING | someone starts typing in a channel or query | $nick, $chan (for a query, their nick), $isprivate; $text is empty. Only while Show others' typing indicators is on, and only on servers that send typing notices |
BUFFER | you move to another buffer | $chan and $network are the buffer you moved to; $text is empty. Not when Heydrun opens or comes to the front (see APPACTIVE) |
DND | Heydrun's Do not disturb turns on or off, however it was done | $text is on or off, so on DND:off runs only as it ends; $chan is the buffer you're in |
URL | a link is added to the Links list | $url is the link, $text the whole message, $nick who posted it, $chan where. Once for each link in a line. Only while Collect links is on, so only for live lines, and your own only with Include your own links; links in encrypted buffers only while Log encrypted messages is on. An on URL:<pattern> filter matches $text, so on URL:*youtube* works |
SIGNAL:<name> | a signal, timer, or HTTP callback fires <name> | your own async plumbing |
Optional glob filter: on TEXT:*help* only runs when the text matches the glob (case-insensitive). Channel events (JOIN, PART, KICK, MODE, the status events, BAN/UNBAN, RAWMODE, TOPIC, INVITE) filter on the channel instead, so on JOIN:#help runs only there; every other event filters on $text, so filter a numeric by testing $code in the body. TYPING and BUFFER have no text, so give them no filter and test $chan or $nick in the body instead.
Headers pasted from mIRC work too: on *:TEXT:*hello*:#:{ is read as <level>:<event>:<match>:<target>:. The level (and prefixes such as @ or !) is ignored, since Heydrun has no user levels. The match text works like a filter (it may contain spaces and colons); with a $ in the level it's a regex instead, as in on $*:TEXT:/^!seen (\S+)/i:#:{. The target is # for channels, ? for private messages, * for both, or a comma list such as #help,#dev. on *:SIGNAL:name: and on *:START: work too, as on SIGNAL:name and on LOAD. For JOIN, PART, KICK and MODE the target is the channel list. A handler for an event Heydrun never raises is reported in the script log at load, rather than silently never running.
The IRC events (JOIN through DISCONNECT) fire only for live traffic, never for history replayed after a reconnect, so a bouncer's backlog doesn't greet everyone again. They report what happened and can't rewrite or halt it.
on CONNECT { msg NickServ IDENTIFY %ns_pass } ; identify as soon as you connect
on JOIN:#help {
if ($isme == true) { return }
notice $nick Welcome to #help, $nick. Ask away, someone will answer.
}
on NOTICE {
if ($nick == NickServ && $contains($text, "You are now identified") == true) { join #private }
}
NUMERIC fires for server output such as WHOIS replies, MOTD lines and error numerics. $code holds the three digit code, or is empty for server text that carries none, and $buffer is where the line was about to be printed, which for a WHOIS reply is the buffer the WHOIS was run from. $whois is true when the line was matched to a WHOIS the user ran, so a filter can leave the same numerics alone elsewhere (301 also answers a message sent to someone away). Suppressing a line hides it; the client still acts on it internally.
Transforming / suppressing text. In TEXT/ACTION/INPUT/NUMERIC handlers:
rewrite <new text>replaces the line that will be shown/sent.haltsuppresses the line entirely (it is not shown/sent) and stops the handler.- returning normally leaves the line unchanged.
SPEAK works the same way on what's said rather than what's shown: rewrite says something else, halt says nothing, and the line in the chat stays as it was. It runs for lines read aloud from the buffer on screen (new messages, events, the results of commands you type, connection alerts), not for mentions announced from other buffers, /speak, /last, /catchup or a script's own speak. $text is the whole spoken line, worded by the user's reading settings (nick, time, encryption note), so match it with isin, iswm or a filter such as on SPEAK:*http* rather than comparing it whole.
on SPEAK:*http* { rewrite $re_replace($text, "https?://\S+", "link") }
HIGHLIGHT, TYPING, BUFFER, DND and URL report what happened, like the IRC events, and can't rewrite or halt anything. HIGHLIGHT comes alongside Heydrun's own alerts for a mention, not instead of them, so a handler that alerts again makes it twice as loud; use it to keep, forward or count mentions rather than to sound them. BUFFER is how a script knows which buffer you're in, as there's no field for it:
on BUFFER { set %here $chan }
on TYPING {
if ($chan == %here) { return }
echo -s $nick is typing in $chan
}
on DND:off { echo -a Do not disturb is off }
LOAD runs on the app's main path at (re)load. TEXT/ACTION/INPUT and the IRC events run synchronously when the line is processed. See §12 for threads.
4. Commands
One command per statement (verb first). Full set:
| command | purpose |
|---|---|
set %v <value> | assign a global (value is set-trimmed); set %v with no value clears it to "" |
set -l %v <value> | assign a local (current handler/alias call only) |
unset %v | remove a variable |
inc %v / dec %v | +1 / −1 numeric |
push %v <value> | append to a list variable |
setat %map <key> <value> | set a map/list entry |
rewrite <text> | replace the current event's text (TEXT/ACTION/INPUT/NUMERIC), or what's said (SPEAK) |
echo <buffer> <text> | print a local line into <buffer> (not sent to the server). -a is the buffer you're in, -s the server buffer; a variable that's empty (like $chan in QUIT) also means the one you're in. An echo into the buffer on screen just after a command you typed is read aloud as that command's result, as Heydrun's own are |
msg <buffer> <text> | send a PRIVMSG to <buffer>; if <buffer> is a variable that's empty, nothing is sent |
raw <line> | send a raw IRC line |
signal <name> [args…] | fire SIGNAL:<name> now |
timer <ms> <signal> [args…] | fire SIGNAL:<signal> after <ms> (at least 20) |
log <text> / debug <text> | write <text> to the script debug log (development aid) |
sidebar add|remove... | manage a sidebar launcher (see §11) |
http.get <url> <signal> [ctx…] | async GET, result to SIGNAL:<signal> (§10) |
http.post <url> <body> <signal> [ctx…] | async POST (§10) |
view {... } | mount an interactive UI (§9) |
foreach %x %collection {... } | iterate a list/map (§7) |
while (<cond>) {... } | loop while the condition holds (§7) |
if / elseif / else | conditionals (§6) |
return / halt / break / continue | control flow (§7) |
<aliasname> [args…] | call another alias |
toast <text> | show a brief on-screen notice; TalkBack usually reads it |
notify <text> | post a notification in Heydrun's Scripts category, whether Heydrun is open or not; its title is the buffer the script ran in, such as the channel of the message or where its command was typed, and tapping it opens that buffer. A script that ran with no buffer, such as from a timer, uses the buffer on screen. Needs Show notifications on; posted without sound during Do not disturb. Colour codes are removed and the text cut to 1000 characters |
flash | flash the edge of the screen once, as for a mention, whether or not Flash for mentions is on; with Remove animations on it shows and goes without fading |
vibrate [mention|private] | play Heydrun's mention or private message vibration; with anything else, or nothing, a short knock. Needs In-app vibration on, and follows Vibration type, Vibration strength and Vibrate even on silent |
sound <name> | play one of Heydrun's in-app sounds: message, action, notice, private, mention, highlight, join, part, quit, nick, topic, typing, invite, kick, dcc, online, offline, connected or disconnected. Follows In-app sounds and that sound's own switch, vibrates as that sound does, and shows its caption when Captions for sounds is on (all but message, action and notice have one). An unknown name is ignored |
speak <text> | say <text> aloud through the user's Speak with choice (screen reader or Heydrun's voice), for a spoken cue that isn't on screen. Not for ordinary output: a screen reader already reads what's shown. Only while Scripts can speak is on; colour codes removed, cut to 500 characters |
speak -i <text> | the same, stopping whatever is being said first. Keep it for what can't wait, such as "your turn" |
stfu | stop speaking now, as /stfu does |
dnd on|off|<minutes> | turn Heydrun's Do not disturb on until turned off, off, or on for 1 to 10080 minutes; sets away when Set away while on is on. Anything else is ignored |
flash, vibrate, sound and speak work only while Heydrun is open, and are held while its Do not disturb is on: a held sound still shows its caption, and connected, disconnected, and private with Let private messages through on, sound anyway, as Heydrun's own do. notify works with Heydrun closed, and during Do not disturb is posted silently. Each of speak, flash, vibrate, sound and notify works at most 5 times in any 5 seconds; past that they're dropped, not queued, and none of them makes an error when held, so the script carries on.
The notify command posts a notification. It's unrelated to the NOTIFY event and to the /notify command, which are about the notify list.
decorate and action are accepted by the parser and dispatched as UI intents, but the current host ignores them (reserved). Don't rely on them yet.
A script can also run these app commands, in the buffer its event came from: me, join, part, cycle, topic, mode, invite, kick, knock, names, who, whois, whowas, list, notice, ctcp, nick, away, back, op, deop, voice, devoice, ban, unban, ignore and unignore. Commands that would drop or move the connection (quit, server and the like) are left out on purpose; raw remains for a script that really means it. Any other unknown verb is reported in the buffer and skipped.
5. Functions
Call as $name(arg, arg,...). Args are comma-separated and trimmed; they may themselves be $/% expressions. Functions never mutate their inputs. Because args are trimmed, a separator with surrounding spaces can't be passed literally - e.g. $join(%xs, , ) yields an empty separator, not ", ".
String: $len(s) $lower(s) $upper(s) $left(s,n) $right(s,n) $substr(s,start[,len]) $replace(s,find,to) $trim(s) $contains(s,sub)→bool $indexof(s,sub) $repeat(s,n) $pad(s,n[,ch]) $padleft(s,n[,ch]) $capitalize(s) $title(s)
A negative n counts from the other end, as in mIRC: $left(s,-2) is all but the last two characters and $right(s,-2) all but the first two.
Regex (Java/Kotlin flavour; input capped at 20 000 chars): $re_match(s,pattern)→bool $re_find(s,pattern) (first whole match) $re_group(s,pattern,n) (capture group n; 0 = whole match) $re_replace(s,pattern,to) (literal replacement - no $1 backrefs, since $ is the script sigil). An invalid pattern makes re_match/re_find/re_group return empty and re_replace return the input unchanged.
Math: $calc(expr) (arithmetic + - * / % with parens, e.g. $calc((%pot + %bet) % 2)) $mod(a,b) $idiv(a,b) (integer/floor division) $int(x) (floor) $round(x[,dp]) $ceil(x) $abs(x) $pow(a,b) $clamp(x,lo,hi) $rand(n)→0..n−1 / $rand(lo,hi)>inclusive. $rand, $pick and $shuffle are fine for games but not unguessable; use $age.rand(n) for secrets. $min(…)/$max(…) take either several numeric args or a single list $max(3,9,2) and $max(%scores) both work.
/is floating-point division.$calc(5 / 2)is2.5, not2. For whole-number results (chip counts, indices, anything you store or compare as an integer) use$idiv(5, 2)→2, and take the remainder with%:$calc(5 % 2)→1. ($int($calc(5 / 2))works too but reads worse.) A stray fractional value that reaches a stored quantity will surprise you later.
Collections: $list(…) $map(k,v,k,v,…) $get(coll,key) $len(coll) $keys(map) $values(map) $has(coll,key)→bool $sort(coll) $reverse(coll) $join(list[,sep]) $split(s[,sep]) $slice(coll,from,to) $concat(…) $find(list,item)→index $count(coll,item) $sum(list) $range(lo,hi) $pick(list) (random element) $shuffle(list) $tojson(value)
Double-quoted function arguments are string literals. The quotes delimit the value (one layer is stripped;
$/%inside still expand), so a delimiter or separator that contains spaces or commas is written naturally:$split(%s, " ")splits on a space,$split(%csv, ",")on a comma,$join(%l, ", ")inserts a comma+space. The argument splitter ignores commas and parens inside quotes. Unquoted args behave as before:$split(%s)splits on spaces,$split(%s, ~)on a bare~.
Misc: $setting(key) (host settings; e.g. applang/lang → device language code such as en) · $json(body,path) (§10) · $urlencode(s)
Calling an unknown $name(...) yields an empty string (the function set is closed) and logs hex: unknown function $name() - check the log if a value comes back mysteriously blank.
6. Conditionals & operators
if (%turn == 2) {... }
elseif (%turn > 2) {... }
else {... }
Comparison operators: == != < > <= >=. If both sides parse as numbers they compare numerically, otherwise lexically. Also:
isin-a isin bis true whenbcontains the substringaiswm- wildcard match, e.g.$text iswm hello*
Word operators (isin, iswm) need surrounding spaces. Combine tests with && / || and negate a bare test with !. A bare value is truthy when it is non-empty and not "false" or "0" - so if (%flag) {... } works.
Conditions are evaluated left to right: || groups are tried, each an && chain of comparisons, with no precedence between &&/|| beyond that order. Parenthesised grouping is supported and nests to any depth, and !(...) negates a whole group:
if ((%a == 1 || %b == 1) && %c >= 5) {... }
if (!(%started == 1 && %ishost == 0)) {... }
Function-call parens inside a comparison ($get, $len,...) are unaffected; a group is recognised only when a (...) pair spans one whole &&/|| term.
7. Control flow
returnleave the current handler/alias.haltsuppress the current event's line (TEXT/ACTION/INPUT) and stop.foreach %item %collection {... }iterate a list's items, or a map's keys.while (<cond>) {... }loop while the condition (§6) holds;break/continueapply. There is no built-in iteration cap, so awhileis bounded only by the step/time budget (§12) make sure the condition can become false.break/continueinside aforeachorwhile.timer <ms> <signal> [ctx...]schedule work; the signal handler picks it up.signal <name> [ctx..]fire immediately.
foreach %fp %seats {
if ($get(%folded,%fp) == 1) { continue }
echo $chan seat: $get(%name,%fp)
}
set %i 0
while (%i < 3) {
echo $chan tick %i
set %i $calc(%i + 1)
}
8. Collections
Lists and maps are values you keep in globals:
set %seats $list()
push %seats alice
push %seats bob
set %stack $map()
setat %stack alice 1000
echo $chan $get(%stack, alice) ; 1000
foreach %p %stack { echo $chan $p = $get(%stack,%p) }
$tojson(%stack) serialises to JSON (strings JSON reads as a number, such as 12 or -0.5, emit unquoted so they round-trip; 007 and 1e5 stay strings); pair it with $json() to read structured data back. Control characters, IRC colour and bold codes included, are escaped.
9. The view DSL (view {... })
view {... } mounts an interactive surface (rendered by ScriptSurface). It is re-mountable - call view again to redraw with new state. When the user closes the surface, the engine fires SIGNAL:VIEW_CLOSED, so bind cleanup there:
on SIGNAL:view_closed { my_reset }
Elements
column, row, stack (z-stacked/overlapping), ring (radial), surface (a single framed child), text "…", button "label" <actionId> [args…] [props], card <code> [red] [back], image <url>, spacer.
Containers take a {... } body of child elements. foreach %x %coll {... } works inside a view body to lay out data-driven children (N seats, a list,...), and so does if (...) {... } elseif (...) {... } else {... }, to show a part only sometimes. The body is filled in before it's read, so a variable can also hold a prop, such as %off set to disabled; an empty one adds nothing.
Props (after an element, space-separated)
Flags: bold, fill (fill width), wrap (a row flows onto extra lines instead of overflowing), circle, ellipse (an oval shape on a surface - a poker felt, a token). Card flags: red (red suit), back (face-down). Image scale flags: crop (default, fills and clips), fit (letterbox), stretch (distort to fill).
Value props: width <dp>, height <dp>, size <dp>, radius <dp>, pad <dp>, gap <dp>, weight <f>, color <c>, bg <c>, textsize <dp>, offsetx <dp>, offsety <dp>, align <center|start|end|top|bottom>, border <color> [width], gradient..., elevation/elev, bgimage <url> (a surface background image, painted behind its child - layer a translucent gradient over it as a readability tint).
Screen reader props: alt "<text>" describes an image; an image without it is treated as decoration and skipped. heading makes a text a heading, which screen reader users can jump between, and the first heading also names the script's screen. live reads a text out whenever it changes, such as a score or whose turn it is. Use it for changes that matter, not for text that updates every second, such as a timer: each change interrupts the screen reader. A script's pictures load only while Settings > IRC > Let scripts load images is on.
On a button, alt "<text>" is its spoken name, for a label of symbols such as "♠" or "▲"; the label still shows. Quote an alt of more than one word. selected marks a button as chosen (a held card, a picked seat): it's read as selected, and drawn with an outline in the theme's primary colour. A word on screen helps too, such as "You said higher". disabled marks one that can't be used right now: it's drawn faded, keeps its place and its focus, is read as disabled, and a tap does nothing. A variable can hold several props at once, such as %pick set to selected bg #1565c0.
Don't let colour alone carry meaning, as some people can't tell colours apart and screen readers don't say them: a right answer also says "Right", whose turn it is is also in a live text, and a chosen button is also selected.
button "▲" hl_guess higher alt "Higher" selected
button "▼" hl_guess lower alt "Lower" disabled
merge on a container reads everything in it as one item, such as a seat's name, chips and cards, or a label and its value. With alt as well, that name is read instead of the contents. Quote a name of more than one word: column merge alt "Seat 1, 500 chips".
game on the root container marks the view as a game, which keeps its animations when the phone's Remove animations is on, as Android games do. It has to be on the one outermost container (several top-level elements are wrapped in a plain column). A script also shows as a game, with a Game badge on the Scripts screen, when a ; @game comment is among the comment lines at the top of the file, before any code.
A ring reads its children in the order they're written, child 0 first, whatever their place around the table, so write seats in turn order. A card is read as one name, such as "Queen of hearts" or "Face-down card". A new card face drops in with a bounce, except when Remove animations is on and the view isn't a game: then it just appears.
A remote image loads from its URL with no bundled asset, so rich table art costs no APK size. Compose a scene by layering: an outer surface with a bgimage, an ellipse felt surface on top, image <url> circle avatars, and cards.
view {
column gap 8 pad 12 {
text "Table" bold heading
text "$turn to play" live
row gap 6 wrap {
foreach %fp %seats { card $get(%hole,%fp) width 30 }
}
row gap 8 {
button "Fold" poker_fold
button "Call" poker_call
}
}
}
Buttons >→< actions
A button's first token is an action id; remaining non-prop tokens are args. Tapping it runs an alias of that name if one exists, otherwise fires SIGNAL:<ACTIONID>. So button "Deal" poker_start calls alias poker_start (or fires SIGNAL:POKER_START).
10. HTTP + JSON
http.get [flags] <url> <signal> [ctx…]
http.post [flags] <url> <body> <signal> [ctx…]
http.post [flags] -b %var <url> <signal> [ctx…]
Flags go before the URL:
| flag | effect |
|---|---|
-t <type> | sets Content-Type instead of letting the body shape decide |
-h <name:value> | adds a request header; repeat for more than one |
-b %var | takes the body whole from a variable, spaces and quotes included |
Flag values are read before expansion, so a %var in one is that variable's whole value rather than the tokens the argument splitter would otherwise break it into. That is what makes -b the way to send JSON: the positional body is one space-delimited token, so anything with a space in it has to arrive through -b. Write a header whose value has spaces the same way (set %auth Authorization: Bearer $token, then -h %auth).
Both are asynchronous: they fire the request and return immediately; when it completes, SIGNAL:<signal> runs with these extra fields plus your ctx as $1 $2...:
| field | meaning |
|---|---|
$httpok | "true" if status 200-299 |
$httpstatus | numeric HTTP status |
$httpbody | response body, cut off after about 1 MB |
$httplocation | Location header, or empty; upload endpoints answering 201 Created put the new URL here rather than in the body |
$httperror | why the request never got a status, when $httpstatus is 0: blocked by policy, unreachable, a file too large, and so on |
Without -t, the POST body's Content-Type is inferred: a body starting { or [ is sent as JSON, one that looks like key=value&key=value (has =, no spaces) is sent form-urlencoded, and anything else goes as text/plain. $urlencode() your values when using the positional body so it stays space-free.
Posting JSON to an endpoint that wants a token looks like this:
alias paste {
set -l %payload $tojson($map(text, $1-, lang, irc))
http.post -t application/json -h %auth -b %payload https://paste.example/api paste_done $buffer
}
on SIGNAL:paste_done {
if ($httpok == true) { echo $1 pasted: $httplocation }
else { echo $1 paste failed ($httpstatus) }
}
-b only sends text a script already holds. To send a file, see media.* below.
The callback (and any signal/timer you fire from a handler) runs on the same network and buffer the originating event came from, even if you have since switched to another network. So echo, msg, and raw inside the callback go back to where the message was, not to whatever window is active when the reply lands. Thread the buffer through ctx (as translate.hex does with $buffer) so you know where to echo.
Read JSON out of the body with $json(body, path). The path is dot-separated and supports object keys and array indices:
$json($httpbody, translatedText) ; {"translatedText": "..."}
$json($httpbody, detectedLanguage.language) ; nested object
$json($httpbody, 0.2) ; arrays: element [0] then [2]
Because the request is async and its handler can echo into the passed-through buffer, the classic pattern is to thread the target buffer + original text as ctx:
on TEXT {
if ($isme == true) { return }
http.post %tr_ep q=$urlencode($text)&target=en tr_done $buffer $text
}
on SIGNAL:tr_done {
if ($httpok == true) { echo $1 ↳ $json($httpbody, translatedText) }
}
Network access is subject to the host's policy; a blocked or failed request returns $httpok == false with the reason in $httperror (don't forget an else: a silent success-only handler is why a failing endpoint looks like "nothing happened"). Scripts get no network access at all while any network using a proxy is connected.
Uploading a file
media.pick [-m <mime>] <signal> [ctx…]
media.upload [-h <name:value>] [-p <name=value>] [-f <field>] [-r] <url> <token> <signal> [ctx…]
media.pick does not open anything by itself. Heydrun shows a prompt naming the buffer and network the script is running in, and only if the user agrees does the system file picker appear. The script is then handed a token for that one file, never a path, and can read nothing else on the device. Tokens last until scripts are reloaded.
The pick's signal is delivered only to the script that called media.pick, and only that script can upload with the token. After the user declines, further picks from the same script are refused without a prompt for a minute, unless they come from a command the user ran.
SIGNAL:<signal> from a pick carries:
| field | meaning |
|---|---|
$mediaok | "true" if a file was chosen; "false" if the user declined |
$mediatoken | opaque handle to pass to media.upload |
$medianame | file name as shown to the user |
$mediamime | MIME type |
$mediasize | size in bytes, or -1 when the provider doesn't say |
media.upload sends that file to the URL without the bytes ever passing through the script. The request body is staged in the cache first so it carries an exact Content-Length: a chunked upload is invisible to servers that parse multipart from the content length (PHP's parser is one), which answer as though no file arrived. It POSTs multipart/form-data under field name file by default (-f <field> to rename it, -r to send the bytes as the raw body instead, -p <name=value> to add a text form field beside the file, repeatable, which is how an endpoint's own options are passed), and answers with the same fields an http.post does, $httplocation and $httperror included. Files over 64 MB are refused with $httperror saying so. Redirects are not followed, so a 3xx is reported rather than resending the file to a host the permission check never saw.
alias img { media.pick -m image/* img_picked $buffer }
on SIGNAL:img_picked {
if ($mediaok != true) { return }
media.upload https://paste.example/img $mediatoken img_done $1
}
on SIGNAL:img_done {
if ($httpok != true) { echo $1 upload failed ($httpstatus) $httperror | return }
set -l %url $trim($httplocation)
if ($len(%url) == 0) { set -l %url $trim($httpbody) }
msg $1 %url
}
Redirects are not followed, so an endpoint that answers with a 301 to a trailing slash or to an index.php reports that 301 instead of uploading; the error names where it wanted to send you, and that address is what belongs in the URL.
There is no empty-string literal: %url == "" compares against a two-character string and is never true for a blank value. Test emptiness with $len(%url) == 0.
Only one pick can be outstanding at a time; a second request while the prompt is up is answered with $mediaok false rather than stacking dialogs.
Point the URL at the exact endpoint, file name included, since a directory URL that answers 301 is not followed. And check the body even on a 2xx: upload endpoints often answer 200 with a JSON body describing a failure, so $httpok alone is not success.
11. Sidebar launchers
Scripts contribute entries to the app's script launcher list:
on LOAD { sidebar add poker poker_open Poker Night }
sidebar add <id> <command> <label words…> registers a launcher that runs <command> (an alias, or a SIGNAL:) when tapped; sidebar remove <id> drops it.
12. Threads & lifecycle
- Every handler runs on the app's main thread:
LOAD, aliases and buttons, events, and thetimer,http.*andmedia.*callbacks. Handlers never run at the same time as each other. TEXT/ACTION/INPUT/NUMERICrun synchronously while the line is processed; return quickly. Do slow work by firing anhttp.*/timerand finishing in the signal handler.- Signals fire the matching
SIGNAL:handler in every script that registered it, except the signal frommedia.pick, which only reaches the script that asked.
A script is dropped and reloaded (its handlers cleared and re-registered, LOAD re-fired) on reload; globals do not survive a reload. Anything still pending is cancelled too: a timer, http.* request or media.* pick started before the reload never answers afterwards, so an edited script never receives its previous copy's callbacks.
13. Sandbox notes
- No filesystem, no arbitrary process access, only the commands/functions above.
- Networking goes through the host HTTP with a policy check; there is no raw socket.
- A script only affects buffers/networks via
echo/msg/raw, and UI viaview/sidebar/toastand the alerts below. speakis said only while Scripts can speak is on (Settings, Accessibility; on by default), Heydrun is open and its Do not disturb is off, and at most 5 lines in 5 seconds.flash,vibrate,soundandnotifyfollow the user's own settings for each (§4), and each works at most 5 times in 5 seconds, so a script can't flood the user with alerts.- With Scripts can read encrypted messages off (Settings, Privacy),
on TEXT,on NOTICE,on INPUT,on SPEAKandon HIGHLIGHTdon't fire for messages in an encrypted channel or query. Commands typed there still reachon INPUT. - Bundled scripts ship disabled; the user opts in from the Scripts screen. Editing a bundled script in-app preserves your edits across app updates; unedited bundled scripts are refreshed to the shipped version on update.
14. age.* encrypted transport for scripted games (Heydrun)
These are part of the app, not core language, used by games eg: poker.hex to run over the +AGE encrypted channel/among peers (and to drive practice bots locally):
Commands: age.join <chan>, age.host <chan>, age.send <chan> <tokens…> (send to peers, fail-closed until keyed), age.local <from> <tokens…> (inject an event as another local seat - practice bots), age.seal <fp> <c1> <c2>, age.close <chan> (drop a closed table's keys and roster), age.purge <chan> (drop its queued outgoing lines). Functions: $age.me (your fingerprint), $age.rand(n), $age.sha(s), $age.fp(nick) (a pinned nick's fingerprint), $age.ready(chan) (true once keyed), $age.owner(chan) (the elected host: the lowest fingerprint present, identical on every client) and $age.members(chan) (the other +AGE members present, space-separated).
Incoming peer messages surface as SIGNAL:AGE_MSG with the sender's fingerprint in $from and the payload tokens in $1 $2.... Sealed hole cards arrive as SIGNAL:AGE_DEAL with $from and the dealt tokens in $data. SIGNAL:AGE_PEER ($chan, $fp) fires when someone announces themselves on a channel, SIGNAL:AGE_READY ($chan) when a channel becomes keyed, and SIGNAL:AGE_LEFT ($chan, $from, $nick) when a member leaves by part, quit or kick; $from is your own fingerprint when you leave or lose the connection. See poker.hex for a full worked example.
15. Example
; shout.hex
; echo a loud copy of anything containing "!!!"
on LOAD { sidebar add shout shout_help Shout help }
alias shout_help { echo $chan shout.hex: I echo lines containing !!! in caps }
on TEXT {
if ($isme == true) { return }
if ($text iswm *!!!*) { echo $chan 📣 $upper($text) }
}
16. Accessibility
People use Heydrun by eye, by ear with a screen reader, without sound, and in noisy or quiet places, so a script should work for all of them. In short:
- Show what a script has to say, with
echo,toastor a view. A screen reader reads what's on screen, so that reaches its users too. A script's echo right after a command you typed is read aloud as that command's result; otherwise only when events are read aloud, as it has no sender. - Get attention in more than one way:
notifyfor everyone, open or not;flashto see;vibrateto feel;sound <name>to hear, captioned. Each follows the user's settings and Do not disturb, at most 5 in 5 seconds. speakonly for a spoken cue that isn't on screen, or that someone would otherwise have to go looking for, such as "your turn" when the bot's line doesn't say it's you.speak -icuts in first,stfustops.$screen.reader,$screen.dndand$screen.motionsay whether a screen reader, Do not disturb and Remove animations are on.dnd on|off|<minutes>sets Do not disturb, andon DNDruns as it changes.on SPEAKcan reword or silence what's read aloud, without changing the chat.- In a view: a
headingnames the screen, buttons havealtnames andselectedanddisabledstates (selectedis outlined,disabledfaded),mergereads a group as one item, and onelivetext says what just happened. Don't let colour alone carry meaning. Rings read in seat order and cards by name.gameon the root and; @gameat the top mark a game.
Accessible scripts explains each of these, how to test a script with TalkBack and with the sound off, and has complete examples: a dice roller, a reminder, a turn cue, a list of what you missed during Do not disturb, away notes, SPEAK filters, and a higher or lower card game.