ui

Native windows, widgets, menus, dialogs and themes.

v2.0.0Desktopbundledimport "ui";
Overview Installation Documentation Examples

Overview

A small, beautiful desktop toolkit. One theme restyles the whole window, widgets place themselves in a column or a row, and everything is owner-drawn so it looks the same on every machine. No dependencies: hphp build links the whole Win32 layer into one exe.

stdlib — embedded Win32 native themed auto-layout chainable

Hello GUI

import "ui";

$app = new App("My App");
$app->heading("Hello, world");
$app->sub("This is HolyPHP UI 2.0.");
$app->button("Click me", "primary", function() use ($app) {
    $app->msg("It works.");
});
$app->run();

No coordinates. The heading, the subtitle and the button stack themselves, and every one of them follows the same theme.

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install ui

This adds the library to hphp.yaml, installs it into .hphp/packages/ui/ and pins the exact version in hphp.lock:

require:
  ui: "^2.0"

Use it

import "ui";

ui is bundled with the compiler, so import "ui"; also works in a single file without installing anything, and hphp install works offline.

Outside a project

hphp install ui          # for your user, shared by all scripts
hphp create myapp                 # or start a project, then: hphp install ui
Packageui
Version2.0.0 (follows the compiler)
Entry fileui.hphp
Sourcepackages/lib/ui ↗

Documentation

Hello GUI

import "ui";

$app = new App("My App");
$app->heading("Hello, world");
$app->sub("This is HolyPHP UI 2.0.");
$app->button("Click me", "primary", function() use ($app) {
    $app->msg("It works.");
});
$app->run();

No coordinates. The heading, the subtitle and the button stack themselves, and every one of them follows the same theme.

Themes

A theme is a universal style: colours, corner radius, type size, row height. Change it at any time — every widget follows immediately.

void theme(string|map $which, map $over = null)
$app->theme("dark");        // dark (default)
$app->theme("light");
$app->theme("midnight");
$app->theme("ocean");
$app->theme("forest");
$app->theme("rose");
$app->theme("mono");

// override single keys, on top of a preset …
$app->theme("dark", ["accent" => 0xFF5722]);

// … or roll a whole theme from scratch
$app->theme(["bg" => 0x101014, "surface" => 0x171A21,
               "text" => 0xE8EAF0, "accent" => 0x7C5CFF,
               "dark" => 1]);

Theme keys

KeyMeaning
bg surface elevatedwindow, card and raised backgrounds
text mutedbody and secondary text
accent onAccentprimary colour and the text on top of it
borderoutlines and dividers
radiuscorner radius, pixels
font titlebody and heading size, points
rowlist and popup row height
dark1 for dark themes (drives native chrome)

Universal style shortcuts

App pad(int $px) // window padding + widget padding App gap(int $px) // space between widgets App radius(int $px) // corner radius everywhere App font(int $pt, bool $bold = false) App style(string $role) // default button role
$app->theme("midnight")->pad(28)->gap(12)->radius(12)->font(11);

Roles

Six ready-made button styles. Pass one to a factory, or make it the default for everything that follows.

$app->button("Save");                 // subtle (the default)
$app->button("Save", "primary");       // filled with the accent colour
$app->button("Delete", "danger");
$app->button("Done", "success");
$app->button("More", "ghost");         // no fill until hovered
$app->link("Read the docs");           // a text link

$app->style("primary");                 // every button from here on

Layout

The window stacks its children top to bottom. To put things side by side, put them inside a row() — a row lays its children out across and wraps when it runs out of room. Every container grows to fit what you put inside it.

$cols = $app->row();
$left  = $cols->column(400);
$right = $cols->column(400);

$form = $left->card(400);          // rounded surface
$form->label("Email");
$form->input("you@example.com");
$form->checkbox("Remember me", true);
$form->button("Sign in", "primary", $handler);

$sec = $right->section("Preferences", 400);   // captioned outline
$sec->slider(60);
$sec->progress(35);
ContainerWhat it is
column($w = 0)vertical box
row($w = 0)horizontal box, wraps
card($w = 0, $h = 0)rounded surface, auto height
section($caption, $w = 0, $h = 0)captioned outline
panel($x, $y, $w, $h)free-form, absolute

Absolute placement still works and never disturbs the flow:

$app->button("Reset", "ghost")->move(20, 20, 90, 0);

Widgets

FactoryWidgetExtras
heading($text) / sub($text) / label($text)Label—
button($text, $role, $onClick)ButtononClick()
link($text, $onClick)LinkonClick()
input($text = "")Inputcontent() / setValue() / onChange()
checkbox($text, $on = false)Checkboxchecked() / setChecked() / toggle()
list($items) / combo($items)ListBox / ComboBoxadd / addAll / items / count / clear / remove / selected / select / selectedText
progress($pct = 0)ProgressBarprogress($pct) / percent()
slider($value = 0)Slidervalue($v) / current() / range($lo,$hi) / onChange($v)
divider()Divider—

Every widget shares the same methods, and they chain

UIObject text(string $t) string content() UIObject setValue(string $v) UIObject show() / hide() bool enabled() / disable() UIObject move(int $x, int $y, int $w = 0, int $h = 0) UIObject size(int $w, int $h) UIObject focus() array rect() // [x, y, w, h] as painted, in window coordinates UIObject font(int $pt, bool $bold = false) UIObject color(int $rgb) / bg(int $rgb) / accent(int $rgb) UIObject radius(int $px) UIObject style(string $role) UIObject onClick(fn) / onChange(fn) / onKey(fn)
$app->button("Danger", "danger")->radius(20)->accent(0xE040FB)->font(12, true);

Window

void title(string $t) / size(int $w, int $h) / pos(int $x, int $y) bool alive() void run() // blocking event loop void tick(int $ms = 15) // pump events once, keep your own loop void close() / quit() void every(int $ms, fn) void onClose(fn) // return false to veto void onKey(fn) // fn(int $vk, int $char)

Scrolling

A window whose content is taller than its client area scrolls with the mouse wheel, PageUp/PageDown and Ctrl+Home/End. A script can also drive it:

array scroll() // [offset, contentHeight, viewportHeight] App scrollBy(int $dy) / scrollTo(int $y) int scrollOffset() / contentHeight()
Tip: run() blocks like a normal desktop app (best with hphp build). tick() returns every ~15 ms so your script keeps control and console output stays alive (best with hphp run).

Menus

$file = $app->menu("File");
$file->item("Open", function() use ($app) {
    $f = $app->openFile("Text|*.txt;HolyPHP|*.hphp");
    if ($f != "") { $app->msg("Opened " . $f); }
});
$file->separator();
$file->item("Quit", function() use ($app) { $app->close(); });

Dialogs & system

void msg(string $text, string $title = "HolyPHP") void warn(string $text, string $title = "Warning") void error(string $text, string $title = "Error") bool ask(string $text, string $title = "Question") string openFile(string $patterns = "All files|*.*") // "" = cancelled string saveFile(string $patterns) string folder() int color(int $initial = 0x4C7DFF) // 0xRRGGBB, null = cancelled void clip(string $text) string paste()

Timers

$ticks = 0;
$app->every(400, function() use (&$ticks, $bar, $label) {
    $ticks = $ticks + 1;              // by-ref capture
    $pct = ($ticks * 5) % 100;
    $bar->progress($pct);
    $label->text("{$pct}% complete");   // repaints one widget
});

Colours

Colours are plain 0xRRGGBB integers everywhere.

$app->button("Paint", "", 20, 20)->bg(0x1E88E5)->color(0xFFFFFF);

Two helpers build them: ui_rgb($r, $g, $b) packs channels and ui_channel($rgb, $i) reads one back.

How it works

The Win32 layer lives in the runtime (hphp_ui.c): a handle table, a window proc that routes events to HolyPHP closures, and guarded callback invocation — an exception inside a handler prints and keeps the app alive instead of unwinding through C. Every control is owner-drawn from one paint routine, so the theme is the single source of truth. Callbacks run on the GUI thread; long work belongs in a timer.

Tip: onClick() / onChange() take a closure directly — $btn->onClick(function() { ... }) — and capture anything with use.

Examples

5 complete programs. Every one is type-checked with the compiler before the site is published; copy one into src/ of a project (hphp create) and run it.

01Hello, window

The smallest complete desktop app. new App() opens a themed window, and widgets such as heading(), sub() and button() stack themselves top to bottom - no coordinates needed. A button takes a role (primary, danger, ghost, ...) and a closure to run when it is clicked.

01-hello-window.hphp
<?php
import "ui";

// A 480 x 300 window with the default dark theme.
$app = new App("Hello", 480, 300);

// Text: a big heading and a muted subtitle.
$app->heading("Hello, world");
$app->sub("This window was written in HolyPHP.");

// A button that opens a message box when clicked.
$app->button("Say hello", "primary", function() use ($app) {
    $app->msg("Hello from HolyPHP!", "Greetings");
});

// A second button that asks before closing the window.
$app->button("Quit", "ghost", function() use ($app) {
    if ($app->ask("Really quit?")) {
        $app->close();
    }
});

// Hand control to the window until it is closed.
$app->run();
Try it
hphp run 01-hello-window.hphp

02A counter with buttons

State in a GUI program is just a variable that the click handlers share. The handlers capture it by reference (use (&$count)) so every button sees the same number, and text() updates the label. Buttons sit side by side inside a row(), and the minus button is disabled at zero.

02-counter.hphp
<?php
import "ui";

$app = new App("Counter", 360, 260);
$app->theme("ocean");

$count = 0;

// The number itself, shown as a heading.
$app->sub("Clicks so far");
$display = $app->heading("0");

// Three buttons next to each other.
$buttons = $app->row();
$minus = $buttons->button("-1");
$plus = $buttons->button("+1", "primary");
$reset = $buttons->button("Reset", "ghost");

// Redraw the label and enable or disable "-1" to match the count.
$refresh = function() use (&$count, $display, $minus) {
    $display->text("$count");
    $minus->enable($count > 0);
};
$refresh();

// Each handler changes the shared count, then refreshes the view.
$plus->onClick(function() use (&$count, $refresh) {
    $count = $count + 1;
    $refresh();
});
$minus->onClick(function() use (&$count, $refresh) {
    $count = $count - 1;
    $refresh();
});
$reset->onClick(function() use (&$count, $refresh) {
    $count = 0;
    $refresh();
});

$app->run();
Try it
hphp run 02-counter.hphp

03A sign-up form with validation

A small form inside a card(): text inputs, a combo() drop-down and a checkbox(). Clicking "Create account" reads every field with content(), selectedText() and checked(), validates them, and shows either the first problem in a red label or a summary in a message box.

03-signup-form.hphp
<?php
import "ui";

$app = new App("Create account", 460, 560);
$app->theme("light");
$app->heading("Create your account");

// The form fields, inside a rounded card.
$form = $app->card(400);
$form->label("Name");
$name = $form->input("");
$form->label("Email");
$email = $form->input("");
$form->label("Plan");
$plan = $form->combo(["Free", "Pro", "Team"]);
$plan->select(0);
$terms = $form->checkbox("I accept the terms");

// Where validation errors appear (empty until needed).
$errors = $form->label("")->color(0xD32F2F);

// Read the fields, find the first problem, then report.
$submit = function() use ($app, $name, $email, $plan, $terms, $errors) {
    $problem = "";
    if (trim($name->content()) == "") {
        $problem = "Please enter your name.";
    } elseif (!str_contains($email->content(), "@")) {
        $problem = "That email address looks wrong.";
    } elseif (!$terms->checked()) {
        $problem = "You need to accept the terms.";
    }

    $errors->text($problem);
    if ($problem != "") {
        return;
    }
    $app->msg("Welcome, " . trim($name->content()) . "!\n"
        . "Plan: " . $plan->selectedText() . "\n"
        . "We sent a confirmation to " . $email->content() . ".", "Account created");
};

$form->button("Create account", "primary", $submit);

// Pressing Enter in the email field submits too (13 = the Enter key).
$email->onKey(function($key, $char, $mods) use ($submit) {
    if ($key == 13) {
        $submit();
    }
});

$app->run();
Try it
hphp run 03-signup-form.hphp

04A to-do list with a menu

A list() box holds the tasks. Type a task and press Enter or click "Add"; select one and click "Done" to remove it. A menu bar adds File > Save, which writes the tasks to a file picked with saveFile().

04-todo-list.hphp
<?php
import "ui";

$app = new App("To-do", 420, 480);
$app->heading("Things to do");

// Input and "Add" button side by side.
$entry = $app->row();
$newTask = $entry->input("");
$add = $entry->button("Add", "primary");

// The list, the "Done" button and a status line.
$tasks = $app->list(["Water the plants", "Write the report"]);
$done = $app->button("Done", "success");
$status = $app->sub("");

$updateStatus = function() use ($tasks, $status) {
    $status->text($tasks->count() . " task(s) left");
};
$updateStatus();

// Add the typed task, then clear the input for the next one.
$addTask = function() use ($newTask, $tasks, $updateStatus) {
    $text = trim($newTask->content());
    if ($text == "") {
        return;
    }
    $tasks->add($text);
    $newTask->text("");
    $updateStatus();
};
$add->onClick($addTask);
$newTask->onKey(function($key, $char, $mods) use ($addTask) {
    if ($key == 13) {
        $addTask();
    }
});

// Remove the selected task (selected() is -1 when nothing is selected).
$done->onClick(function() use ($tasks, $updateStatus) {
    $index = $tasks->selected();
    if ($index >= 0) {
        $tasks->remove($index);
        $updateStatus();
    }
});

// File menu: save the list to disk, or quit.
$file = $app->menu("File");
$file->item("Save...", function() use ($app, $tasks) {
    $path = $app->saveFile("Text files|*.txt");
    if ($path != "") {
        file_put_contents($path, implode("\n", $tasks->items()) . "\n");
        $app->msg("Saved " . $tasks->count() . " tasks to " . $path);
    }
});
$file->item("Quit", function() use ($app) {
    $app->close();
});

$app->run();
Try it
hphp run 04-todo-list.hphp

05A focus timer with themes

A Pomodoro timer: a slider() sets the minutes, every() ticks once a second, a progress() bar fills up, and a combo() of ui_theme_names() restyles the whole window live with theme().

05-focus-timer.hphp
<?php
import "ui";

$app = new App("Focus timer", 420, 420);

// Settings: session length (1-60 minutes) and theme.
$settings = $app->section("Settings", 360);
$length = $settings->slider(25);
$length->range(1, 60);
$themes = $settings->combo(ui_theme_names());

// The clock: time left, a progress bar and the start button.
$clock = $app->heading("25:00");
$bar = $app->progress(0);
$startStop = $app->button("Start", "primary");

// Timer state, shared by the handlers below.
$total = 25 * 60;
$left = $total;
$running = false;

// Show the remaining time as mm:ss and fill the bar as time passes.
$show = function() use (&$total, &$left, $clock, $bar) {
    $clock->text(sprintf("%02d:%02d", intdiv($left, 60), $left % 60));
    $bar->progress(intdiv(($total - $left) * 100, $total));
};

// Moving the slider resets the timer to the new length.
$length->onChange(function($minutes) use (&$total, &$left, $show) {
    $total = $minutes * 60;
    $left = $total;
    $show();
});

// Picking a theme restyles every widget at once.
$themes->onChange(function($index, $name) use ($app) {
    $app->theme($name);
});

// Start / pause toggles one flag; the timer below checks it.
$startStop->onClick(function() use (&$running, $startStop) {
    $running = !$running;
    $startStop->text($running ? "Pause" : "Start");
});

// Once a second: count down while running; at zero, announce and reset.
$app->every(1000, function() use ($app, &$running, &$left, &$total, $startStop, $show) {
    if (!$running) {
        return;
    }
    $left = $left - 1;
    if ($left == 0) {
        $running = false;
        $startStop->text("Start");
        $app->msg("Time is up - take a break!");
        $left = $total;
    }
    $show();
});

$app->run();
Try it
hphp run 05-focus-timer.hphp