Apps in Rust, Go, or JavaScript
A ztk window does not need an app in Tcl. ztk has ztcl::wasm, the WebAssembly engine of ztcl, so a program in a language that compiles to WebAssembly can make the widgets and get the events. The window is a native ztk window: the same widgets, the same renderer, and the same platform code as for a Tcl script.
Each language has a binding: a library that puts the Tk API in the form of the language. Select a language, and each example of this page shows it.
| Language | Binding | Toolchain |
|---|---|---|
| Rust | ztk-rust | cargo with the target wasm32-unknown-unknown |
| Go | ztk-go | TinyGo with the target wasm-unknown |
| JavaScript | ztk-wasm-demos, folder js |
QuickJS, built for wasm32-wasi with zig cc. The engine and the script are one module. |
The same app in each language
The hello app has a label, an entry, and a button. The button writes a greeting with the text of the entry into the label.
pub use tk::app_event;
use tk::{Button, Entry, Label, Pack};
#[no_mangle]
pub extern "C" fn app_init() {
let root = tk::root().title("Hello from Rust");
let msg = Label::new(root).text("Type a name.").id("msg");
let name = Entry::new(root).width(24).id("name");
let greet = Button::new(root).text("Greet").id("greet").on_click(move || {
msg.text(&format!("Hello, {}, from Rust!", name.get()));
});
let pad = Pack { padx: 16, pady: 8, ..Pack::default() };
msg.pack(pad);
name.pack(pad);
greet.pack(pad);
}
package main
import "github.com/beetlebugorg/ztk-go/tk"
//go:wasmexport app_init
func appInit() {
root := tk.Root()
root.SetTitle("Hello from Go")
msg := tk.NewLabel(root, tk.Opts{ID: "msg", Text: "Type a name."})
name := tk.NewEntry(root, tk.Opts{ID: "name", Width: 24})
greet := tk.NewButton(root, tk.Opts{ID: "greet", Text: "Greet", Command: func() {
msg.SetText("Hello, " + name.Get() + ", from Go!")
}})
pad := tk.Pack{PadX: 16, PadY: 8}
msg.Pack(pad)
name.Pack(pad)
greet.Pack(pad)
}
func main() {}
const root = tk.root.setTitle("Hello from JavaScript");
const msg = new tk.Label(root, { id: "msg", text: "Type a name." });
const name = new tk.Entry(root, { id: "name", width: 24 });
const greet = new tk.Button(root, {
id: "greet",
text: "Greet",
command: () => msg.configure({ text: `Hello, ${name.value}, from JavaScript!` }),
});
for (const w of [msg, name, greet]) w.pack({ padx: 16, pady: 8 });
The bindings have the same examples: this hello app, a spreadsheet with formulas, a vector drawing app, and a test of text with the special characters of Tcl. The Rust binding also has a gallery of each widget class.
Set up a project
rustup target add wasm32-unknown-unknown
cargo new --lib hello
Cargo.toml:
[lib]
crate-type = ["cdylib"]
[dependencies]
tk = { package = "ztk", git = "https://github.com/beetlebugorg/ztk-rust" }
[profile.release]
opt-level = "s"
lto = true
panic = "abort"
codegen-units = 1
strip = true
The app exports app_init, which builds the widgets. The line pub use tk::app_event; exports the function of the crate that runs the closures.
Install TinyGo 0.44 or later, and wasm-opt of Binaryen on the PATH or in WASMOPT.
go mod init example.com/hello
go get github.com/beetlebugorg/ztk-go
The app exports app_init with //go:wasmexport app_init. The package exports the function that runs the callbacks, and main stays empty.
The module is the QuickJS engine with the script in it. js/build.sh of ztk-wasm-demos builds the engine with zig cc -target wasm32-wasi and puts one script into the module. The script is the app: the top level of the script builds the widgets.
Build and run
cargo build --release --target wasm32-unknown-unknown
ztk target/wasm32-unknown-unknown/release/hello.wasm
The hello module has 21,037 bytes.
tinygo build -target=wasm-unknown -gc=conservative -opt=z -no-debug -o hello.wasm .
ztk hello.wasm
The hello module has 7,869 bytes. -gc=conservative is the collector that frees memory: the default of the target does not free.
js/build.sh
ztk dist/js-hello.wasm
The spreadsheet module has 926 KB, by the numbers of the demo repository: the module has the engine.
A file with the extension .wasm on the command line of ztk is an app. ztk loads the module, gives it the imports of tk, and calls its export app_init.
Run an app from a URL
ztk https://github.com/beetlebugorg/ztk-wasm-demos/blob/main/dist/rust-vector.wasm
ztk downloads the module and runs it. A module from the network is the code of a stranger, so it runs in a sandbox:
| Rule | What it does |
|---|---|
Only https |
An http URL is an error. The address of a file page of GitHub (.../blob/...) becomes the address of the file itself. |
| Only a module | The file has at most 64 MB and starts with the magic number of WebAssembly. A script in Tcl from a URL does not run. |
| No capability | The app has no file, no channel, no socket, no process, no clock, and no environment. --allow and --root with a URL are an error. |
| No host command | The commands that reach outside the window are gone before the module starts: send, interp, package, the file dialogs, ztk::hotkey, ztk::tray, ztk::taskbar, ztk::recent, ztk::dnd, ztk::toast, ztk::terminal, and the commands of ztk::mac and ztk::win. |
| Its own clipboard | Copy and paste work inside the app. The app does not read and does not write the clipboard of the system. |
| A memory limit | 1 GB for the interpreter and the module. |
ztk prints one line with the address and the word sandbox before the window opens. The module is not kept: each run downloads it again.
The sandbox does not limit what the app draws in its own windows. An app from a URL can show a window that looks like one of another program, so read the address before you type a password into it. A module can keep the processor busy: close the window of an app that does not answer.
Test an app
A Tcl script can run a module with ztk::wasm::run FILE, for a test or for a window with a part in Tcl. ztk::wasm::widget ID gives the path of the widget that the app named with its id option, and ztk::wasm::item CANVAS ID gives a canvas item. The script reads the widgets and sends events to them with ztk::inject:
ztk::wasm::run hello.wasm
update
[ztk::wasm::widget name] insert end Tk
[ztk::wasm::widget greet] invoke
puts [[ztk::wasm::widget msg] cget -text]
exit
ztk --headless check.tcl
The run needs no display. The binding repositories test each example this way: tests/lib.tcl has helpers for clicks, drags, and typed text.
From a module to one program file
ztk bundle makes one app from a main script and its files (An app in one file). The main script of a module app is one line, which loads the module next to it:
# main.tcl
ztk::wasm::run [file join [file dirname [info script]] hello.wasm]
ztk bundle -o hello main.tcl hello.wasm
ztk bundle -o hello.exe --target x86_64-windows main.tcl hello.wasm
ztk bundle -o Hello.app --name Hello --icon icon.png main.tcl hello.wasm
The first line makes one program file for this computer, the second one for Windows, and the third a macOS app folder. The program file has the ztk runtime and the module, and the user needs no ztk and no toolchain. On arm64 macOS the hello app in Go is one file of 32,624,070 bytes.
How it works
The Tk API is a WebAssembly interface: an import module with the name tk. A module calls typed functions, and no Tcl text crosses the boundary. One file, tk.wit, defines the 91 functions, and a script makes the import layer of each language from it.
| Part | In the interface |
|---|---|
| A widget, a canvas item, a variable, a font, a timer | A handle, one i32 that the host gives. The module has no path name. |
| A widget class | One function for each class, with the parent: tk.button(parent), tk.entry(parent), tk.canvas(parent). |
| An option | A typed call with the option as an enum: tk.set_str, tk.set_int, tk.set_f64, tk.set_bool, tk.set_color. A number goes as a number, and a color as 0xRRGGBBAA. |
| A callback | tk.on_command(widget, id), tk.bind(widget, event, id), and tk.after(ms, id). The host calls the export app_event(id), and the module reads the event with tk.event_x(), tk.event_y(), and tk.event_key(). |
| The geometry | tk.pack, tk.grid, and tk.place, with numbers and enums. |
| The canvas | tk.canvas_rect(canvas, x1, y1, x2, y2) gives an item handle, and tk.item_move, tk.item_coords_set, and tk.item_set_color change it. |
| Each other Tk command | tk.call(words) with a list of words. A word needs no quoting. |
The interface file is src/library/wasm/tk.wit of the ztk repository, and the ABI has the core signature of each import and the exports of a module. tools/wasm-tk-gen.py writes the import layer of each language from that file, so a binding for one more language is that generated layer and a small library over it.
What a module can reach
A module has its linear memory and the imports of tk, which are the Tk commands of the interpreter of the window. The module gets no file, socket, or process of its own. The compute limit and the memory limit of the interpreter count the work of the module.
Limits
- The interface has the widgets and the functions that the example apps use, and a set of common ones. It does not have images, menus, the ttk widgets, text tags, or dialogs yet.
tk.callreaches them. - A typed call for each option is more calls than one script: the spreadsheet makes 406 calls at its start.
- ztk has no fixed API for the interface yet, so it can change.