Sfoglia il codice sorgente

Add browser visit history with URL-bar autocomplete

Every page that finishes loading is recorded (URL, title, visit count and
a stamp counter that orders visits across windows and reboots) in a
128-entry BSS table.  Browser windows share /share/bhist, merged on every
write, and it is persisted to /data/BHIST.DAT at most every 3 s.

While the address bar has the focus a dropdown lists up to six entries:
the top sites for an empty bar, otherwise URL prefixes (with or without
the scheme and www.) ranked above URL and title substrings, plus visits
and recency.  Typing at the end completes inline to the next '/' of the
best match, and Enter opens the history URL it stands for.  Up/Down
preview a row, Delete forgets it, Esc closes the list, a click opens it.

The browser no longer fits the floppy lite pack: it is now in the full
pack only, and floppy boots run BROWSER from root.img through the
existing launcher fallback.  browser-host gains --keys for scripted
headless typing.
Johannes Zellner 4 giorni fa
parent
commit
ce76a5ac91
9 ha cambiato i file con 726 aggiunte e 22 eliminazioni
  1. 34 7
      AGENTS.md
  2. 8 4
      Makefile
  3. 3 1
      docs/boot.html
  4. 1 1
      docs/development.html
  5. 5 2
      docs/userland.html
  6. 1 0
      host/host.h
  7. 8 2
      host/main.c
  8. 42 1
      host/window_headless.c
  9. 624 4
      user/apps/browser/browser.c

+ 34 - 7
AGENTS.md

@@ -134,7 +134,10 @@ make clean
   host files/sockets and `fork/exec` for `curl __serve`).  Run
   `./browser-host [--size WxH] [--root DIR] URL|FILE`, or
   `./browser-host --headless --wait 3000 --shot out.ppm URL` to render the
-  compat ladder without a display.  It needs the multilib `lib32-sdl3`,
+  compat ladder without a display; `--keys 'clo{down}{enter}'` types into
+  the headless window (100 ms per key from 300 ms after the first frame;
+  `{enter} {esc} {tab} {bs} {del} {up} {down} {left} {right} {ctrl-l}
+  {wait}`).  It needs the multilib `lib32-sdl3`,
   `lib32-wayland` and `lib32-libxkbcommon`; host sockets replace the NebOS TCP
   stack and the kernel/WM paths are not exercised.
 - QEMU guests default to 512 MB (`QEMU_MEM`, e.g. `make run QEMU_MEM=1G`),
@@ -143,8 +146,10 @@ make clean
   to `cmds_pack_gz.bin`, wrapped by `mkrootfs` with a one-sector `NBROOT1`
   header into `cmds.img` (the 8 MB USB partition image) and `BOOTX64.EFI`.
   The floppy images append `rootfs.bin`, built the same way from
-  `cmds-lite.pack` (everything but `firmware/*`), because the ~1 MB WiFi
-  firmware does not fit a 1.44 MB floppy.  The kernel itself no longer
+  `cmds-lite.pack` (everything but `firmware/*`, `install/kernel.bin` and
+  `bin/browser.app`), because the ~1 MB WiFi firmware and the ~500 KB gzip
+  browser do not fit a 1.44 MB floppy; a floppy boot runs the browser from
+  `BROWSER` on `root.img`.  The kernel itself no longer
   carries the pack; the boot path loads it into RAM and `ramfs_init` takes a
   private copy (`bin/<name>` mounted at `/ramfs`).
 - The WiFi firmware `firmware/iwlwifi-7265D-29.ucode` (Chromebook) and
@@ -1308,7 +1313,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   with mirrored corner indices, notched corners and pixel-art J/Q/K portraits;
   the back is the castle.  The bar's "Cards" button launches
   `/ramfs/bin/solitaire`.
-- **Browser**: the real browser ships in the pack as `bin/browser.app`
+- **Browser**: the real browser ships in the full pack as `bin/browser.app`
+  (not in the floppy lite pack: floppy boots load `BROWSER` from `root.img`)
   (it links ngui, the full image library, inflate, TLS, uhttp and the
   vendored QuickJS engine in `third_party/quickjs/`, but the rootfs is no longer
   constrained by the kernel's low-memory window).
@@ -1410,6 +1416,25 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   so later visits to a bare domain go straight to its canonical scheme/host.
   Remote stylesheets are cached under `/share/bcss-*` for the current boot, so
   a reload or a fresh browser launch does not fetch the same CSS sheets again.
+  **Visit history and URL-bar autocomplete**: every page that finishes
+  loading (not `about:`, URLs under 512 bytes) is recorded in a 128-entry
+  BSS table (`hist_tab`: URL, title, visit count, stamp; the page heap is
+  reset per navigation, so it cannot live there).  The stamp is a counter
+  carried in the file (max + 1 per visit), so it orders visits across
+  windows and reboots without a wall clock; a full table evicts the lowest
+  stamp.  The boot's windows share `/share/bhist`, rewritten on every visit
+  after merging the current file in (max visits, newest title), and
+  `persist_tick()` copies it to `/data/BHIST.DAT` (8.3, plaintext
+  `NBHIST1\n` then `<visits> <stamp> <url>\t<title>\n`); startup reads
+  `/share` first, else `/data`.  While the address bar has the focus a
+  dropdown lists up to six entries: an empty bar shows the top sites, typing
+  ranks prefixes of the URL (also without scheme or `www.`) over URL and
+  then title substrings, plus visits and recency.  Typing at the end also
+  completes inline to the next `/` of the best prefix match, selected, and
+  Enter on that text opens the URL it came from (scheme included).
+  Up/Down preview a row in the bar, Delete forgets the highlighted row,
+  Esc closes the list (and drops the completion), a click opens a row.
+  The in-session back/forward stack (`history[]`, 16 entries) is separate.
   Images are prefetched up to four at a time and only when their measured
   position is within the viewport plus 160 px; deferred images are loaded as
   the page scrolls.  Network work runs in up to `FETCH_WORKERS` (four)
@@ -1924,7 +1949,8 @@ font subsets live in the pack under `fonts/`, the WiFi firmware under
 `firmware/`, the UI icons at `icons/adwaita16.icn` (both packs) and the
 flat kernel at `install/kernel.bin` (full pack only;
 `install self` reads it).  The floppy images use `cmds-lite.pack` (no
-firmware and no `install/kernel.bin`, to stay inside 1.44 MB).
+firmware, `install/kernel.bin` or `bin/browser.app`, to stay inside
+1.44 MB; the browser launcher falls back to `BROWSER` on `root.img`).
 
 `rootfs.bin` is the floppy append (header + lite pack); `rootfs-full.bin`
 is the header + full gzip pack used by `make net-install`; `cmds.img` is the
@@ -2396,8 +2422,9 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    ~204 KiB gzip), the RTL8821A firmware and tables (31,898 + 11,668
    bytes) and `install/kernel.bin` is ~1.88 MiB gzip (~120 KB under the
    cap), inflating to ~3.6 MB, which adds about
-   half a second to the boot; the floppy lite pack is ~930 KiB gzip and
-   deliberately omits the firmware and `install/kernel.bin`.  `libdeflate-gzip -12` is still preferred.  Over
+   half a second to the boot; the floppy lite pack is ~580 KiB gzip and
+   deliberately omits the firmware, `install/kernel.bin` and the browser
+   (`BROWSER` on `root.img` is the floppy copy).  `libdeflate-gzip -12` is still preferred.  Over
    115200 serial a raw `cmds-dev` pack (3.5 MiB) now takes about four
    minutes; use `net-cmds`.
 9. SMP is **ACPI/MADT only**: no Intel MP-table fallback, so a Pentium II SMP

+ 8 - 4
Makefile

@@ -471,7 +471,8 @@ $(call app,chat).elf: $(call app,chat).o $(CHAT_LOGIN) $(UJSON) $(UHTTP_OBJS) $(
 gallery.elf: $(U)/apps/gallery/gallery.o $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
 	$(ULINK)
 
-# browser: the real app ships as bin/browser.app (and BROWSER on root.img)
+# browser: the real app ships as bin/browser.app in the full pack (and
+# BROWSER on root.img, which floppy boots use)
 # because it links ngui, the image library, TLS, uhttp and QuickJS;
 # ucmd_browser.c is the tiny PATH launcher.  Compiled with function sections
 # and linked with --gc-sections: unreachable image, TLS and UI paths are
@@ -778,12 +779,14 @@ $(ICON_FILE): mkicons $(wildcard $(ICON_THEME)/*.svg)
 HELLO_ELF = $(U)/apps/hello/hello.elf
 PACK_FILES = $(foreach a,$(UCMDS),bin/$(a)=$(call app,$(a)).elf) \
              bin/hello=$(HELLO_ELF) \
-             bin/browser.app=browser.elf \
              bin/gallery.app=gallery.elf \
              $(foreach f,$(FONT_FILES),$(f)=$(f)) \
              $(ICON_FILE)=$(ICON_FILE)
 PACK_DEPS = $(UCMD_ELFS) $(HELLO_ELF) browser.elf gallery.elf $(FONT_FILES) \
             $(ICON_FILE) mkpack
+# The browser (~500 KB gzip) is in the full pack only: a floppy boot runs it
+# from BROWSER on root.img, which the bin/browser launcher already tries.
+PACK_BROWSER_FILES = bin/browser.app=browser.elf
 
 # `install self` reads the flat kernel from the full pack.  The lite/floppy
 # pack deliberately omits it (no room on a 1.44 MB disk).
@@ -835,10 +838,11 @@ firmware/rtl8821a.tbl: mkrtwtbl
 	./mkrtwtbl $@
 
 cmds.pack: $(PACK_DEPS) $(WIFI_FW_FILE) kernel.bin
-	./mkpack $@ $(PACK_FILES) $(PACK_INSTALL_FILES) $(PACK_FW_FILES)
+	./mkpack $@ $(PACK_FILES) $(PACK_BROWSER_FILES) $(PACK_INSTALL_FILES) \
+	    $(PACK_FW_FILES)
 
 # The floppy images cannot hold the ~1 MB firmware: they get the same pack
-# without firmware/*.
+# without firmware/* (and without bin/browser.app).
 cmds-lite.pack: $(PACK_DEPS)
 	./mkpack $@ $(PACK_FILES)
 

+ 3 - 1
docs/boot.html

@@ -294,7 +294,9 @@
 			The build produces several images from the same boot sector, kernel
 			and rootfs. The floppy images append the <em>lite</em> pack
 			(<code>rootfs.bin</code> from <code>cmds-lite.pack</code>, everything
-			but <code>firmware/*</code>) so they still fit 1.44 MB. The USB
+			but <code>firmware/*</code>, the cursor bundle, the install kernel and
+			<code>bin/browser.app</code>) so they still fit 1.44 MB; a floppy boot
+			runs the browser from <code>BROWSER</code> on <code>root.img</code>. The USB
 			rootfs partition carries the full pack (about 1.3 MB gzip with the
 			WiFi firmware), which now ends past the first 1.44 MB: a BIOS that
 			boots the stick as a CHS-only floppy can no longer read all of it.

+ 1 - 1
docs/development.html

@@ -238,7 +238,7 @@
 					<tr><td><code>make test-chat</code></td><td>Host tests (ASan/UBSan) for the chat client's JSON parser, cookie jar and the OIDC login page/reply/config parsers.</td></tr>
 					<tr><td><code>make test-chat-e2e</code></td><td>Boots QEMU with an NE2000 on slirp, starts <code>tools/mock_chat.py</code> and drives <code>chat</code> through QMP: native login, send, live poll, read marker, older paging, browse/join, new DM, saved-session resume and sign-out.  <code>CHAT_E2E=--totp|--consent|--passkey|--wrong</code> runs a login variant.</td></tr>
 					<tr><td><code>make compat-serve</code></td><td>Serve the browser compatibility ladder from <code>testdata/browser/compat/</code> on port 8000 for the board or QEMU guest.</td></tr>
-					<tr><td><code>make browser-host</code></td><td>Build the Linux SDL3 development harness (<code>browser-host</code> and its <code>host-curl</code> helper). It implements the ring-3 <code>SYS_*</code> ABI with host files, BSD sockets, <code>fork/exec</code> and an SDL3 window, so pages render and accept input without QEMU. Run <code>./browser-host [--size WxH] [--root DIR] URL|FILE</code>; <code>--headless --wait 3000 --shot out.ppm</code> writes the canvas without a display. Needs the 32-bit SDL3/Wayland libraries (<code>lib32-sdl3</code>, <code>lib32-wayland</code>, <code>lib32-libxkbcommon</code>).</td></tr>
+					<tr><td><code>make browser-host</code></td><td>Build the Linux SDL3 development harness (<code>browser-host</code> and its <code>host-curl</code> helper). It implements the ring-3 <code>SYS_*</code> ABI with host files, BSD sockets, <code>fork/exec</code> and an SDL3 window, so pages render and accept input without QEMU. Run <code>./browser-host [--size WxH] [--root DIR] URL|FILE</code>; <code>--headless --wait 3000 --shot out.ppm</code> writes the canvas without a display, and <code>--keys 'clo{down}{enter}'</code> types into it (one key per 100 ms; <code>{enter}</code>, <code>{esc}</code>, <code>{tab}</code>, <code>{bs}</code>, <code>{del}</code>, arrows, <code>{ctrl-l}</code>, <code>{wait}</code>). Needs the 32-bit SDL3/Wayland libraries (<code>lib32-sdl3</code>, <code>lib32-wayland</code>, <code>lib32-libxkbcommon</code>).</td></tr>
 					<tr><td><code>make fonts</code></td><td>Regenerate the checked-in Arimo/Liberation Mono subsets with <code>pyftsubset</code>.</td></tr>
 				</tbody>
 			</table>

+ 5 - 2
docs/userland.html

@@ -306,7 +306,7 @@
 			The pack is built from the <code>UCMDS</code> list in the Makefile
 			(one <code>user/apps/&lt;name&gt;/</code> directory each) as
 			<code>bin/&lt;name&gt;</code>, plus <code>hello</code> and the real
-			<code>browser.app</code> and <code>gallery.app</code>. It is mounted
+			<code>browser.app</code> (full pack only) and <code>gallery.app</code>. It is mounted
 			read-only at <code>/ramfs</code>; the shell's default PATH points at
 			<code>/ramfs/bin</code>.
 		</p>
@@ -372,7 +372,9 @@
 	<section id="browser">
 		<h2>Browser</h2>
 		<p>
-			The real browser is <code>bin/browser.app</code> in the pack. It links
+			The real browser is <code>bin/browser.app</code> in the full pack; the
+			floppy lite pack omits it and the <code>bin/browser</code> launcher runs
+			<code>BROWSER</code> from <code>root.img</code> instead. It links
 			ngui, the image library, inflate, TLS, uhttp and the vendored QuickJS
 			engine. It opens at 1100×700 (960×640 and 780×540 fallbacks on
 			smaller screens), with a URL bar, history, a status bar, inline
@@ -396,6 +398,7 @@
 			<li><strong>Caps.</strong> 2 MB page body, 832 KB CSS, 6144 DOM nodes, 4608 rules, 16 images. Each image gets an <code>img_estimate()</code>-sized decode arena that is freed after the scaled bitmap is made; navigation calls <code>heap_reset()</code> and unmaps the page heap.</li>
 			<li><strong>Fetching.</strong> Up to four worker processes prefetch images in parallel within the viewport plus 160 px; each worker keeps its own TCP/TLS connection and its own request/body/meta files (keyed by browser pid and worker slot, so multiple windows do not collide).  Completed images are decoded as jobs finish.  Stylesheet and external-script bodies are downloaded in parallel but parsed/executed in document order, and one image starts before the script phase so it overlaps script loading.  Idle helpers stay warm for same-origin navigations (they exit after ten idle seconds, and losing window focus stops them), while a cross-origin navigation closes them first so the old page's connections cannot stall the new fetch.  A DNS failure is retried once.  While loading, the status bar reports the page fetch's header and first-byte times; when the load is done it shows <code>Loaded in N ms: page P (headers H), parse, css, paint, js</code> for 12 s.  On the Cloudron store under QEMU/TCG with e1000 that is 2572 ms, of which the scripts take 1911 ms; QuickJS is built <code>-O1</code>, which beat <code>-Os</code> and <code>-O2</code> there.</li>
 			<li><strong>URL entry.</strong> A dotted name without a scheme that is not a known local file extension is treated as a hostname, so <code>cloudron.io</code> does not hit the local-file stat. A typed hostname is tried as <code>https://</code> first, skipping the common <code>http://host</code> → <code>https://host</code> hop; if the https connection is refused, reset, times out or fails the TLS handshake, the browser retries once over <code>http://</code> and replaces the history entry. Origin-level redirects (such as <code>https://host</code> → <code>https://www.host</code>) are cached per process and in <code>/share/borigins</code>; the first visit still follows them, later visits go straight to the canonical origin. Remote stylesheets are cached under <code>/share/bcss-*</code> for the current boot, so a reload or a fresh browser launch skips the CSS downloads.</li>
+			<li><strong>History and autocomplete.</strong> Every page that finishes loading is recorded in a 128-entry table (URL, title, visit count and a stamp counter that orders visits across windows and reboots without a clock). Browser windows of one boot share <code>/share/bhist</code>, merged and rewritten on each visit, and it is saved to <code>/data/BHIST.DAT</code> at most every 3 s. While the address bar has the focus a dropdown lists up to six matches: an empty bar shows the most visited and recent sites; typing ranks URL prefixes (with or without the scheme and <code>www.</code>) above URL and title substrings. Typing at the end completes inline to the next <code>/</code> of the best match (<code>clo</code> &rarr; <code>cloudron.io/</code>, the added part selected), and Enter opens the history URL it came from. Up/Down preview a row, Delete forgets it, Esc closes the list and a click opens a row.</li>
 			</ul>
 		<p>
 			The browser's default canvas is dark, matching the ngui theme, but an

+ 1 - 0
host/host.h

@@ -9,6 +9,7 @@ struct host_options {
 	const char *shot;
 	unsigned int wait_ms;
 	int headless;
+	const char *keys;       /* --keys: scripted headless keystrokes */
 	int width;
 	int height;
 };

+ 8 - 2
host/main.c

@@ -1,7 +1,11 @@
 /* browser-host: run the NebOS browser as a Linux/Wayland program.
  *
  * Usage: browser-host [--size WxH] [--root DIR] [--headless]
- *                     [--wait MS] [--shot FILE] [URL|FILE]
+ *                     [--wait MS] [--shot FILE] [--keys KEYS] [URL|FILE]
+ *
+ * --keys types into a headless window, one key every 100 ms from 300 ms
+ * after the first frame: plain characters, plus {enter} {esc} {tab} {bs}
+ * {del} {up} {down} {left} {right} {ctrl-l} and {wait} (a 1 s pause).
  */
 #include <signal.h>
 #include <stdio.h>
@@ -17,7 +21,7 @@ static void usage(void)
 	fprintf(stderr,
 		"usage: browser-host [--size WxH] [--root DIR] [--headless]\n"
 		"                    [--wait MS] [--shot|--screenshot FILE]\n"
-		"                    [URL|FILE]\n");
+		"                    [--keys KEYS] [URL|FILE]\n");
 }
 
 static int parse_size(const char *s, int *w, int *h)
@@ -65,6 +69,8 @@ int main(int argc, char **argv)
 			host_opts.shot = argv[++i];
 		} else if (!strcmp(a, "--screenshot") && i + 1 < argc) {
 			host_opts.shot = argv[++i];
+		} else if (!strcmp(a, "--keys") && i + 1 < argc) {
+			host_opts.keys = argv[++i];
 		} else if (!strcmp(a, "--help") || !strcmp(a, "-h")) {
 			usage();
 			return 0;

+ 42 - 1
host/window_headless.c

@@ -128,9 +128,50 @@ int host_headless_scroll(struct win_scroll *out)
 	return 0;
 }
 
+/* --keys: the next scripted key once it is due, else 0. */
+static const char *key_pos;
+static unsigned long long key_due;
+
 int host_headless_key(void)
 {
-	return 0;
+	static const struct {
+		const char *name;
+		int code;
+	} names[] = {
+		{"enter", '\n'}, {"esc", 0x1B}, {"tab", 0x09}, {"bs", 0x08},
+		{"del", 0x108}, {"left", 0x100}, {"right", 0x101},
+		{"up", 0x102}, {"down", 0x103}, {"ctrl-l", 0x0C}, {"wait", -1},
+	};
+	unsigned long long now = now_ms();
+	int code;
+
+	if (!host_opts.keys || !presented)
+		return 0;
+	if (!key_pos) {
+		key_pos = host_opts.keys;
+		key_due = first_present + 300;
+	}
+	if (!*key_pos || now < key_due)
+		return 0;
+	code = (unsigned char)*key_pos++;
+	if (code == '{') {
+		const char *end = strchr(key_pos, '}');
+		unsigned int i;
+
+		code = 0;
+		for (i = 0; end && i < sizeof(names) / sizeof(names[0]); i++)
+			if (strlen(names[i].name) == (size_t)(end - key_pos) &&
+			    !strncmp(key_pos, names[i].name,
+				     (size_t)(end - key_pos)))
+				code = names[i].code;
+		key_pos = end ? end + 1 : key_pos + strlen(key_pos);
+		if (code < 0) {
+			key_due = now + 1000;
+			return 0;
+		}
+	}
+	key_due = now + 100;
+	return code;
 }
 
 int host_headless_screen(unsigned int *w, unsigned int *h)

+ 624 - 4
user/apps/browser/browser.c

@@ -1716,6 +1716,277 @@ static void persist_cookies_flush(void)
 	free(jar);
 }
 
+/* ---- visit history (URL-bar autocomplete) ----
+ *
+ * Every page that finishes loading is recorded with its title, a visit
+ * count and a stamp: a counter that only grows and travels with the file,
+ * so it orders visits across windows and boots without a wall clock.  The
+ * table lives in BSS, because the page heap is reset on every navigation.
+ * The boot's browser windows share it through /share/bhist (rewritten on
+ * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
+ * at most every PERSIST_MS, like the cookie jar.  A save re-reads
+ * /share/bhist and merges it first, so two windows add to one history
+ * instead of overwriting each other.  File format: "NBHIST1\n", then
+ * "<visits> <stamp> <url>\t<title>\n" per entry.  Plaintext, like the
+ * other browser state on /data. */
+#define HIST_MAX        128
+#define HIST_URL_MAX    512
+#define HIST_FILE_MAX   (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
+#define HIST_MAGIC      "NBHIST1\n"
+#define SHARE_HIST      "/share/bhist"
+#define DATA_HIST       "/data/BHIST.DAT"
+#define HIST_FORGET_MAX 16
+
+struct hist_ent {
+	unsigned int visits;
+	unsigned int stamp;
+	char url[HIST_URL_MAX];
+	char title[BR_TITLE_MAX];
+};
+
+static struct hist_ent hist_tab[HIST_MAX];
+static int hist_n;
+static int hist_share_dirty, hist_data_dirty;
+/* URLs removed in this process: a merge must not bring them back. */
+static unsigned int hist_forgot[HIST_FORGET_MAX];
+static int hist_nforgot;
+
+static unsigned int hist_hash(const char *s)
+{
+	return persist_sum((const unsigned char *)s, s_len(s));
+}
+
+static int hist_is_forgotten(const char *url)
+{
+	unsigned int h = hist_hash(url);
+	int i;
+
+	for (i = 0; i < hist_nforgot; i++)
+		if (hist_forgot[i] == h)
+			return 1;
+	return 0;
+}
+
+static int hist_find(const char *url)
+{
+	int i;
+
+	for (i = 0; i < hist_n; i++)
+		if (s_eq(hist_tab[i].url, url))
+			return i;
+	return -1;
+}
+
+static unsigned int hist_next_stamp(void)
+{
+	unsigned int m = 0;
+	int i;
+
+	for (i = 0; i < hist_n; i++)
+		if (hist_tab[i].stamp > m)
+			m = hist_tab[i].stamp;
+	return m + 1;
+}
+
+/* Copy a title, turning tabs/newlines (the file separators) into spaces. */
+static void hist_copy_title(char *d, const char *s, unsigned int n)
+{
+	unsigned int i;
+
+	for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
+		d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
+	d[i] = '\0';
+}
+
+/* Insert or update an entry; the newer stamp wins the title, the larger
+ * visit count is kept.  A full table evicts the least recent entry, unless
+ * the new one is older still.  Returns NULL when nothing was stored. */
+static struct hist_ent *hist_put(const char *url, const char *title,
+				 unsigned int visits, unsigned int stamp)
+{
+	struct hist_ent *e;
+	int i = hist_find(url);
+
+	if (i < 0) {
+		if (hist_n < HIST_MAX) {
+			i = hist_n++;
+		} else {
+			int j;
+
+			i = 0;
+			for (j = 1; j < hist_n; j++)
+				if (hist_tab[j].stamp < hist_tab[i].stamp)
+					i = j;
+			if (hist_tab[i].stamp >= stamp)
+				return 0;
+		}
+		e = &hist_tab[i];
+		e->visits = 0;
+		e->stamp = 0;
+		e->title[0] = '\0';
+		s_copy(e->url, url, sizeof(e->url));
+	}
+	e = &hist_tab[i];
+	if (visits > e->visits)
+		e->visits = visits;
+	if (stamp >= e->stamp) {
+		e->stamp = stamp;
+		if (title && title[0])
+			hist_copy_title(e->title, title, BR_TITLE_MAX);
+	} else if (!e->title[0] && title) {
+		hist_copy_title(e->title, title, BR_TITLE_MAX);
+	}
+	return e;
+}
+
+static unsigned int hist_parse_dec(const char *b, int n, int *pos)
+{
+	unsigned int v = 0;
+
+	while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
+		v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
+	return v;
+}
+
+static void hist_merge_buf(const char *b, int n)
+{
+	int pos = (int)s_len(HIST_MAGIC);
+	char url[HIST_URL_MAX], title[BR_TITLE_MAX];
+
+	if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
+		return;
+	while (pos < n) {
+		unsigned int visits, stamp, ul = 0;
+		int t0, t1;
+
+		visits = hist_parse_dec(b, n, &pos);
+		if (pos < n && b[pos] == ' ')
+			pos++;
+		stamp = hist_parse_dec(b, n, &pos);
+		if (pos < n && b[pos] == ' ')
+			pos++;
+		while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
+			if (ul + 1 < sizeof(url))
+				url[ul++] = b[pos];
+			pos++;
+		}
+		url[ul] = '\0';
+		t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
+		while (t1 < n && b[t1] != '\n')
+			t1++;
+		pos = t1 + 1;
+		hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
+		if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
+			hist_put(url, title, visits, stamp);
+	}
+}
+
+static int hist_serialize(char *b, unsigned int cap)
+{
+	unsigned int n = 0;
+	int i;
+
+	s_append(b, &n, HIST_MAGIC, cap);
+	for (i = 0; i < hist_n; i++) {
+		struct hist_ent *e = &hist_tab[i];
+
+		if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
+			break;
+		s_append_dec(b, &n, e->visits, cap);
+		b[n++] = ' ';
+		s_append_dec(b, &n, e->stamp, cap);
+		b[n++] = ' ';
+		s_append(b, &n, e->url, cap);
+		b[n++] = '\t';
+		s_append(b, &n, e->title, cap);
+		b[n++] = '\n';
+	}
+	return (int)n;
+}
+
+/* Merge /share/bhist, then write it back (and /data when asked). */
+static void hist_sync(int to_data)
+{
+	char *b = (char *)malloc(HIST_FILE_MAX + 1);
+	int n;
+
+	if (!b)
+		return;
+	n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
+		       (int)HIST_FILE_MAX);
+	if (n > 0)
+		hist_merge_buf(b, n);
+	n = hist_serialize(b, HIST_FILE_MAX);
+	u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
+	hist_share_dirty = 0;
+	if (to_data) {
+		/* No /data mount: the write fails, and there is nothing to
+		 * retry until the next visit. */
+		u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
+		hist_data_dirty = 0;
+	}
+	free(b);
+}
+
+/* Startup: the boot's shared copy, else the saved one from /data. */
+static void hist_load(void)
+{
+	char *b = (char *)malloc(HIST_FILE_MAX + 1);
+	int n;
+
+	if (!b)
+		return;
+	n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
+		       (int)HIST_FILE_MAX);
+	if (n <= 0) {
+		n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
+			       (int)HIST_FILE_MAX);
+		if (n > 0)
+			u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
+	}
+	if (n > 0)
+		hist_merge_buf(b, n);
+	free(b);
+}
+
+static void hist_visit(const char *url, const char *title)
+{
+	struct hist_ent *e;
+	unsigned int i;
+
+	if (!url[0] || starts_with(url, "about:") ||
+	    s_len(url) >= HIST_URL_MAX)
+		return;
+	for (i = 0; url[i]; i++)
+		if ((unsigned char)url[i] < 0x20)
+			return;
+	e = hist_put(url, title, 0, hist_next_stamp());
+	if (!e)
+		return;
+	e->visits++;
+	hist_data_dirty = 1;
+	hist_sync(0);
+}
+
+static void hist_forget(int i)
+{
+	if (i < 0 || i >= hist_n)
+		return;
+	if (hist_nforgot < HIST_FORGET_MAX)
+		hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
+	hist_n--;
+	for (; i < hist_n; i++)
+		hist_tab[i] = hist_tab[i + 1];
+	hist_data_dirty = 1;
+	hist_sync(0);
+}
+
+static void hist_tick(void)
+{
+	if (hist_share_dirty || hist_data_dirty)
+		hist_sync(hist_data_dirty);
+}
+
 /* Main-loop hook: write back to /data at most every PERSIST_MS. */
 static void persist_tick(void)
 {
@@ -1727,6 +1998,7 @@ static void persist_tick(void)
 	persist_cookies_flush();
 	if (persist_ndirty)
 		persist_store_flush();
+	hist_tick();
 }
 
 /* <link rel="modulepreload">: download the page's module graph on all
@@ -5268,6 +5540,7 @@ static void load_page(const char *url, int local, int push)
 	}
 	preload_begin();
 	page_loading = 0;
+	hist_visit(page_url, page_title);
 	s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
 	url_in.len = s_len(url_in.text);
 	url_in.cursor = url_in.len;
@@ -10999,6 +11272,339 @@ static int find_hit(int x, int y)
 	return 0;
 }
 
+/* ---- URL-bar autocomplete ----
+ *
+ * While the address bar has the focus a dropdown lists up to SUG_MAX
+ * history entries.  An empty bar (a fresh focus, Ctrl+L) shows the most
+ * visited/recent sites; typing ranks prefix matches of the URL (with or
+ * without the scheme and "www.") above substring matches of the URL, then
+ * of the title, and adds visit count and recency.  Typing at the end of the
+ * text also completes inline to the next '/' of the best prefix match
+ * ("clo" -> "cloudron.io/"), with the added part selected so the next
+ * keystroke replaces it; Enter on that text opens the history URL it came
+ * from (scheme included).  Up/Down preview a row in the bar, Delete on a
+ * highlighted row forgets it, Esc closes the list (a second Esc leaves the
+ * bar), and a click on a row opens it. */
+#define SUG_MAX   6
+#define SUG_ROW_H 36
+
+static int sug_idx[SUG_MAX];
+static int sug_n, sug_sel = -1, sug_open;
+static char sug_typed[NGUI_INPUT_MAX];    /* what the user typed */
+static char sug_restore[NGUI_INPUT_MAX];  /* bar text before a preview */
+static char ac_text[NGUI_INPUT_MAX];      /* bar text of the inline completion */
+static char ac_url[HIST_URL_MAX];         /* the history URL it stands for */
+static struct ngui_rect url_rect, sug_rect;
+static int url_had_focus;
+
+static char lc(char c)
+{
+	return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
+}
+
+static int prefix_ci(const char *s, const char *p)    /* p is lower case */
+{
+	for (; *p; s++, p++)
+		if (lc(*s) != *p)
+			return 0;
+	return 1;
+}
+
+static unsigned int url_scheme_len(const char *url)
+{
+	if (starts_with(url, "https://"))
+		return 8;
+	if (starts_with(url, "http://"))
+		return 7;
+	return 0;
+}
+
+/* Offset in `url` where the lower-case text `t` matches as a prefix: the
+ * whole URL, the URL without its scheme, or without scheme and "www.". */
+static int hist_prefix_at(const char *url, const char *t)
+{
+	unsigned int s = url_scheme_len(url);
+
+	if (prefix_ci(url, t))
+		return 0;
+	if (s && prefix_ci(url + s, t))
+		return (int)s;
+	if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
+		return (int)s + 4;
+	return -1;
+}
+
+static int hist_score(const struct hist_ent *e, const char *t,
+		      unsigned int next)
+{
+	unsigned int age = next - e->stamp;
+	int sc, at;
+
+	if (!t[0]) {
+		sc = 0;
+	} else if ((at = hist_prefix_at(e->url, t)) >= 0) {
+		/* Shorter rests first: "cloudron.io/" before its subpages. */
+		int rest = (int)s_len(e->url + at);
+
+		sc = 4000 - (rest > 400 ? 400 : rest);
+	} else if (contains_ci(e->url, t)) {
+		sc = 1000;
+	} else if (contains_ci(e->title, t)) {
+		sc = 600;
+	} else {
+		return -1;
+	}
+	sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
+	sc += age >= 500 ? 0 : (int)(500 - age);
+	return sc;
+}
+
+static void sug_lower(char *t, unsigned int cap)
+{
+	unsigned int k;
+
+	for (k = 0; sug_typed[k] && k + 1 < cap; k++)
+		t[k] = lc(sug_typed[k]);
+	t[k] = '\0';
+}
+
+static void sug_refresh(void)
+{
+	char t[NGUI_INPUT_MAX];
+	int sc[SUG_MAX], i, j;
+	unsigned int next = hist_next_stamp();
+
+	sug_lower(t, sizeof(t));
+	sug_n = 0;
+	for (i = 0; i < hist_n; i++) {
+		int s = hist_score(&hist_tab[i], t, next);
+
+		if (s < 0)
+			continue;
+		j = sug_n;
+		if (j == SUG_MAX) {
+			if (sc[SUG_MAX - 1] >= s)
+				continue;
+			j = SUG_MAX - 1;
+		}
+		while (j > 0 && sc[j - 1] < s) {
+			sc[j] = sc[j - 1];
+			sug_idx[j] = sug_idx[j - 1];
+			j--;
+		}
+		sc[j] = s;
+		sug_idx[j] = i;
+		if (sug_n < SUG_MAX)
+			sug_n++;
+	}
+	if (sug_sel >= sug_n)
+		sug_sel = -1;
+}
+
+/* Complete the typed text inline to the next '/' of the best prefix match. */
+static void sug_inline(void)
+{
+	char t[NGUI_INPUT_MAX];
+	const char *url, *rest;
+	unsigned int L, start, end, hs, tn, n = 0;
+	unsigned int next = hist_next_stamp();
+	int i, best = -1, best_sc = -1, at = 0;
+
+	sug_lower(t, sizeof(t));
+	L = s_len(t);
+	if (!L)
+		return;
+	for (i = 0; i < hist_n; i++) {
+		int a = hist_prefix_at(hist_tab[i].url, t), s;
+
+		if (a < 0)
+			continue;
+		s = hist_score(&hist_tab[i], t, next);
+		if (s > best_sc) {
+			best_sc = s;
+			best = i;
+			at = a;
+		}
+	}
+	if (best < 0)
+		return;
+	url = hist_tab[best].url;
+	rest = url + at;
+	/* Typing the scheme ("htt") completes past "https://", not to it. */
+	hs = at == 0 ? url_scheme_len(url) : 0;
+	start = L > hs ? L : hs;
+	end = start;
+	while (rest[end] && rest[end] != '/')
+		end++;
+	if (rest[end] == '/')
+		end++;
+	tn = s_len(sug_typed);
+	if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
+		return;
+	s_append(ac_text, &n, sug_typed, sizeof(ac_text));
+	for (; L < end && n + 1 < sizeof(ac_text); L++)
+		ac_text[n++] = rest[L];
+	ac_text[n] = '\0';
+	s_copy(ac_url, url, (unsigned int)at + end + 1);
+	ngui_input_set(&url_in, ac_text);
+	url_in.anchor = tn;     /* select the completed part */
+}
+
+static void sug_close(void)
+{
+	sug_open = 0;
+	sug_sel = -1;
+	ac_text[0] = '\0';
+}
+
+static int sug_visible(void)
+{
+	return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
+}
+
+/* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
+ * start page) lists the top sites until something is typed. */
+static int sug_focus_check(void)
+{
+	int focused = ngui_focus(&ui) == ID_URL;
+
+	if (focused && !url_had_focus) {
+		sug_typed[0] = '\0';
+		sug_close();
+		sug_open = 1;
+		sug_refresh();
+	}
+	url_had_focus = focused;
+	return focused;
+}
+
+static void url_submit(unsigned int *action)
+{
+	if (ac_text[0] && s_eq(url_in.text, ac_text))
+		s_copy(click_url, ac_url, sizeof(click_url));
+	*action |= ACT_NAV;
+	sug_close();
+}
+
+/* The bar text changed through typing or editing. */
+static void sug_changed(void)
+{
+	unsigned int pl = s_len(sug_typed);
+	int grew = url_in.len > pl && url_in.cursor == url_in.len &&
+		   !memcmp(url_in.text, sug_typed, pl);
+
+	s_copy(sug_typed, url_in.text, sizeof(sug_typed));
+	ac_text[0] = '\0';
+	sug_sel = -1;
+	sug_open = 1;
+	sug_refresh();
+	if (grew)
+		sug_inline();
+}
+
+/* Keys for the list, taken off the queue before the text field sees them.
+ * Only a leading run is handled; the rest goes to the field. */
+static void sug_keys(void)
+{
+	int k;
+
+	while ((k = ngui_key_peek(&ui)) != 0) {
+		if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
+			ngui_key(&ui);
+			if (!sug_open) {
+				sug_open = 1;
+				continue;
+			}
+			if (sug_sel < 0)
+				s_copy(sug_restore, url_in.text,
+				       sizeof(sug_restore));
+			if (k == NGUI_KEY_DOWN)
+				sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
+			else
+				sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
+			ngui_input_set(&url_in, sug_sel >= 0 ?
+				       hist_tab[sug_idx[sug_sel]].url :
+				       sug_restore);
+		} else if (k == NGUI_KEY_ESC && sug_visible()) {
+			ngui_key(&ui);
+			if (sug_sel >= 0)
+				ngui_input_set(&url_in, sug_restore);
+			else if (ac_text[0] && s_eq(url_in.text, ac_text))
+				ngui_input_set(&url_in, sug_typed);
+			sug_close();
+		} else if (k == NGUI_KEY_DELETE && sug_visible() &&
+			   sug_sel >= 0) {
+			ngui_key(&ui);
+			hist_forget(sug_idx[sug_sel]);
+			ngui_input_set(&url_in, sug_restore);
+			sug_sel = -1;
+			sug_refresh();
+		} else {
+			break;
+		}
+	}
+}
+
+/* A press on a row of last frame's list opens it; any press on the list is
+ * swallowed so the page underneath does not see it. */
+static void sug_click(unsigned int *action)
+{
+	int row;
+
+	if (!(ui.pressed & 1) || !sug_rect.w ||
+	    !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
+		return;
+	row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
+	if (row >= 0 && row < sug_n) {
+		s_copy(click_url, hist_tab[sug_idx[row]].url,
+		       sizeof(click_url));
+		*action |= ACT_NAV;
+		sug_close();
+	}
+	ui.pressed = 0;
+}
+
+static void draw_suggest(struct ngui_rect page)
+{
+	struct ngui_rect r;
+	int i, rows = sug_n, hover = -1;
+
+	r.x = url_rect.x;
+	r.y = url_rect.y + url_rect.h + 1;
+	r.w = url_rect.w < 320 ? 320 : url_rect.w;
+	if (r.x + r.w > ui.w - 2)
+		r.w = ui.w - 2 - r.x;
+	while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
+		rows--;
+	if (rows <= 0 || r.w < 60) {
+		sug_rect.w = 0;
+		return;
+	}
+	r.h = rows * SUG_ROW_H + 2;
+	sug_rect = r;
+	if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
+		hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
+	}
+	ngui_fill_rect(&ui, r, ui.theme.border);
+	for (i = 0; i < rows; i++) {
+		const struct hist_ent *e = &hist_tab[sug_idx[i]];
+		struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
+				       r.w - 2, SUG_ROW_H};
+		struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
+		unsigned short bg = i == sug_sel ? ui.theme.selection :
+				    i == hover ? ui.theme.panel_alt :
+				    ui.theme.panel;
+
+		ngui_fill_rect(&ui, rr, bg);
+		ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
+				   e->title[0] ? e->title : e->url,
+				   ui.theme.text);
+		ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
+				   i == sug_sel ? ui.theme.text :
+				   ui.theme.text_dim);
+	}
+}
+
 static void draw_toolbar(struct ngui_rect r, unsigned int *action)
 {
 	int x = r.x + 4, y = r.y + 4, h = 22;
@@ -11037,16 +11643,23 @@ static void draw_toolbar(struct ngui_rect r, unsigned int *action)
 	in_w = r.x + r.w - 6 - go_w - 4 - in_x;
 	if (in_w < 60)
 		in_w = 60;
-	res = ngui_text_input(&ui, ID_URL,
-			      (struct ngui_rect){in_x, y, in_w, h}, &url_in);
+	url_rect = (struct ngui_rect){in_x, y, in_w, h};
+	if (sug_focus_check())
+		sug_keys();
+	res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
+	sug_focus_check();      /* a click into the bar focuses it here */
+	if (res & NGUI_INPUT_CHANGED)
+		sug_changed();
 	if (res & NGUI_INPUT_SUBMIT)
-		*action |= ACT_NAV;
+		url_submit(action);
 	if (res & NGUI_INPUT_CANCEL)
 		ngui_set_focus(&ui, 0);
 	if (ngui_button(&ui, ID_GO,
 			(struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
 			"Go"))
-		*action |= ACT_NAV;
+		url_submit(action);
+	if (!sug_focus_check())
+		sug_close();
 }
 
 static int page_hover_node(void)
@@ -11252,9 +11865,15 @@ static void draw(unsigned int *action)
 	toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
 	status = ngui_cut_bottom(&r, BR_STATUS_H);
 	page = r;
+	if (sug_visible())
+		sug_click(action);
 	draw_toolbar(toolbar, action);
 	draw_page(page);
 	draw_status(status);
+	if (sug_visible())
+		draw_suggest(page);
+	else
+		sug_rect.w = 0;
 }
 
 static void redraw_now(void)
@@ -11876,6 +12495,7 @@ void _start(const char *arg)
 	css_cache_init();
 	script_cache_init();
 	persist_restore();
+	hist_load();
 	page_scroll.offset = 0;
 	page_scroll.content_h = 0;