Skip to content

tinyweb for Java

tinyweb’s Java implementation is a library of its own: a Java program can use it to draw on a web page, add buttons, labels and sliders to it, play sounds and answer the reader, with no Pyking anywhere. It is the file Pyking copies beside a program compiled for java21, renamed Tinyweb.java.

Download tinyweb-java.zip: Tinyweb.java, the example below, and the samples in tinyweb_assets/.

Running a program

The program serves its own page: web_init starts the server and prints its address, and once the program’s own code has finished it goes on serving the page and calling the functions it handed over until it is stopped (Ctrl-C). Open the address in a browser.

Terminal window
javac Tinyweb.java Example.java
java Example

The page asks for a sample beside where the program runs first, then in tinyweb_assets/ there.

An example

// A canvas, two circles, two samples and buttons that play them, written
// in Java against Tinyweb.java. Build it with
// javac Tinyweb.java Example.java
// then run `java Example` and open the address it prints.
public final class Example {
private static int presses = 0;
public static void main(String[] args) {
Tinyweb.web_init(0);
int kick = Tinyweb.load_sample("kick1.wav");
int snare = Tinyweb.load_sample("snare1.wav");
int canvas = Tinyweb.canvas(400, 200);
Tinyweb.draw_circle(canvas, 100, 50, 30, "#ff0000");
Tinyweb.draw_circle(canvas, 100, 50, 20, "#000000");
Tinyweb.make_button("Play kick", () -> Tinyweb.play_sample(kick, 0.0, 1.0, 1.0));
Tinyweb.make_button("Play snare", () -> {
presses += 1;
System.out.println("snare, press " + presses);
Tinyweb.play_sample(snare, 0.0, 0.5, 1.0);
});
Tinyweb.make_button("Does nothing", () -> { });
System.out.println("built the page");
}
}

Functions

Every function but web_init needs web_init to have been called first, or PYKING_TINYWEB_LOG to be set (below); otherwise it says so and the program ends with status 1.

web_init

public static void web_init(int port)

Serves the program’s page on port and prints its address, tinyweb: http://127.0.0.1:N/; port 0 picks any free port. Call it before anything else. With PYKING_TINYWEB_LOG set it does nothing.

canvas

public static int canvas(int width, int height)

A new canvas, width by height pixels, placed below what the page already shows. Answers the number that names it.

fill_canvas

public static void fill_canvas(int c, String color)

Fills the whole canvas c with color, a CSS color such as "#ff0000" or "red".

draw_circle

public static void draw_circle(int c, int x, int y, int radius, String color)

A filled circle on the canvas c, centred at (x, y).

draw_rect

public static void draw_rect(int c, int x, int y, int width, int height, String color)

A filled rectangle on the canvas c, with its top left corner at (x, y).

draw_line

public static void draw_line(int c, int x1, int y1, int x2, int y2, String color, int width)

A straight line on the canvas c, from (x1, y1) to (x2, y2), width pixels wide.

draw_text

public static void draw_text(int c, int x, int y, String words, String color, int size)

words written on the canvas c, with the top left corner of the text at (x, y), size pixels high.

make_button

public static int make_button(String title, Runnable on_click)

A button showing title, placed below what the page already shows, which calls on_click each time it is pressed. Answers the number that names it.

label

public static int label(String text)

A line of text, placed below what the page already shows. Answers the number that names it to set_label.

set_label

public static void set_label(int id, String text)

Replaces the text of the label id with text.

make_slider

public static int make_slider(int low, int high, int value, Consumer<Integer> on_change)

A slider from low to high, starting at value, placed below what the page already shows, which calls on_change with each new value it is moved to. Answers the number that names it.

apply_style

public static void apply_style(int id, String kind, String property, String value)

Changes the page’s look. With kind “theme”, value names a theme: “light” (the default), “dark”, “plain”, “paper” or “retro”. With kind “page”, “button”, “label”, “slider” or “canvas”, property of every element of that kind becomes value; with kind “element”, only the element id’s. property is one of background, color, border, radius, font, size, padding, gap, accent and width, and value is CSS, such as “#336699” or “12px”. id is 0 except for an element.

load_sample

public static int load_sample(String name)

Starts loading the sound file name and answers a number naming it to play_sample. The name is looked up beside where the program runs first, and then among the samples tinyweb ships in tinyweb_assets/: kick1.wav, snare1.wav, hihat1.wav and piano_c1.wav.

play_sample

public static void play_sample(int sample, double at, double volume, double rate)

Plays the sample sample: at the time at on the page’s clock, or now if that has passed; volume times as loud, and rate times as fast, which raises its pitch as much.

time

public static double time()

The page’s clock, in seconds, as the page last reported it: inside an on_frame callback, the time the frame is for. It is the audio clock once sound has started, so a time read here is a time play_sample can be given.

on_frame

public static void on_frame(Consumer<Double> draw)

Calls draw before each frame the page shows, with the time the frame is for.

on_mouse

public static void on_mouse(int c, BiConsumer<Integer, Integer> click)

Calls click with the position, in pixels from the top left corner, of every click on the canvas c.

on_key

public static void on_key(Consumer<String> pressed)

Calls pressed with the name of every key pressed while the page has the focus: a letter or digit as itself, and otherwise the browser’s name for it, such as “ArrowLeft”, “Enter” or ” ”.

Without a page

Two environment variables, each a file path, run a program with no page at all, which is how it is tested: with PYKING_TINYWEB_LOG set, every command the program would send its page is appended to that file as one line, and once the program’s own code has finished the events PYKING_TINYWEB_EVENTS lists — click ID, slide ID VALUE, frame T, mouse ID X Y, key NAME, one per line — are delivered as if a reader had caused them.

Terminal window
PYKING_TINYWEB_LOG=page.log PYKING_TINYWEB_EVENTS=clicks.txt java Example

What Pyking generates

Pyking’s own tinyweb tests, compiled for java21. Each comes with the libraries it needs as Pyking writes them — tinyweb’s implementation under its own name, and the module Pyking compiles from tinyweb’s Pyking half — and is built and run with:

Terminal window
javac TinywebExternal.java Tinyweb.java Program.java
java Program

lib_tinyweb_frames

# Animation kept in time with sound: each frame is drawn for the time
# the page gives it, and each beat is scheduled half a second ahead on
# the same clock, so it sounds where the picture says it is. The
# .events file delivers four frames.
import tinyweb as tw
tw.web_init(0)
c = tw.canvas(200, 100)
kick = tw.load_sample("kick1.wav")
beat = 0.5
var next_beat = 0.0
def draw(t: Float):
tw.clear(c, "#111111")
tw.circle(c, int(t * 100.0), 50, 10, "#ffcc00")
if t >= next_beat:
print("beat scheduled at " ++ string(next_beat + beat) ++ ", drawn at " ++ string(t))
tw.play(kick, at = next_beat + beat)
next_beat := next_beat + beat
tw.on_frame(draw)
print(tw.time())

lib_tinyweb_frames.zip

Program.java, as Pyking generates it
// Generated from lib_tinyweb_frames.pyk by the Pyking compiler. Do not edit.
// Target: java21. Compile with: javac --release 21 Program.java
// then run with: java Program
public final class Program {
// A Float written the way Pyking writes one, which is not the way
// Java writes a double.
private static String pykFloatStr(double x) {
if (Double.isNaN(x)) return "nan";
if (x == Double.POSITIVE_INFINITY) return "inf";
if (x == Double.NEGATIVE_INFINITY) return "-inf";
String sign = (x < 0.0 || (x == 0.0 && 1.0 / x < 0.0)) ? "-" : "";
double a = Math.abs(x);
if (a == 0.0) return sign + "0.0";
String s = "";
for (int p = 0; p <= 16; p++) {
s = String.format(java.util.Locale.ROOT, "%." + p + "e", a);
if (Double.parseDouble(s) == a) break;
}
int at = s.indexOf('e');
String digits = s.substring(0, at).replace(".", "");
int decpt = Integer.parseInt(s.substring(at + 1)) + 1;
int n = digits.length();
while (n > 1 && digits.charAt(n - 1) == '0') n--;
digits = digits.substring(0, n);
if (decpt <= -4 || decpt > 16) {
String mantissa =
n == 1 ? digits : digits.charAt(0) + "." + digits.substring(1);
return sign + mantissa + "e" + (decpt - 1);
}
StringBuilder out = new StringBuilder(sign);
if (decpt <= 0) {
out.append("0.");
for (int i = 0; i < -decpt; i++) out.append('0');
return out.append(digits).toString();
}
if (decpt >= n) {
out.append(digits);
for (int i = 0; i < decpt - n; i++) out.append('0');
return out.append(".0").toString();
}
return out.append(digits, 0, decpt).append('.')
.append(digits.substring(decpt)).toString();
}
private static int pykTruncate(double x) {
if (Double.isNaN(x) || x <= -2147483649.0 || x >= 2147483648.0) {
return 0;
}
return (int) x;
}
// What the top level binds, where every method can read it; the
// top level in `main` below is what fills each of them in.
private static int c;
private static int kick;
private static double beat;
private static double next_beat;
private static void draw(final double t) {
Tinyweb.clear(c, "#111111");
Tinyweb.circle(c, pykTruncate(t * 100.0), 50, 10, "#ffcc00");
if (t >= next_beat) {
System.out.println("beat scheduled at " + pykFloatStr(next_beat + beat) + ", drawn at " + pykFloatStr(t));
Tinyweb.play(kick, next_beat + beat, Tinyweb.play__default__volume(), Tinyweb.play__default__rate());
next_beat = next_beat + beat;
}
}
public static void main(String[] args) {
// Every module of the program, in the order they must run.
Tinyweb.init();
TinywebExternal.web_init(0);
c = TinywebExternal.canvas(200, 100);
kick = TinywebExternal.load_sample("kick1.wav");
beat = 0.5;
next_beat = 0.0;
TinywebExternal.on_frame((p$1) -> draw(p$1));
System.out.println(pykFloatStr(TinywebExternal.time()));
}
}

lib_tinyweb_input

# The mouse, the keyboard and a slider, each reported on a label, and
# the other drawing functions. The .events file clicks the canvas,
# presses two keys -- the second Enter -- and moves the slider.
import tinyweb as tw
tw.web_init(0)
c = tw.canvas(300, 200)
tw.rect(c, 0, 0, 300, 200, "#eeeeee")
tw.line(c, 0, 0, 300, 200)
tw.line(c, 0, 200, 300, 0, "red", width = 3)
tw.text(c, 10, 10, "click \"me\"", size = 20)
status = tw.label("nothing yet")
def clicked(x: Int, y: Int):
tw.set_label(status, "clicked at " ++ string(x) ++ ", " ++ string(y))
tw.circle(c, x, y, 5, "blue")
def pressed(key: String):
print("key [" ++ key ++ "]")
if key == "Enter":
tw.play_file("snare1.wav")
def moved(value: Int):
tw.set_label(status, "slider at " ++ string(value))
tw.on_mouse(c, clicked)
tw.on_key(pressed)
tw.slider(0, 10, 5, on_change = moved)
tw.slider(1, 3, 2)

lib_tinyweb_input.zip

Program.java, as Pyking generates it
// Generated from lib_tinyweb_input.pyk by the Pyking compiler. Do not edit.
// Target: java21. Compile with: javac --release 21 Program.java
// then run with: java Program
public final class Program {
// What the top level binds, where every method can read it; the
// top level in `main` below is what fills each of them in.
private static int c;
private static int status;
private static void clicked(final int x, final int y) {
TinywebExternal.set_label(status, "clicked at " + String.valueOf(x) + ", " + String.valueOf(y));
Tinyweb.circle(c, x, y, 5, "blue");
}
private static void pressed(final String key) {
System.out.println("key [" + key + "]");
if (key.equals("Enter")) {
Tinyweb.play_file("snare1.wav");
}
}
private static void moved(final int value) {
TinywebExternal.set_label(status, "slider at " + String.valueOf(value));
}
public static void main(String[] args) {
// Every module of the program, in the order they must run.
Tinyweb.init();
TinywebExternal.web_init(0);
c = TinywebExternal.canvas(300, 200);
Tinyweb.rect(c, 0, 0, 300, 200, "#eeeeee");
Tinyweb.line(c, 0, 0, 300, 200, Tinyweb.line__default__color(), Tinyweb.line__default__width());
Tinyweb.line(c, 0, 200, 300, 0, "red", 3);
Tinyweb.text(c, 10, 10, "click \"me\"", Tinyweb.text__default__color(), 20);
status = TinywebExternal.label("nothing yet");
TinywebExternal.on_mouse(c, (p$1, p$2) -> clicked(p$1, p$2));
TinywebExternal.on_key((p$1) -> pressed(p$1));
Tinyweb.slider(0, 10, 5, (p$1) -> moved(p$1));
Tinyweb.slider(1, 3, 2, Tinyweb.slider__default__on_change());
}
}

lib_tinyweb_sound_graphics1

# A canvas, two circles, two samples and buttons that play them: the
# first tinyweb program.
import tinyweb as tw
tw.web_init(0)
kick = tw.load_sample("kick1.wav")
snare = tw.load_sample("snare1.wav")
canvas = tw.canvas(400, 200)
tw.circle(canvas, 100, 50, 30, "#ff0000") # canvas, x, y, radius, color
tw.circle(canvas, 100, 50, 20) # the color defaults to "#000000"
var presses = 0
def play_kick():
tw.play(kick)
def play_sound():
presses := presses + 1
print("snare, press " ++ string(presses))
tw.play(snare, volume = 0.5)
tw.button("Play kick", on_click = play_kick)
tw.button("Play snare", on_click = play_sound)
tw.button("Does nothing") # on_click is optional
print("built the page")

lib_tinyweb_sound_graphics1.zip

Program.java, as Pyking generates it
// Generated from lib_tinyweb_sound_graphics1.pyk by the Pyking compiler. Do not edit.
// Target: java21. Compile with: javac --release 21 Program.java
// then run with: java Program
public final class Program {
// What the top level binds, where every method can read it; the
// top level in `main` below is what fills each of them in.
private static int kick;
private static int snare;
private static int canvas;
private static int presses;
private static void play_kick() {
Tinyweb.play(kick, Tinyweb.play__default__at(), Tinyweb.play__default__volume(), Tinyweb.play__default__rate());
}
private static void play_sound() {
presses = presses + 1;
System.out.println("snare, press " + String.valueOf(presses));
Tinyweb.play(snare, Tinyweb.play__default__at(), 0.5, Tinyweb.play__default__rate());
}
public static void main(String[] args) {
// Every module of the program, in the order they must run.
Tinyweb.init();
TinywebExternal.web_init(0);
kick = TinywebExternal.load_sample("kick1.wav");
snare = TinywebExternal.load_sample("snare1.wav");
canvas = TinywebExternal.canvas(400, 200);
Tinyweb.circle(canvas, 100, 50, 30, "#ff0000");
Tinyweb.circle(canvas, 100, 50, 20, Tinyweb.circle__default__color());
presses = 0;
Tinyweb.button("Play kick", () -> play_kick());
Tinyweb.button("Play snare", () -> play_sound());
Tinyweb.button("Does nothing", Tinyweb.button__default__on_click());
System.out.println("built the page");
}
}

lib_tinyweb_style

# The page's look: a theme, the style of every element of a kind, and
# the style of one element. The .events file presses the button, which
# changes the theme and one label while the page is showing.
import tinyweb as tw
tw.web_init(0)
tw.theme("paper")
tw.theme("no such theme")
tw.page_style(background = "#fdf6e3", color = "#586e75", font = "serif", size = 18, padding = 12, gap = 16)
tw.button_style(background = "#268bd2", color = "white", border = "none", radius = 14, font = "monospace", size = 16, padding = 8)
tw.label_style(background = "lightyellow", color = "#333333", border = "1px solid gold", radius = 4, font = "sans-serif", size = 14, padding = 6)
tw.slider_style(accent = "crimson", width = 240, color = "crimson", font = "monospace", size = 20)
tw.canvas_style(border = "3px solid teal", radius = 10)
title = tw.label("Styled")
tw.set_style(title, background = "navy", color = "white", border = "2px dashed orange", radius = 0, font = "Georgia", size = 28, padding = 10, width = 300)
level = tw.slider(0, 10, 4)
tw.set_colors(level, color = "seagreen")
c = tw.canvas(120, 60)
tw.set_style(c, border = "1px solid black")
def pressed():
tw.theme("retro")
tw.set_colors(title, background = "black")
print("now retro")
ok = tw.button("Retro", on_click = pressed)
tw.set_colors(ok, color = "black", background = "gold")

lib_tinyweb_style.zip

Program.java, as Pyking generates it
// Generated from lib_tinyweb_style.pyk by the Pyking compiler. Do not edit.
// Target: java21. Compile with: javac --release 21 Program.java
// then run with: java Program
public final class Program {
// What the top level binds, where every method can read it; the
// top level in `main` below is what fills each of them in.
private static int title;
private static int level;
private static int c;
private static int ok;
private static void pressed() {
Tinyweb.theme("retro");
Tinyweb.set_colors(title, Tinyweb.set_colors__default__color(), "black");
System.out.println("now retro");
}
public static void main(String[] args) {
// Every module of the program, in the order they must run.
Tinyweb.init();
TinywebExternal.web_init(0);
Tinyweb.theme("paper");
Tinyweb.theme("no such theme");
Tinyweb.page_style("#fdf6e3", "#586e75", "serif", 18, 12, 16);
Tinyweb.button_style("#268bd2", "white", "none", 14, "monospace", 16, 8);
Tinyweb.label_style("lightyellow", "#333333", "1px solid gold", 4, "sans-serif", 14, 6);
Tinyweb.slider_style("crimson", 240, "crimson", "monospace", 20);
Tinyweb.canvas_style("3px solid teal", 10);
title = TinywebExternal.label("Styled");
Tinyweb.set_style(title, "navy", "white", "2px dashed orange", 0, "Georgia", 28, 10, Tinyweb.set_style__default__accent(), 300);
level = Tinyweb.slider(0, 10, 4, Tinyweb.slider__default__on_change());
Tinyweb.set_colors(level, "seagreen", Tinyweb.set_colors__default__background());
c = TinywebExternal.canvas(120, 60);
Tinyweb.set_style(c, Tinyweb.set_style__default__background(), Tinyweb.set_style__default__color(), "1px solid black", Tinyweb.set_style__default__radius(), Tinyweb.set_style__default__font(), Tinyweb.set_style__default__size(), Tinyweb.set_style__default__padding(), Tinyweb.set_style__default__accent(), Tinyweb.set_style__default__width());
ok = Tinyweb.button("Retro", () -> pressed());
Tinyweb.set_colors(ok, "black", "gold");
}
}