commit 7324e95cb59e0798926b5b732cf33663d2e7682a
parent 79431aac4ac2b2782c22790615328f5f9cd414a7
Author: torter <koubbamohamedrayan@gmail.com>
Date: Sun, 25 Oct 2026 22:09:50 -0400
jiggity, our own installer. the usb boots to Try or Install; Install runs jiggity alone, it installs and restarts, and the first start sets up the user, language and the rest
Diffstat:
10 files changed, 1008 insertions(+), 13 deletions(-)
diff --git a/build.sh b/build.sh
@@ -163,7 +163,6 @@ cp "$ISO_DIR/live/initrd.img" "$ROOT/boot/initramfs-$KVER.img"
echo "=== [5/5] SQUASHFS AND ISO"
mksquashfs "$ROOT" "$ISO_DIR/live/rootfs.squashfs" -comp zstd -Xcompression-level 15 -b 1M -noappend -no-xattrs -quiet
mkdir -p "$ISO_DIR/boot/grub"
-TITLE="Chamesle Linux $VERSION$SUFFIX ($EDITION_NAME)"
# the same boot menu theme an installed system gets
THEME=$ROOT/usr/share/grub/themes/chamesle
[ -d "$THEME" ] && mkdir -p "$ISO_DIR/boot/grub/themes" && cp -r "$THEME" "$ISO_DIR/boot/grub/themes/"
@@ -185,21 +184,32 @@ if [ -f \$prefix/themes/chamesle/theme.txt ]; then
fi
if [ ! -f /live/vmlinuz ]; then search --no-floppy --set=root --file /live/vmlinuz; fi
-menuentry "Try or install $TITLE" {
+# two choices, like a Windows USB: try it, or install it. Install starts Jiggity alone on the screen, with no desktop
+menuentry "Try Chamesle" {
linux /live/vmlinuz quiet splash loglevel=3 drm.panic_screen=kmsg
initrd /live/initrd.img
}
-menuentry "$TITLE (safe graphics)" {
- linux /live/vmlinuz quiet loglevel=3 nomodeset drm.panic_screen=kmsg
+menuentry "Install Chamesle" {
+ linux /live/vmlinuz chamesle.install=1 quiet splash loglevel=3 drm.panic_screen=kmsg
initrd /live/initrd.img
}
-menuentry "$TITLE (copy to RAM)" {
- linux /live/vmlinuz chamesle.toram=1 quiet splash loglevel=3 drm.panic_screen=kmsg
- initrd /live/initrd.img
-}
-menuentry "$TITLE (show boot messages)" {
- linux /live/vmlinuz loglevel=4 console=tty0 console=ttyS0,115200 drm.panic_screen=kmsg
- initrd /live/initrd.img
+submenu "More options" {
+ menuentry "Try Chamesle (safe graphics)" {
+ linux /live/vmlinuz quiet loglevel=3 nomodeset drm.panic_screen=kmsg
+ initrd /live/initrd.img
+ }
+ menuentry "Install Chamesle (safe graphics)" {
+ linux /live/vmlinuz chamesle.install=1 quiet loglevel=3 nomodeset drm.panic_screen=kmsg
+ initrd /live/initrd.img
+ }
+ menuentry "Try Chamesle (copy to RAM)" {
+ linux /live/vmlinuz chamesle.toram=1 quiet splash loglevel=3 drm.panic_screen=kmsg
+ initrd /live/initrd.img
+ }
+ menuentry "Try Chamesle (show boot messages)" {
+ linux /live/vmlinuz loglevel=4 console=tty0 console=ttyS0,115200 drm.panic_screen=kmsg
+ initrd /live/initrd.img
+ }
}
EOF
"$GRUB_MKRESCUE" -o "$ISO" "$ISO_DIR" -volid CHAMESLE
diff --git a/editions/gnome/overlay/etc/dinit.d/display-manager b/editions/gnome/overlay/etc/dinit.d/display-manager
@@ -1,6 +1,6 @@
# gdm (the gnome edition's, the others use sddm): gnome locks the screen only under gdm
type = process
-command = /usr/lib/dinit/gdm
+command = /usr/lib/chamesle/display-manager /usr/lib/dinit/gdm
depends-on = dbus
depends-on = elogind
waits-for = polkitd
diff --git a/overlay/etc/dinit.d/display-manager b/overlay/etc/dinit.d/display-manager
@@ -1,6 +1,6 @@
# sddm, with the chamesle sign-in screen
type = process
-command = /usr/bin/sddm
+command = /usr/lib/chamesle/display-manager /usr/bin/sddm
depends-on = dbus
depends-on = elogind
waits-for = polkitd
diff --git a/overlay/usr/bin/jiggity b/overlay/usr/bin/jiggity
@@ -0,0 +1,2 @@
+#!/bin/sh
+exec /usr/bin/python3 /usr/lib/jiggity/jiggity.py "$@"
diff --git a/overlay/usr/lib/chamesle/display-manager b/overlay/usr/lib/chamesle/display-manager
@@ -0,0 +1,14 @@
+#!/bin/sh
+# runs jiggity (chamesle.install=1) or first boot setup instead of the display manager
+export HOME=/root XDG_RUNTIME_DIR=/run/jiggity XCURSOR_THEME=Adwaita XCURSOR_SIZE=24
+mkdir -p -m 700 /run/jiggity
+alone() { xinit "$@" -- /usr/bin/Xorg :0 vt7 -nolisten tcp -keeptty >> /var/log/jiggity.log 2>&1; }
+if grep -qw chamesle.install=1 /proc/cmdline; then
+ alone /usr/bin/jiggity
+ exit 1
+fi
+if [ -f /etc/chamesle/firstboot ]; then
+ alone /usr/bin/python3 /usr/lib/jiggity/firstboot.py
+ [ -f /etc/chamesle/firstboot ] && exit 1
+fi
+exec "$@"
diff --git a/overlay/usr/lib/jiggity/disks.py b/overlay/usr/lib/jiggity/disks.py
@@ -0,0 +1,190 @@
+# drive scanning and partitioning
+import json
+import os
+import subprocess
+
+GiB = 1 << 30
+MiB = 1 << 20
+MIN_SIZE = 20 * GiB
+ESP_TYPE = "c12a7328-f81f-11d2-ba4b-00a0c93ec93b"
+
+
+def efi():
+ return os.path.exists("/sys/firmware/efi")
+
+
+def run(*cmd, input=None):
+ print("jiggity:", " ".join(cmd))
+ r = subprocess.run(cmd, input=input, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+ if r.stdout:
+ print(r.stdout.rstrip())
+ if r.returncode:
+ raise RuntimeError("%s failed: %s" % (cmd[0], (r.stdout or "").strip().splitlines()[-1:] or ""))
+ return r.stdout
+
+
+def size_text(n):
+ if n >= 1000 * GiB:
+ return "%.1f TB" % (n / (1024 * GiB))
+ if n >= GiB:
+ return "%.1f GB" % (n / GiB)
+ return "%d MB" % (n // MiB)
+
+
+def live_medium():
+ out = subprocess.run(["lsblk", "-J", "-o", "PATH,PKNAME,LABEL,FSTYPE"], text=True, stdout=subprocess.PIPE).stdout
+ for d in json.loads(out)["blockdevices"]:
+ for dev in [d] + d.get("children", []):
+ if dev.get("label") == "CHAMESLE" or dev.get("fstype") == "iso9660":
+ return d["path"]
+ return None
+
+
+def part_path(disk, number):
+ return "%s%s%d" % (disk, "p" if disk[-1].isdigit() else "", number)
+
+
+class Row:
+ def __init__(self, kind, disk, label, total, free, type_text, start=0, end=0, number=0):
+ self.kind, self.disk, self.label = kind, disk, label
+ self.total, self.free, self.type_text = total, free, type_text
+ self.start, self.end, self.number = start, end, number
+
+ @property
+ def usable(self):
+ return self.kind in ("drive", "free") and self.total >= MIN_SIZE
+
+
+def parted_lines(disk):
+ r = subprocess.run(["parted", "-m", "-s", disk, "unit", "B", "print", "free"], text=True,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ return r.stdout.splitlines()
+
+
+def scan():
+ skip = live_medium()
+ out = subprocess.run(["lsblk", "-J", "-b", "-d", "-o", "PATH,SIZE,TYPE,MODEL,RO,TRAN"], text=True,
+ stdout=subprocess.PIPE).stdout
+ rows = []
+ n = 0
+ for d in json.loads(out)["blockdevices"]:
+ # skip zram and empty card readers
+ if d["type"] != "disk" or d["ro"] or d["path"] == skip or d["path"].startswith("/dev/zram") or int(d["size"]) < GiB:
+ continue
+ name = "Drive %d" % n
+ model = (d.get("model") or "").strip()
+ rows.append(Row("drive", d["path"], "%s%s" % (name, ": " + model if model else ""), int(d["size"]), 0,
+ "Whole drive"))
+ lines = parted_lines(d["path"])
+ label = lines[1].split(":")[5] if len(lines) > 1 else "unknown"
+ if label not in ("gpt", "msdos"):
+ rows.append(Row("free", d["path"], "%s Unallocated Space" % name, int(d["size"]), int(d["size"]), "",
+ 0, int(d["size"]) - 1))
+ n += 1
+ continue
+ for line in lines[2:]:
+ f = line.rstrip(";").split(":")
+ start, end, size = (int(x.rstrip("B")) for x in f[1:4])
+ if f[4] == "free":
+ if size >= 64 * MiB:
+ rows.append(Row("free", d["path"], "%s Unallocated Space" % name, size, size, "", start, end))
+ else:
+ num = int(f[0])
+ fs, pname, flags = f[4], f[5], f[6]
+ kind = "System" if "esp" in flags or "boot" in flags and fs.startswith("fat") else \
+ "MSR (Reserved)" if "msftres" in flags else "Recovery" if "msftdata" not in flags and "hidden" in flags \
+ else fs or "Primary"
+ free = used_free(part_path(d["path"], num), fs, size)
+ rows.append(Row("part", d["path"], "%s Partition %d%s" % (name, num, ": " + pname if pname else ""),
+ size, free, kind, start, end, num))
+ n += 1
+ return rows
+
+
+def used_free(path, fs, size):
+ r = subprocess.run(["lsblk", "-J", "-b", "-o", "FSAVAIL", path], text=True, stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL)
+ try:
+ avail = json.loads(r.stdout)["blockdevices"][0]["fsavail"]
+ return int(avail) if avail is not None else size
+ except (ValueError, KeyError, IndexError):
+ return size
+
+
+def numbers(disk):
+ nums = set()
+ for line in parted_lines(disk)[2:]:
+ f = line.rstrip(";").split(":")
+ if f[4] != "free":
+ nums.add(int(f[0]))
+ return nums
+
+
+def settle():
+ subprocess.run(["partprobe"], stderr=subprocess.DEVNULL)
+ subprocess.run(["udevadm", "settle"])
+
+
+def has_esp(disk):
+ for line in parted_lines(disk)[2:]:
+ f = line.rstrip(";").split(":")
+ if f[4] != "free" and "esp" in f[6]:
+ return part_path(disk, int(f[0]))
+ return None
+
+
+def has_bios_grub(disk):
+ return any("bios_grub" in line for line in parted_lines(disk)[2:])
+
+
+class Plan:
+ # boot is only set with encryption, grub can't read luks2
+ efi = boot = root = None
+ format_efi = False
+
+
+def make(row, encrypt):
+ disk = row.disk
+ plan = Plan()
+ if row.kind == "drive" or parted_lines(disk)[1:2] and parted_lines(disk)[1].split(":")[5] not in ("gpt", "msdos"):
+ run("wipefs", "-a", disk)
+ run("parted", "-s", disk, "mklabel", "gpt")
+ start, end = MiB, None
+ else:
+ start = (row.start + MiB - 1) // MiB * MiB
+ end = (row.end + 1) // MiB * MiB
+ label = parted_lines(disk)[1].split(":")[5]
+ pieces = []
+ if efi():
+ plan.efi = has_esp(disk)
+ if not plan.efi:
+ pieces.append(("efi", 512 * MiB))
+ plan.format_efi = True
+ elif label == "gpt" and not has_bios_grub(disk):
+ pieces.append(("bios_grub", MiB))
+ if encrypt:
+ pieces.append(("boot", GiB))
+ pieces.append(("root", None))
+ at = start
+ for what, size in pieces:
+ before = numbers(disk)
+ stop = "100%" if size is None and end is None else "%dB" % ((at + size if size else end) - 1)
+ if label == "gpt":
+ run("parted", "-s", "-a", "optimal", disk, "unit", "B", "mkpart", "chamesle-" + what, "%dB" % at, stop)
+ else:
+ run("parted", "-s", "-a", "optimal", disk, "unit", "B", "mkpart", "primary", "%dB" % at, stop)
+ num = (numbers(disk) - before).pop()
+ path = part_path(disk, num)
+ if what == "efi":
+ run("parted", "-s", disk, "set", str(num), "esp", "on")
+ plan.efi = path
+ elif what == "bios_grub":
+ run("parted", "-s", disk, "set", str(num), "bios_grub", "on")
+ elif what == "boot":
+ plan.boot = path
+ else:
+ plan.root = path
+ if size:
+ at += size
+ settle()
+ return plan
diff --git a/overlay/usr/lib/jiggity/firstboot.py b/overlay/usr/lib/jiggity/firstboot.py
@@ -0,0 +1,203 @@
+#!/usr/bin/python3
+# first boot setup: time zone, wi-fi, user account
+import os
+import re
+import subprocess
+import sys
+import threading
+
+import gi
+gi.require_version("Gtk", "3.0")
+from gi.repository import Gtk, GLib
+
+sys.path.insert(0, "/usr/lib/jiggity")
+import ui
+
+MARK = "/etc/chamesle/firstboot"
+GROUPS = "wheel audio video input network storage optical scanner lp plugdev bluetooth users kvm".split()
+
+
+def zones():
+ out = []
+ try:
+ for line in open("/usr/share/zoneinfo/zone1970.tab"):
+ if not line.startswith("#"):
+ out.append(line.split("\t")[2].strip())
+ except OSError:
+ out = ["UTC"]
+ return sorted(out)
+
+
+def online():
+ r = subprocess.run(["nmcli", "-t", "-f", "STATE", "general"], text=True, stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL)
+ return r.stdout.strip() == "connected"
+
+
+class FirstBoot(ui.SetupWindow):
+ def __init__(self):
+ super().__init__("Chamesle")
+ self.pages = [self.page_zone(), self.page_wifi(), self.page_account(), self.page_wait()]
+ self.show_page(0)
+
+ # time zone
+ def page_zone(self):
+ box = ui.page("Let's start with your time zone. Is this the right one?",
+ "It sets your clock. Type a city to find yours.")
+ self.zone_filter = Gtk.SearchEntry(margin_top=10)
+ box.pack_start(self.zone_filter, False, False, 0)
+ self.zone_store = Gtk.ListStore(str, str)
+ for z in zones():
+ self.zone_store.append([z.replace("_", " ").replace("/", " / "), z])
+ filt = self.zone_store.filter_new()
+ filt.set_visible_func(lambda m, it, d: self.zone_filter.get_text().lower() in m[it][0].lower())
+ self.zone_filter.connect("search-changed", lambda *a: filt.refilter())
+ view = Gtk.TreeView(model=filt, headers_visible=False)
+ view.append_column(Gtk.TreeViewColumn("", Gtk.CellRendererText(), text=0))
+ self.zone_sel = view.get_selection()
+ self.zone_sel.connect("changed", lambda s: self.set_button_sensitive("Yes", s.get_selected()[1] is not None))
+ scroll = Gtk.ScrolledWindow(min_content_height=260)
+ scroll.add(view)
+ scroll.get_style_context().add_class("table")
+ box.pack_start(scroll, True, True, 6)
+ return box, [("Yes", self.after_zone)]
+
+ def after_zone(self, *a):
+ model, it = self.zone_sel.get_selected()
+ self.zone = model[it][1]
+ self.show_page(2 if online() else 1)
+
+ # wi-fi
+ def page_wifi(self):
+ box = ui.page("Let's connect you to a network", "You need the internet for updates and the app store.")
+ self.wifi_store = Gtk.ListStore(str, str, str)
+ view = Gtk.TreeView(model=self.wifi_store, headers_visible=False)
+ view.append_column(Gtk.TreeViewColumn("", Gtk.CellRendererText(), text=0))
+ view.append_column(Gtk.TreeViewColumn("", Gtk.CellRendererText(xalign=1), text=1))
+ self.wifi_sel = view.get_selection()
+ self.wifi_sel.connect("changed", self.on_wifi)
+ scroll = Gtk.ScrolledWindow(min_content_height=200, margin_top=10)
+ scroll.add(view)
+ scroll.get_style_context().add_class("table")
+ box.pack_start(scroll, True, True, 0)
+ row = Gtk.Box(spacing=10, margin_top=8)
+ row.pack_start(Gtk.Label(label="Password:"), False, False, 0)
+ self.wifi_pass = Gtk.Entry(visibility=False, width_chars=28)
+ row.pack_start(self.wifi_pass, False, False, 0)
+ box.pack_start(row, False, False, 0)
+ self.wifi_note = Gtk.Label(xalign=0, wrap=True)
+ self.wifi_note.get_style_context().add_class("note")
+ box.pack_start(self.wifi_note, False, False, 0)
+ return box, [("Connect", self.on_connect), ("Skip for now", lambda *a: self.show_page(2))]
+
+ def fill_wifi(self):
+ self.wifi_store.clear()
+ r = subprocess.run(["nmcli", "-t", "-f", "SSID,SIGNAL,SECURITY", "device", "wifi", "list", "--rescan", "yes"],
+ text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
+ seen = set()
+ for line in r.stdout.splitlines():
+ f = re.split(r"(?<!\\):", line)
+ if len(f) < 3 or not f[0] or f[0] in seen:
+ continue
+ seen.add(f[0])
+ self.wifi_store.append([f[0].replace("\\:", ":"), "%s%%%s" % (f[1], " \U0001F512" if f[2] else ""), f[2]])
+ self.wifi_note.set_text("" if len(self.wifi_store) else "No Wi-Fi networks found. You can skip this and connect later.")
+ self.on_wifi()
+
+ def on_wifi(self, *a):
+ self.set_button_sensitive("Connect", self.wifi_sel.get_selected()[1] is not None)
+
+ def on_connect(self, *a):
+ model, it = self.wifi_sel.get_selected()
+ ssid, secure = model[it][0], model[it][2]
+ cmd = ["nmcli", "device", "wifi", "connect", ssid]
+ if secure:
+ cmd += ["password", self.wifi_pass.get_text()]
+ self.wifi_note.set_text("Connecting to %s..." % ssid)
+
+ def go():
+ ok = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
+ GLib.idle_add(lambda: self.show_page(2) if ok else
+ self.wifi_note.set_text("Couldn't connect to %s. Check the password and try again." % ssid))
+ threading.Thread(target=go, daemon=True).start()
+
+ # the account
+ def page_account(self):
+ box = ui.page("Who's going to use this PC?", "")
+ grid = Gtk.Grid(column_spacing=12, row_spacing=10, margin_top=14)
+ self.name = Gtk.Entry(width_chars=30, placeholder_text="Your name")
+ self.user = Gtk.Entry(width_chars=30)
+ self.pw1 = Gtk.Entry(width_chars=30, visibility=False)
+ self.pw2 = Gtk.Entry(width_chars=30, visibility=False)
+ for r, (text, e) in enumerate([("Name:", self.name), ("Username:", self.user), ("Password:", self.pw1),
+ ("Confirm password:", self.pw2)]):
+ grid.attach(Gtk.Label(label=text, xalign=1), 0, r, 1, 1)
+ grid.attach(e, 1, r, 1, 1)
+ e.connect("changed", self.on_account)
+ self.user_edited = False
+ self.user.connect("key-press-event", lambda *a: setattr(self, "user_edited", True))
+ box.pack_start(grid, False, False, 0)
+ self.account_note = Gtk.Label(xalign=0, wrap=True, margin_top=10)
+ self.account_note.get_style_context().add_class("note")
+ box.pack_start(self.account_note, False, False, 0)
+ return box, [("Next", self.on_done), ("Back", lambda *a: self.show_page(0))]
+
+ def on_account(self, entry):
+ if entry is self.name and not self.user_edited:
+ u = re.sub(r"[^a-z0-9_-]", "", self.name.get_text().split(" ")[0].lower())
+ self.user.set_text(u)
+ u, p1, p2 = self.user.get_text(), self.pw1.get_text(), self.pw2.get_text()
+ note, ok = "", True
+ if u and not re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", u):
+ note, ok = "A username is lowercase letters and numbers, starting with a letter.", False
+ elif u in ("root", "live", "daemon", "bin", "nobody"):
+ note, ok = "That username is taken by the system. Pick another one.", False
+ elif p2 and p1 != p2:
+ note, ok = "The passwords don't match.", False
+ self.account_note.set_text(note)
+ self.set_button_sensitive("Next", ok and bool(u and p1 and p1 == p2))
+
+ def on_done(self, *a):
+ self.show_page(3)
+ threading.Thread(target=self.make_account, daemon=True).start()
+
+ # just a moment
+ def page_wait(self):
+ box = ui.page("Just a moment...", "")
+ spinner = Gtk.Spinner(margin_top=40, halign=Gtk.Align.CENTER)
+ spinner.set_size_request(48, 48)
+ spinner.start()
+ box.pack_start(spinner, False, False, 0)
+ return box, []
+
+ def make_account(self):
+ user, name, pw = self.user.get_text(), self.name.get_text(), self.pw1.get_text()
+ groups = [g.split(":")[0] for g in open("/etc/group")]
+ subprocess.run(["useradd", "-m", "-s", "/bin/bash", "-c", name, "-G",
+ ",".join(g for g in GROUPS if g in groups), user])
+ subprocess.run(["chpasswd", "-c", "SHA512"], input="%s:%s\n" % (user, pw), text=True)
+ subprocess.run(["ln", "-sf", "/usr/share/zoneinfo/" + self.zone, "/etc/localtime"])
+ with open("/etc/timezone", "w") as f:
+ f.write(self.zone + "\n")
+ host = re.sub(r"[^a-z0-9-]", "", user.lower())[:20] + "-pc"
+ with open("/etc/hostname", "w") as f:
+ f.write(host + "\n")
+ with open("/etc/hosts", "w") as f:
+ f.write("127.0.0.1\tlocalhost\n127.0.1.1\t%s\n::1\tlocalhost ip6-localhost ip6-loopback\n" % host)
+ subprocess.run(["hostname", host])
+ os.unlink(MARK)
+ GLib.idle_add(Gtk.main_quit)
+
+ def show_page(self, n):
+ super().show_page(n)
+ if n == 1:
+ GLib.idle_add(self.fill_wifi)
+ if n == 0:
+ self.set_button_sensitive("Yes", False)
+ if n == 2:
+ self.set_button_sensitive("Next", False)
+
+
+if __name__ == "__main__":
+ FirstBoot()
+ Gtk.main()
diff --git a/overlay/usr/lib/jiggity/install.py b/overlay/usr/lib/jiggity/install.py
@@ -0,0 +1,163 @@
+# progress(step, percent): 0 partition, 1 copy, 2 configure, 3 bootloader, 4 cleanup
+import os
+import subprocess
+import time
+
+import disks
+from disks import run
+
+SOURCE = "/run/chamesle/rootfs/"
+T = "/target"
+# live session only
+LIVE_ONLY = ["/etc/sudoers.d/live", "/etc/polkit-1/rules.d/49-live.rules", "/etc/lightdm/lightdm.conf.d/90-live.conf",
+ "/etc/sddm.conf.d/90-live.conf", "/usr/share/applications/chamesle-install.desktop", "/usr/bin/chamesle-install",
+ "/usr/bin/live-installer", "/usr/lib/live-installer", "/usr/share/live-installer",
+ "/usr/share/icons/live-installer-progress-dot-on.png", "/usr/share/icons/live-installer-progress-dot-off.png",
+ "/var/lib/AccountsService/users/live", "/usr/bin/jiggity"]
+
+
+def chroot(*cmd, input=None):
+ return run("chroot", T, *cmd, input=input)
+
+
+def uuid(dev):
+ return subprocess.run(["blkid", "-s", "UUID", "-o", "value", dev], text=True, stdout=subprocess.PIPE).stdout.strip()
+
+
+def set_grub(key, value):
+ path = T + "/etc/default/grub"
+ lines = open(path).read().split("\n") if os.path.exists(path) else []
+ line = '%s="%s"' % (key, value)
+ for i, l in enumerate(lines):
+ if l.lstrip("#").startswith(key + "="):
+ lines[i] = line
+ break
+ else:
+ lines.append(line)
+ with open(path, "w") as f:
+ f.write("\n".join(lines).rstrip("\n") + "\n")
+
+
+def install(row, passphrase, language, keyboard, progress):
+ os.makedirs(T, exist_ok=True)
+ progress(0, 0)
+ plan = disks.make(row, passphrase is not None)
+ progress(0, 40)
+ root = plan.root
+ if passphrase is not None:
+ run("cryptsetup", "luksFormat", "--batch-mode", "--type", "luks2", "--key-file=-", plan.root, input=passphrase)
+ run("cryptsetup", "open", "--key-file=-", plan.root, "chamesle", input=passphrase)
+ root = "/dev/mapper/chamesle"
+ if plan.format_efi:
+ run("mkfs.fat", "-F", "32", "-n", "EFI", plan.efi)
+ if plan.boot:
+ run("mkfs.ext4", "-F", "-q", "-L", "boot", plan.boot)
+ run("mkfs.btrfs", "-f", "-L", "Chamesle", root)
+ run("mount", root, T)
+ run("btrfs", "subvolume", "create", T + "/@", T + "/@home")
+ run("umount", T)
+ run("mount", "-o", "subvol=@,compress=zstd:1", root, T)
+ os.makedirs(T + "/home", exist_ok=True)
+ run("mount", "-o", "subvol=@home,compress=zstd:1", root, T + "/home")
+ if plan.boot:
+ os.makedirs(T + "/boot", exist_ok=True)
+ run("mount", plan.boot, T + "/boot")
+ if plan.efi:
+ os.makedirs(T + "/boot/efi", exist_ok=True)
+ run("mount", plan.efi, T + "/boot/efi")
+ progress(0, 100)
+
+ # progress = files copied / inodes used on the live root
+ total = int(subprocess.run(["df", "--output=iused", SOURCE], text=True, stdout=subprocess.PIPE).stdout.split()[-1])
+ excludes = []
+ for d in "home/* dev/* proc/* sys/* tmp/* run/* mnt/* media/* lost+found".split():
+ excludes += ["--exclude=/" + d]
+ p = subprocess.Popen(["rsync", "--archive", "--hard-links", "--acls", "--xattrs", "--no-D", "--out-format=%n"]
+ + excludes + [SOURCE, T + "/"], text=True, errors="ignore", stdout=subprocess.PIPE)
+ done = 0
+ for _ in p.stdout:
+ done += 1
+ if done % 200 == 0:
+ progress(1, min(99, done * 100 // max(total, 1)))
+ if p.wait():
+ raise RuntimeError("copying the files failed")
+ progress(1, 100)
+
+ for d in ("dev", "proc", "sys", "run"):
+ os.makedirs(T + "/" + d, exist_ok=True)
+ run("mount", "--rbind", "/" + d, T + "/" + d)
+ run("mount", "--make-rslave", T + "/" + d)
+ for path in LIVE_ONLY:
+ run("rm", "-rf", T + path)
+ if os.path.exists(T + "/etc/gdm/custom.conf"):
+ run("sed", "-i", "/^# the live session only$/d; /^AutomaticLogin/d", T + "/etc/gdm/custom.conf")
+ chroot("userdel", "-r", "live")
+ chroot("passwd", "-dl", "root")
+ open(T + "/etc/chamesle/firstboot", "w").close()
+ progress(2, 30)
+
+ with open(T + "/etc/fstab", "w") as f:
+ r = uuid(root)
+ f.write("# made by Jiggity\nproc /proc proc defaults 0 0\n")
+ f.write("UUID=%s / btrfs defaults,subvol=@,compress=zstd:1 0 0\n" % r)
+ f.write("UUID=%s /home btrfs defaults,subvol=@home,compress=zstd:1 0 0\n" % r)
+ if plan.boot:
+ f.write("UUID=%s /boot ext4 defaults 0 2\n" % uuid(plan.boot))
+ if plan.efi:
+ f.write("UUID=%s /boot/efi vfat umask=0077 0 2\n" % uuid(plan.efi))
+ if passphrase is not None:
+ with open(T + "/etc/crypttab", "a") as f:
+ f.write("chamesle UUID=%s none luks,discard,tries=3\n" % uuid(plan.root))
+ progress(2, 50)
+
+ locale = language + ".UTF-8"
+ path = T + "/etc/default/libc-locales"
+ lines = open(path).read().split("\n") if os.path.exists(path) else []
+ if locale + " UTF-8" not in [l.lstrip("#").strip() for l in lines]:
+ lines.append(locale + " UTF-8")
+ lines = [locale + " UTF-8" if l.lstrip("#").strip() == locale + " UTF-8" else l for l in lines]
+ with open(path, "w") as f:
+ f.write("\n".join(lines).rstrip("\n") + "\n")
+ chroot("locale-gen")
+ with open(T + "/etc/locale.conf", "w") as f:
+ f.write("LANG=%s\n" % locale)
+ layout, variant = keyboard
+ os.makedirs(T + "/etc/X11/xorg.conf.d", exist_ok=True)
+ with open(T + "/etc/X11/xorg.conf.d/00-keyboard.conf", "w") as f:
+ f.write('Section "InputClass"\n Identifier "system-keyboard"\n MatchIsKeyboard "on"\n'
+ ' Option "XkbLayout" "%s"\n Option "XkbVariant" "%s"\nEndSection\n' % (layout, variant or ""))
+ with open(T + "/etc/vconsole.conf", "w") as f:
+ f.write("KEYMAP=%s\n" % (layout + ("-" + variant if variant else "")))
+ progress(2, 100)
+
+ if passphrase is not None:
+ set_grub("GRUB_CMDLINE_LINUX", "rd.luks.uuid=%s" % uuid(plan.root))
+ chroot("dracut", "--force", "--regenerate-all")
+ progress(3, 40)
+ cmdline = "quiet splash loglevel=3 drm.panic_screen=kmsg"
+ if os.path.exists(T + "/usr/lib/chamesle/init"):
+ cmdline += " init=/usr/lib/chamesle/init"
+ set_grub("GRUB_DISTRIBUTOR", "Chamesle")
+ set_grub("GRUB_CMDLINE_LINUX_DEFAULT", cmdline)
+ set_grub("GRUB_DISABLE_OS_PROBER", "false")
+ set_grub("GRUB_GFXMODE", "auto")
+ set_grub("GRUB_GFXPAYLOAD_LINUX", "keep")
+ if os.path.exists(T + "/usr/share/grub/themes/chamesle/theme.txt"):
+ set_grub("GRUB_THEME", "/usr/share/grub/themes/chamesle/theme.txt")
+ if disks.efi():
+ chroot("grub-install", "--target=x86_64-efi", "--efi-directory=/boot/efi", "--bootloader-id=chamesle")
+ # some firmware only boots the fallback path
+ chroot("grub-install", "--target=x86_64-efi", "--efi-directory=/boot/efi", "--removable", "--no-nvram")
+ else:
+ chroot("grub-install", "--target=i386-pc", row.disk)
+ progress(3, 70)
+ chroot("grub-mkconfig", "-o", "/boot/grub/grub.cfg")
+ if "Chamesle" not in open(T + "/boot/grub/grub.cfg").read():
+ raise RuntimeError("the boot menu came out without Chamesle in it")
+ progress(3, 100)
+
+ os.sync()
+ subprocess.run(["umount", "-R", T])
+ if passphrase is not None:
+ subprocess.run(["cryptsetup", "close", "chamesle"])
+ progress(4, 100)
diff --git a/overlay/usr/lib/jiggity/jiggity.py b/overlay/usr/lib/jiggity/jiggity.py
@@ -0,0 +1,265 @@
+#!/usr/bin/python3
+# jiggity - the chamesle installer
+import subprocess
+import sys
+import threading
+
+import gi
+gi.require_version("Gtk", "3.0")
+from gi.repository import Gtk, Gdk, GLib
+
+sys.path.insert(0, "/usr/lib/jiggity")
+import disks
+import install
+import ui
+
+LANGUAGES = [
+ ("English (United States)", "en_US"), ("English (United Kingdom)", "en_GB"), ("Français", "fr_FR"),
+ ("Deutsch", "de_DE"), ("Español", "es_ES"), ("Español (México)", "es_MX"), ("Italiano", "it_IT"),
+ ("Português (Brasil)", "pt_BR"), ("Português", "pt_PT"), ("Nederlands", "nl_NL"), ("Polski", "pl_PL"),
+ ("Türkçe", "tr_TR"), ("Русский", "ru_RU"), ("Українська", "uk_UA"), ("العربية", "ar_MA"), ("العربية (مصر)", "ar_EG"),
+ ("Svenska", "sv_SE"), ("Norsk bokmål", "nb_NO"), ("Dansk", "da_DK"), ("Suomi", "fi_FI"), ("Čeština", "cs_CZ"),
+ ("Magyar", "hu_HU"), ("Română", "ro_RO"), ("Ελληνικά", "el_GR"), ("日本語", "ja_JP"), ("한국어", "ko_KR"),
+ ("中文 (简体)", "zh_CN"), ("中文 (繁體)", "zh_TW"), ("हिन्दी", "hi_IN"), ("Bahasa Indonesia", "id_ID"),
+ ("Tiếng Việt", "vi_VN"),
+]
+STEPS = ["Getting the drive ready", "Copying files", "Getting files ready for installation",
+ "Installing the boot menu", "Finishing up"]
+
+
+def keyboards():
+ out, section = [], None
+ try:
+ lines = open("/usr/share/X11/xkb/rules/base.lst").read().splitlines()
+ except OSError:
+ return [("English (US)", "us", "")]
+ for line in lines:
+ if line.startswith("!"):
+ section = line[1:].strip()
+ continue
+ if not line.strip():
+ continue
+ name, desc = line.split(None, 1)
+ if section == "layout":
+ out.append((desc.strip(), name, ""))
+ elif section == "variant":
+ layout, desc = desc.split(":", 1)
+ out.append((desc.strip(), layout, name))
+ return sorted(out, key=lambda k: k[0].lower())
+
+
+class Jiggity(ui.SetupWindow):
+ def __init__(self):
+ super().__init__("Chamesle Setup")
+ self.rows = []
+ self.pages = [self.page_language(), self.page_start(), self.page_where(), self.page_installing(), self.page_done()]
+ self.show_page(0)
+
+ # language and keyboard
+ def page_language(self):
+ box = ui.page("", "")
+ box.pack_start(ui.logo_line("Chamesle"), False, False, 12)
+ grid = Gtk.Grid(column_spacing=16, row_spacing=14, halign=Gtk.Align.CENTER, margin_top=24)
+ self.language = Gtk.ComboBoxText()
+ for name, code in LANGUAGES:
+ self.language.append(code, name)
+ self.language.set_active_id("en_US")
+ self.keyboard = Gtk.ComboBoxText()
+ self.kbds = keyboards()
+ for i, (desc, layout, variant) in enumerate(self.kbds):
+ self.keyboard.append(str(i), desc)
+ if layout == "us" and not variant:
+ self.keyboard.set_active(i)
+ self.keyboard.connect("changed", self.on_keyboard)
+ for r, (text, w) in enumerate([("Language to install:", self.language), ("Keyboard or input method:", self.keyboard)]):
+ l = Gtk.Label(label=text, xalign=1)
+ grid.attach(l, 0, r, 1, 1)
+ w.set_size_request(320, -1)
+ grid.attach(w, 1, r, 1, 1)
+ box.pack_start(grid, False, False, 0)
+ hint = Gtk.Label(label="Enter your language and other preferences and click \"Next\" to continue.", margin_top=40)
+ hint.get_style_context().add_class("dim")
+ box.pack_start(hint, False, False, 0)
+ return box, [("Next", lambda *a: self.show_page(1))]
+
+ def on_keyboard(self, combo):
+ desc, layout, variant = self.kbds[int(combo.get_active_id())]
+ subprocess.run(["setxkbmap", layout] + (["-variant", variant] if variant else []))
+
+ # install now
+ def page_start(self):
+ box = ui.page("", "")
+ box.pack_start(ui.logo_line("Chamesle"), False, False, 40)
+ button = Gtk.Button(label="Install now", halign=Gtk.Align.CENTER)
+ button.get_style_context().add_class("big")
+ button.connect("clicked", lambda *a: self.show_page(2))
+ box.pack_start(button, False, False, 0)
+ return box, [("Back", lambda *a: self.show_page(0))]
+
+ # where
+ def page_where(self):
+ box = ui.page("Where do you want to install Chamesle?", "")
+ self.store = Gtk.ListStore(str, str, str, str, bool, int)
+ view = Gtk.TreeView(model=self.store, headers_visible=True)
+ for i, (title, xalign) in enumerate([("Name", 0), ("Total size", 1), ("Free space", 1), ("Type", 0)]):
+ cell = Gtk.CellRendererText(xalign=xalign)
+ col = Gtk.TreeViewColumn(title, cell, text=i, sensitive=4)
+ col.set_expand(i == 0)
+ view.append_column(col)
+ self.selection = view.get_selection()
+ self.selection.set_select_function(lambda sel, model, path, selected: model[path][4])
+ self.selection.connect("changed", self.on_where)
+ scroll = Gtk.ScrolledWindow(min_content_height=220)
+ scroll.add(view)
+ scroll.get_style_context().add_class("table")
+ box.pack_start(scroll, True, True, 0)
+ tools = Gtk.Box(spacing=18, margin_top=6)
+ refresh = Gtk.LinkButton(label="Refresh", uri="")
+ refresh.connect("activate-link", lambda *a: self.fill_where() or True)
+ tools.pack_start(refresh, False, False, 0)
+ box.pack_start(tools, False, False, 0)
+ self.where_note = Gtk.Label(xalign=0, wrap=True, margin_top=6)
+ self.where_note.get_style_context().add_class("note")
+ box.pack_start(self.where_note, False, False, 0)
+ self.encrypt = Gtk.CheckButton(label="Encrypt Chamesle with a passphrase", margin_top=10)
+ box.pack_start(self.encrypt, False, False, 0)
+ self.pass_grid = Gtk.Grid(column_spacing=12, row_spacing=8, margin_start=28, no_show_all=True)
+ self.pass1 = Gtk.Entry(visibility=False, width_chars=28)
+ self.pass2 = Gtk.Entry(visibility=False, width_chars=28)
+ for r, (text, e) in enumerate([("Passphrase:", self.pass1), ("Confirm:", self.pass2)]):
+ self.pass_grid.attach(Gtk.Label(label=text, xalign=1), 0, r, 1, 1)
+ self.pass_grid.attach(e, 1, r, 1, 1)
+ e.connect("changed", self.on_where)
+ warn = Gtk.Label(label="You type it every time the computer starts. If you forget it, your files can't be "
+ "recovered.", xalign=0, wrap=True, max_width_chars=60)
+ warn.get_style_context().add_class("note")
+ self.pass_grid.attach(warn, 0, 2, 2, 1)
+ box.pack_start(self.pass_grid, False, False, 0)
+ self.encrypt.connect("toggled", self.on_encrypt)
+ return box, [("Next", self.on_install), ("Back", lambda *a: self.show_page(1))]
+
+ def fill_where(self):
+ self.store.clear()
+ self.rows = disks.scan()
+ for i, r in enumerate(self.rows):
+ name = r.label if r.kind == "drive" else " " + r.label
+ free = disks.size_text(r.free) if r.kind != "drive" else ""
+ self.store.append([name, disks.size_text(r.total), free, r.type_text, r.usable, i])
+ if not self.rows:
+ self.where_note.set_text("No drives were found. Check that the drive is connected, then click Refresh.")
+ self.on_where()
+
+ def on_encrypt(self, check):
+ self.pass_grid.set_visible(check.get_active())
+ if check.get_active():
+ self.pass_grid.show_all()
+ self.on_where()
+
+ def chosen(self):
+ model, it = self.selection.get_selected()
+ return self.rows[model[it][5]] if it else None
+
+ def on_where(self, *a):
+ row = self.chosen()
+ ok = row is not None
+ if row is None:
+ if self.rows:
+ self.where_note.set_text("Pick a drive (to use all of it) or its unallocated space (to keep what's on "
+ "the drive). Chamesle needs at least %s." % disks.size_text(disks.MIN_SIZE))
+ elif row.kind == "drive":
+ self.where_note.set_text("Everything on %s will be erased." % row.label.split(":")[0])
+ else:
+ self.where_note.set_text("Chamesle goes in the unallocated space. Nothing else on the drive changes. "
+ "When the computer starts, you choose between Chamesle and what's already there.")
+ if self.encrypt.get_active():
+ p1, p2 = self.pass1.get_text(), self.pass2.get_text()
+ ok = ok and len(p1) >= 8 and p1 == p2
+ if p1 and len(p1) < 8:
+ self.where_note.set_text("The passphrase needs at least 8 characters.")
+ elif p2 and p1 != p2:
+ self.where_note.set_text("The passphrases don't match.")
+ self.set_button_sensitive("Next", ok)
+
+ def on_install(self, *a):
+ row = self.chosen()
+ if row.kind == "drive":
+ if not ui.confirm(self, "Erase %s?" % row.label.split(":")[0],
+ "Everything on this drive will be deleted, and Chamesle will be installed on it. "
+ "This can't be undone."):
+ return
+ passphrase = self.pass1.get_text() if self.encrypt.get_active() else None
+ language = self.language.get_active_id()
+ desc, layout, variant = self.kbds[int(self.keyboard.get_active_id())]
+ self.show_page(3)
+ threading.Thread(target=self.run_install, args=(row, passphrase, language, (layout, variant)), daemon=True).start()
+
+ # installing
+ def page_installing(self):
+ box = ui.page("Installing Chamesle", "")
+ box.pack_start(Gtk.Label(label="Status", xalign=0, margin_top=10), False, False, 0)
+ self.step_labels = []
+ for s in STEPS:
+ l = Gtk.Label(label=s, xalign=0, margin_start=12, margin_top=6)
+ l.get_style_context().add_class("step")
+ box.pack_start(l, False, False, 0)
+ self.step_labels.append(l)
+ return box, []
+
+ def progress(self, step, percent):
+ def show():
+ for i, l in enumerate(self.step_labels):
+ ctx = l.get_style_context()
+ ctx.remove_class("now")
+ if i < step or (i == step and percent >= 100):
+ l.set_text("✓ " + STEPS[i])
+ ctx.add_class("done")
+ elif i == step:
+ l.set_text(" " + STEPS[i] + (" (%d%%)" % percent if i == 1 else "..."))
+ ctx.add_class("now")
+ else:
+ l.set_text(" " + STEPS[i])
+ GLib.idle_add(show)
+
+ def run_install(self, *args):
+ try:
+ install.install(*args, progress=self.progress)
+ except Exception as e:
+ print("jiggity: the installation failed:", e)
+ GLib.idle_add(self.failed, str(e))
+ return
+ GLib.idle_add(self.show_page, 4)
+ GLib.idle_add(self.countdown, 10)
+
+ def failed(self, why):
+ ui.message(self, "Chamesle couldn't be installed",
+ "%s\n\nThe details are in /var/log/jiggity.log. Click OK to restart." % why)
+ subprocess.run(["reboot"])
+
+ # restart
+ def page_done(self):
+ box = ui.page("Chamesle needs to restart to continue", "")
+ self.count_label = Gtk.Label(xalign=0, margin_top=20)
+ box.pack_start(self.count_label, False, False, 0)
+ note = Gtk.Label(label="Take out the USB stick when the screen goes dark. After the restart you'll set up "
+ "your account.", xalign=0, wrap=True, margin_top=12)
+ note.get_style_context().add_class("dim")
+ box.pack_start(note, False, False, 0)
+ return box, [("Restart now", lambda *a: subprocess.run(["reboot"]))]
+
+ def countdown(self, n):
+ self.count_label.set_text("Restarting in %d seconds" % n)
+ if n == 0:
+ subprocess.run(["reboot"])
+ return False
+ GLib.timeout_add_seconds(1, self.countdown, n - 1)
+ return False
+
+ def show_page(self, n):
+ super().show_page(n)
+ if n == 2:
+ self.fill_where()
+
+
+if __name__ == "__main__":
+ Jiggity()
+ Gtk.main()
diff --git a/overlay/usr/lib/jiggity/ui.py b/overlay/usr/lib/jiggity/ui.py
@@ -0,0 +1,148 @@
+# shared by jiggity and firstboot. runs without a window manager
+import gi
+gi.require_version("Gtk", "3.0")
+from gi.repository import Gtk, Gdk
+
+CSS = b"""
+* { font-family: Inter, "Noto Sans", sans-serif; }
+window.setup { background: linear-gradient(160deg, #0f1a2e 0%, #17407f 55%, #1f5fc4 100%); }
+.dialog { background: #ffffff; color: #1a1f2b; border-radius: 6px; box-shadow: 0 12px 40px rgba(0,0,0,.45); }
+.titlebar { background: #f3f4f6; border-bottom: 1px solid #e3e6eb; border-radius: 6px 6px 0 0; padding: 8px 14px; }
+.titlebar label { font-size: 13px; color: #1a1f2b; }
+.heading { font-size: 20px; font-weight: 600; color: #174c9f; }
+.dim { color: #5d6677; }
+.note { color: #5d6677; font-size: 13px; }
+.brand { font-size: 34px; font-weight: 300; color: #1a1f2b; }
+.footer { border-top: 1px solid #e3e6eb; padding: 12px 16px; }
+button { padding: 6px 22px; border-radius: 4px; }
+button.big { padding: 14px 40px; font-size: 17px; background: #1f5fc4; color: #ffffff; border: none; }
+button.big:hover { background: #174c9f; }
+.step { font-size: 15px; color: #5d6677; }
+.step.now { color: #1a1f2b; font-weight: 600; }
+.step.done { color: #1a1f2b; }
+.table { border: 1px solid #c9ced6; }
+treeview.view:selected { background: #cce0ff; color: #1a1f2b; }
+treeview.view:disabled { color: #9aa1ad; }
+entry { min-height: 30px; }
+"""
+
+
+def page(title, text):
+ box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6, margin=28)
+ if title:
+ h = Gtk.Label(label=title, xalign=0, wrap=True)
+ h.get_style_context().add_class("heading")
+ box.pack_start(h, False, False, 0)
+ if text:
+ t = Gtk.Label(label=text, xalign=0, wrap=True)
+ t.get_style_context().add_class("dim")
+ box.pack_start(t, False, False, 0)
+ return box
+
+
+def logo_line(name):
+ row = Gtk.Box(spacing=16, halign=Gtk.Align.CENTER)
+ row.pack_start(Gtk.Image.new_from_icon_name("chamesle-start", Gtk.IconSize.DIALOG), False, False, 0)
+ l = Gtk.Label(label=name)
+ l.get_style_context().add_class("brand")
+ row.pack_start(l, False, False, 0)
+ return row
+
+
+class SetupWindow(Gtk.Window):
+ # pages: [(box, [(label, callback), ...])], first button is the default
+ def __init__(self, title):
+ super().__init__()
+ provider = Gtk.CssProvider()
+ provider.load_from_data(CSS)
+ Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider,
+ Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
+ settings = Gtk.Settings.get_default()
+ settings.set_property("gtk-theme-name", "Adwaita")
+ settings.set_property("gtk-application-prefer-dark-theme", False)
+ self.get_style_context().add_class("setup")
+ self.set_decorated(False)
+ screen = Gdk.Screen.get_default()
+ mon = screen.get_display().get_primary_monitor() or screen.get_display().get_monitor(0)
+ geo = mon.get_geometry()
+ self.move(geo.x, geo.y)
+ self.set_default_size(geo.width, geo.height)
+ self.connect("delete-event", lambda *a: True)
+
+ outer = Gtk.Box(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER)
+ dialog = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
+ dialog.get_style_context().add_class("dialog")
+ dialog.set_size_request(min(800, geo.width - 40), min(560, geo.height - 40))
+ bar = Gtk.Box(spacing=8)
+ bar.get_style_context().add_class("titlebar")
+ bar.pack_start(Gtk.Image.new_from_icon_name("chamesle-start", Gtk.IconSize.MENU), False, False, 0)
+ bar.pack_start(Gtk.Label(label=title), False, False, 0)
+ dialog.pack_start(bar, False, False, 0)
+ self.stack = Gtk.Stack(transition_type=Gtk.StackTransitionType.CROSSFADE)
+ dialog.pack_start(self.stack, True, True, 0)
+ self.buttons = Gtk.Box(spacing=10, halign=Gtk.Align.END)
+ footer = Gtk.Box()
+ footer.get_style_context().add_class("footer")
+ footer.pack_end(self.buttons, False, False, 0)
+ dialog.pack_start(footer, False, False, 0)
+ outer.add(dialog)
+ self.add(outer)
+ self.show_all()
+ self.button_widgets = {}
+ # no wm, so nobody sets a cursor on the root window
+ cursor = Gdk.Cursor.new_from_name(screen.get_display(), "default")
+ screen.get_root_window().set_cursor(cursor)
+ self.get_window().set_cursor(cursor)
+
+ def show_page(self, n):
+ box, buttons = self.pages[n]
+ if box.get_parent() is None:
+ self.stack.add_named(box, str(n))
+ box.show_all()
+ self.stack.set_visible_child_name(str(n))
+ for child in self.buttons.get_children():
+ self.buttons.remove(child)
+ self.button_widgets = {}
+ for i, (label, callback) in reversed(list(enumerate(buttons))):
+ b = Gtk.Button(label=label)
+ b.connect("clicked", callback)
+ if i == 0:
+ b.get_style_context().add_class("suggested-action")
+ self.buttons.pack_start(b, False, False, 0)
+ self.button_widgets[label] = b
+ self.buttons.show_all()
+ self.buttons.get_parent().set_visible(bool(buttons))
+
+ def set_button_sensitive(self, label, on):
+ if label in self.button_widgets:
+ self.button_widgets[label].set_sensitive(on)
+
+
+def _dialog(parent, title, text, buttons):
+ d = Gtk.Dialog(transient_for=parent, modal=True, decorated=False)
+ d.get_style_context().add_class("dialog")
+ box = d.get_content_area()
+ box.set_spacing(10)
+ box.set_margin_top(20), box.set_margin_start(24), box.set_margin_end(24), box.set_margin_bottom(10)
+ h = Gtk.Label(label=title, xalign=0)
+ h.get_style_context().add_class("heading")
+ box.pack_start(h, False, False, 0)
+ box.pack_start(Gtk.Label(label=text, xalign=0, wrap=True, max_width_chars=52), False, False, 0)
+ for label, response in buttons:
+ d.add_button(label, response)
+ d.set_default_response(buttons[-1][1])
+ d.show_all()
+ pw, ph = parent.get_size()
+ w, h_ = d.get_size()
+ d.move((pw - w) // 2, (ph - h_) // 2)
+ r = d.run()
+ d.destroy()
+ return r
+
+
+def confirm(parent, title, text):
+ return _dialog(parent, title, text, [("Cancel", Gtk.ResponseType.CANCEL), ("OK", Gtk.ResponseType.OK)]) == Gtk.ResponseType.OK
+
+
+def message(parent, title, text):
+ _dialog(parent, title, text, [("OK", Gtk.ResponseType.OK)])