text.py (23907B)
1 #!/usr/bin/python3 2 # jiggity in text, for editions without a desktop: blue like windows setup used to be 3 # text.py install from the usb's Install entry. on the netinst it asks everything, then installs 4 # text.py firstboot the first start: time zone, network, account 5 import curses 6 import locale 7 import os 8 import re 9 import subprocess 10 import sys 11 import threading 12 import time 13 14 sys.path.insert(0, "/usr/lib/jiggity") 15 import account 16 import disks 17 import install 18 from choices import LANGUAGES, STEPS, console_keymap, keyboards 19 20 scr = None 21 # the console font has latin letters only: these languages by their english names 22 ENGLISH = {"ru_RU": "Russian", "uk_UA": "Ukrainian", "el_GR": "Greek", "ar_MA": "Arabic", "ar_EG": "Arabic (Egypt)", 23 "hi_IN": "Hindi", "ja_JP": "Japanese", "ko_KR": "Korean", "zh_CN": "Chinese (Simplified)", 24 "zh_TW": "Chinese (Traditional)"} 25 26 27 def frame(title, keys): 28 scr.bkgd(" ", curses.color_pair(1)) 29 scr.erase() 30 h, w = scr.getmaxyx() 31 scr.addstr(0, 1, " Chamesle Setup", curses.A_BOLD) 32 scr.hline(1, 1, curses.ACS_HLINE, w - 2) 33 scr.addstr(3, 4, title[:w - 6], curses.A_BOLD) 34 scr.attron(curses.color_pair(2)) 35 scr.hline(h - 1, 0, " ", w) 36 scr.addstr(h - 1, 2, keys[:w - 4]) 37 scr.attroff(curses.color_pair(2)) 38 39 40 def text(y, s): 41 # a long error message stops at the bottom of the screen instead of crashing it 42 h, w = scr.getmaxyx() 43 words, line = s.split(), "" 44 for word in words: 45 if len(line) + len(word) + 1 > w - 10: 46 if y < h - 2: 47 scr.addstr(y, 4, line[:w - 8]) 48 y, line = y + 1, "" 49 line = (line + " " + word).strip() 50 if line and y < h - 2: 51 scr.addstr(y, 4, line[:w - 8]) 52 return y + 2 53 54 55 # a list to pick from. type to jump. returns the index, or None for esc 56 def choose(title, note, items, sel=0, disabled=()): 57 top, typed = 0, "" 58 while True: 59 frame(title, "ENTER=Continue ESC=Back Type to search") 60 y = text(5, note) if note else 5 61 h, w = scr.getmaxyx() 62 rows = h - y - 3 63 if sel < top: 64 top = sel 65 if sel >= top + rows: 66 top = sel - rows + 1 67 for i in range(top, min(len(items), top + rows)): 68 attr = curses.color_pair(3) if i == sel else curses.color_pair(1) 69 if i in disabled: 70 attr |= curses.A_DIM 71 scr.addstr(y + i - top, 6, items[i][:w - 12].ljust(w - 12), attr) 72 # the cursor on the chosen line, hidden: the screen reader reads the line it's on 73 scr.move(y + sel - top, 6) 74 k = scr.get_wch() 75 if k in ("\n", curses.KEY_ENTER) and sel not in disabled: 76 return sel 77 if k == "\x1b": 78 return None 79 if k == curses.KEY_UP: 80 sel = max(0, sel - 1) 81 elif k == curses.KEY_DOWN: 82 sel = min(len(items) - 1, sel + 1) 83 elif k == curses.KEY_PPAGE: 84 sel = max(0, sel - rows) 85 elif k == curses.KEY_NPAGE: 86 sel = min(len(items) - 1, sel + rows) 87 elif isinstance(k, str) and k.isprintable(): 88 typed += k.lower() 89 for i, it in enumerate(items): 90 if typed in it.lower(): 91 sel = i 92 break 93 else: 94 typed = k.lower() 95 elif k in (curses.KEY_BACKSPACE, "\x7f"): 96 typed = typed[:-1] 97 98 99 # a line of input. returns the text, or None for esc 100 def ask(title, note, label, secret=False, value=""): 101 curses.curs_set(1) 102 while True: 103 frame(title, "ENTER=Continue ESC=Back") 104 y = text(5, note) if note else 5 105 scr.addstr(y, 4, label) 106 x = 6 + len(label) 107 shown = "*" * len(value) if secret else value 108 scr.addstr(y, x, shown.ljust(32), curses.color_pair(4)) 109 scr.move(y, x + len(shown)) 110 k = scr.get_wch() 111 if k in ("\n", curses.KEY_ENTER): 112 curses.curs_set(0) 113 return value 114 if k == "\x1b": 115 curses.curs_set(0) 116 return None 117 if k in (curses.KEY_BACKSPACE, "\x7f", "\b"): 118 value = value[:-1] 119 elif isinstance(k, str) and k.isprintable() and len(value) < 64: 120 value += k 121 122 123 def say(title, note, keys="ENTER=Continue"): 124 frame(title, keys) 125 text(5, note) 126 scr.refresh() 127 return scr.get_wch() 128 129 130 def yes(title, note): 131 while True: 132 k = say(title, note, "Y=Yes N=No") 133 if k in ("y", "Y"): 134 return True 135 if k in ("n", "N", "\x1b"): 136 return False 137 138 139 # the passphrase and password are typed with the keyboard picked, the same one the boot and the desktop use 140 def use_keyboard(layout, variant): 141 subprocess.run(["loadkeys", console_keymap(layout, variant)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) 142 143 144 def netinst(): 145 try: 146 return open("/usr/share/chamesle/edition").read().strip() == "netinst" 147 except OSError: 148 return False 149 150 151 # what the netinst offers: the editions, the way the website lists them 152 DESKTOPS = [ 153 ("xfce", "Light and quick, set up like Windows. The one to start with."), 154 ("mate", "Very light and rock solid, for older machines."), 155 ("cinnamon", "Linux Mint's desktop, the most polished Windows-style one."), 156 ("gnome", "Modern and clean, with an overview of your windows and a dock."), 157 ("kde", "Familiar at first, and you can change almost anything about it."), 158 ("astro", "GNOME with the sky apps: Stellarium, KStars, Siril and Gpredict."), 159 ("windowmaker", "The NeXTSTEP look: a dock, and the menu wherever you right-click."), 160 ("tty", "The console, with floating windows on top, on ttywm."), 161 ("server", "No desktop. SSH is on from the first start."), 162 ] 163 164 165 def edition_name(e): 166 try: 167 for line in open("/usr/share/chamesle/editions/%s/edition" % e): 168 if line.startswith("name="): 169 return line[5:].strip() 170 except OSError: 171 pass 172 return e 173 174 175 def nm(*args): 176 return subprocess.run(["nmcli"] + list(args), text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 177 178 179 def wifi_list(): 180 r = subprocess.run(["nmcli", "-t", "-f", "SSID,SIGNAL,SECURITY", "device", "wifi", "list", "--rescan", "yes"], 181 text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) 182 seen, out = set(), [] 183 for line in r.stdout.splitlines(): 184 f = re.split(r"(?<!\\):", line) 185 if len(f) < 3 or not f[0] or f[0] in seen: 186 continue 187 seen.add(f[0]) 188 out.append((f[0].replace("\\:", ":"), int(f[1] or 0), f[2])) 189 return sorted(out, key=lambda n: -n[1]) 190 191 192 # online by cable, or by the wi-fi picked here. False for esc 193 def network(): 194 while True: 195 frame("Connecting to the internet", "") 196 text(5, "Looking for a connection...") 197 scr.refresh() 198 for _ in range(10): 199 if account.online(): 200 say("Connected", "Chamesle is online, so it can download the desktop you pick.") 201 return True 202 time.sleep(0.5) 203 nets = wifi_list() 204 items = ["%-40s %3d%%%s" % (n[:40], sig, " locked" if sec else "") for n, sig, sec in nets] 205 items += ["Look again", "I plugged in a cable"] 206 i = choose("Connecting to the internet", "Chamesle downloads your desktop while it installs, so it needs the " 207 "internet. Plug in a cable, or pick your Wi-Fi.", items) 208 if i is None: 209 return False 210 if i >= len(nets): 211 continue 212 ssid, sig, sec = nets[i] 213 cmd = ["device", "wifi", "connect", ssid] 214 if sec: 215 pw = ask("Connecting to %s" % ssid, "", "Wi-Fi password:", True) 216 if pw is None: 217 continue 218 cmd += ["password", pw] 219 frame("Connecting to %s" % ssid, "") 220 text(5, "Connecting...") 221 scr.refresh() 222 if nm(*cmd).returncode: 223 say("Couldn't connect to %s" % ssid, "Check the password and try again.") 224 225 226 # booted from the usb's "with a screen reader" entry 227 def speech(): 228 try: 229 return "chamesle.speech=1" in open("/proc/cmdline").read().split() 230 except OSError: 231 return False 232 233 234 ACCESS = [("reader", "Screen reader", "reads the screen aloud, Super+Alt+S turns it on or off"), 235 ("contrast", "High contrast", "strong colors that are easier to tell apart"), 236 ("text", "Large text", "bigger text everywhere")] 237 238 239 def access_text(access): 240 on = [name.lower() for k, name, _ in ACCESS if access.get(k)] 241 return ", ".join(on) if on else "none" 242 243 244 # a list of things to turn on or off, and Continue at the bottom 245 def access_page(access): 246 sel = len(ACCESS) 247 while True: 248 frame("Seeing the screen", "ENTER=Turn on or off ESC=Back") 249 y = text(5, "Anything here to make it easier? You can change these later in Accessibility, in the menu.") 250 h, w = scr.getmaxyx() 251 for i, (k, name, what) in enumerate(ACCESS): 252 line = "[%s] %-15s %s" % ("x" if access.get(k) else " ", name, what) 253 scr.addstr(y + i, 6, line[:w - 12].ljust(w - 12), curses.color_pair(3) if i == sel else curses.color_pair(1)) 254 scr.addstr(y + len(ACCESS) + 1, 6, "Continue".ljust(w - 12), curses.color_pair(3) if sel == len(ACCESS) else curses.color_pair(1)) 255 scr.move(y + sel + (sel == len(ACCESS)), 6) 256 k = scr.get_wch() 257 if k == "\x1b": 258 return False 259 if k == curses.KEY_UP: 260 sel = max(0, sel - 1) 261 elif k in (curses.KEY_DOWN, "\t"): 262 sel = min(len(ACCESS), sel + 1) 263 elif k in ("\n", curses.KEY_ENTER, " "): 264 if sel == len(ACCESS): 265 return True 266 key = ACCESS[sel][0] 267 access[key] = not access.get(key) 268 269 270 def run_netinst(): 271 kbds = keyboards() 272 us = next((i for i, k in enumerate(kbds) if k[1] == "us" and not k[2]), 0) 273 zs = account.zones() 274 zone_names = [z.replace("_", " ").replace("/", " / ") for z in zs] 275 c = {"lang": 0, "kb": us, "zone": zs.index("Europe/London") if "Europe/London" in zs else 0, "name": "", 276 "user": "", "pw": "", "host": "", "row": None, "passphrase": None, "desktop": 0, 277 "access": {"reader": speech()}} 278 279 def p_lang(): 280 i = choose("Language to install", "", [ENGLISH.get(code, n) for n, code in LANGUAGES], c["lang"]) 281 if i is None: 282 return False 283 c["lang"] = i 284 return True 285 286 def p_keyboard(): 287 i = choose("Keyboard", "", [k[0] for k in kbds], c["kb"]) 288 if i is None: 289 return False 290 c["kb"] = i 291 use_keyboard(*kbds[i][1:]) 292 return True 293 294 def p_zone(): 295 i = choose("Your time zone", "It sets your clock. Type a city to find yours.", zone_names, c["zone"]) 296 if i is None: 297 return False 298 c["zone"] = i 299 return True 300 301 def p_you(): 302 name = ask("Who's going to use this PC?", "", "Your name:", value=c["name"]) 303 if name is None: 304 return False 305 while True: 306 user = ask("Who's going to use this PC?", "Lowercase letters and numbers, starting with a letter.", 307 "Username:", value=c["user"] or account.username_from(name)) 308 if user is None: 309 return False 310 bad = account.bad_username(user) 311 if user and not bad: 312 break 313 say("Who's going to use this PC?", bad or "Pick a username.") 314 while True: 315 pw = ask("Who's going to use this PC?", "", "Password:", True) 316 if pw is None: 317 return False 318 if not pw: 319 continue 320 if ask("Who's going to use this PC?", "Type it again.", "Confirm: ", True) == pw: 321 break 322 say("Who's going to use this PC?", "The passwords don't match.") 323 while True: 324 host = ask("Name this computer", "How it shows up to other computers on the network.", 325 "Computer name:", value=c["host"] or account.hostname_from(user)) 326 if host is None: 327 return False 328 bad = account.bad_hostname(host) 329 if not bad: 330 break 331 say("Name this computer", bad) 332 c.update(name=name, user=user, pw=pw, host=host) 333 return True 334 335 def p_disk(): 336 while True: 337 rows = disks.scan() 338 if not rows: 339 say("No drives found", "Check that the drive is connected, then press ENTER to look again.") 340 continue 341 items = [] 342 for r in rows: 343 free = " %s free" % disks.size_text(r.free) if r.kind != "drive" else "" 344 items.append("%s%-40s %9s%s %s" % ("" if r.kind == "drive" else " ", r.label[:40], 345 disks.size_text(r.total), free, r.type_text)) 346 off = [i for i, r in enumerate(rows) if not r.usable] 347 first = next((i for i in range(len(rows)) if i not in off), 0) 348 i = choose("Where do you want to install Chamesle?", 349 "Pick a drive to use all of it, or its unallocated space to keep what's on it. Chamesle needs " 350 "at least %s. Nothing changes until the last step." % disks.size_text(disks.MIN_SIZE), 351 items, first, off) 352 if i is None: 353 return False 354 c["row"] = rows[i] 355 break 356 c["passphrase"] = None 357 # esc at the passphrase goes back to the question, it doesn't quietly install without encryption 358 while c["passphrase"] is None and yes("Encrypt Chamesle?", "With a passphrase you type every time the computer starts. If you forget it, " 359 "your files can't be recovered."): 360 while True: 361 p1 = ask("Encrypt Chamesle", "At least 8 characters.", "Passphrase:", True) 362 if p1 is None: 363 break 364 if len(p1) < 8: 365 say("Encrypt Chamesle", "The passphrase needs at least 8 characters.") 366 continue 367 if ask("Encrypt Chamesle", "Type it again.", "Confirm: ", True) != p1: 368 say("Encrypt Chamesle", "The passphrases don't match.") 369 continue 370 c["passphrase"] = p1 371 break 372 return True 373 374 def p_desktop(): 375 items = ["%-12s %s" % (edition_name(e), d) for e, d in DESKTOPS] 376 i = choose("Pick your desktop", "You can add another one later with: sudo chamesle-desktop NAME", items, 377 c["desktop"]) 378 if i is None: 379 return False 380 c["desktop"] = i 381 return True 382 383 def p_summary(): 384 row = c["row"] 385 where = ("all of %s (everything on it is erased)" % row.label.split(":")[0] if row.kind == "drive" 386 else "the unallocated space on %s" % row.label.split(":")[0]) 387 lines = [("Language", ENGLISH.get(LANGUAGES[c["lang"]][1], LANGUAGES[c["lang"]][0])), 388 ("Keyboard", kbds[c["kb"]][0]), ("Time zone", zone_names[c["zone"]]), 389 ("You", "%s (%s)" % (c["name"] or c["user"], c["user"])), ("Computer name", c["host"]), 390 ("Install on", where), ("Encrypted", "yes" if c["passphrase"] else "no"), 391 ("Desktop", edition_name(DESKTOPS[c["desktop"]][0])), ("Accessibility", access_text(c["access"]))] 392 while True: 393 frame("Ready to install", "ENTER=Install ESC=Back") 394 y = text(5, "Check this. When you press ENTER, Chamesle installs and the disk is changed. It needs nothing " 395 "more from you until it's done.") 396 for k, v in lines: 397 scr.addstr(y, 6, "%-15s %s" % (k + ":", v)) 398 y += 1 399 scr.refresh() 400 k = scr.get_wch() 401 if k in ("\n", curses.KEY_ENTER): 402 return True 403 if k == "\x1b": 404 return False 405 406 pages = [p_lang, p_keyboard, network, p_zone, p_you, p_disk, p_desktop, lambda: access_page(c["access"]), p_summary] 407 n = 0 408 while n < len(pages): 409 if pages[n](): 410 n += 1 411 else: 412 n = max(0, n - 1) 413 414 desktop = DESKTOPS[c["desktop"]][0] 415 user = {"zone": zs[c["zone"]], "user": c["user"], "name": c["name"], "password": c["pw"], "host": c["host"]} 416 steps = STEPS[:2] + ["Downloading and installing %s" % edition_name(desktop)] + STEPS[2:] 417 work(steps, c["row"], c["passphrase"], LANGUAGES[c["lang"]][1], kbds[c["kb"]][1:], desktop, user, c["access"]) 418 say("Chamesle is installed", "Take out the USB stick, then press ENTER to restart into your new %s desktop." 419 % edition_name(desktop) if desktop != "server" else 420 "Take out the USB stick, then press ENTER to restart. Sign in with your username, or over SSH.") 421 subprocess.run(["reboot"]) 422 423 424 # installs with a screen of steps. returns when it's done, or says what went wrong and restarts 425 def work(steps, row, passphrase, language, keyboard, desktop=None, user=None, access=None): 426 state = {"step": 0, "percent": 0, "error": None, "done": False} 427 428 def go(): 429 try: 430 install.install(row, passphrase, language, keyboard, progress=progress, desktop=desktop, user=user, 431 access=access) 432 except Exception as e: 433 print("jiggity: the installation failed:", e, file=sys.stderr) 434 state["error"] = str(e) 435 state["done"] = True 436 437 def progress(step, percent): 438 state["step"], state["percent"] = step, percent 439 440 threading.Thread(target=go, daemon=True).start() 441 scr.timeout(500) 442 while not state["done"]: 443 frame("Installing Chamesle", "Please wait") 444 for i, s in enumerate(steps): 445 if i < state["step"] or (i == state["step"] and state["percent"] >= 100): 446 line = "[x] " + s 447 elif i == state["step"]: 448 line = "[ ] " + s + (" (%d%%)" % state["percent"] if s.startswith(("Copying", "Downloading")) else "...") 449 else: 450 line = "[ ] " + s 451 scr.addstr(6 + i, 6, line, curses.A_BOLD if i == state["step"] else 0) 452 scr.refresh() 453 try: 454 scr.get_wch() 455 except curses.error: 456 pass 457 scr.timeout(-1) 458 if state["error"]: 459 say("Chamesle couldn't be installed", "%s. The details are in /var/log/jiggity.log. Press ENTER to restart." 460 % state["error"].rstrip(".")) 461 subprocess.run(["reboot"]) 462 sys.exit(1) 463 464 465 def run_install(): 466 if netinst(): 467 return run_netinst() 468 lang = choose("Language to install", "", [ENGLISH.get(c, n) for n, c in LANGUAGES]) 469 if lang is None: 470 lang = 0 471 kbds = keyboards() 472 us = next((i for i, k in enumerate(kbds) if k[1] == "us" and not k[2]), 0) 473 kb = choose("Keyboard", "", [k[0] for k in kbds], us) 474 if kb is None: 475 kb = us 476 use_keyboard(*kbds[kb][1:]) 477 while True: 478 rows = disks.scan() 479 if not rows: 480 say("No drives found", "Check that the drive is connected, then press ENTER to look again.") 481 continue 482 items = [] 483 for r in rows: 484 free = " %s free" % disks.size_text(r.free) if r.kind != "drive" else "" 485 items.append("%s%-40s %9s%s %s" % ("" if r.kind == "drive" else " ", r.label[:40], 486 disks.size_text(r.total), free, r.type_text)) 487 off = [i for i, r in enumerate(rows) if not r.usable] 488 first = next((i for i in range(len(rows)) if i not in off), 0) 489 i = choose("Where do you want to install Chamesle?", 490 "Pick a drive to use all of it, or its unallocated space to keep what's on it. Chamesle needs at " 491 "least %s." % disks.size_text(disks.MIN_SIZE), items, first, off) 492 if i is None: 493 continue 494 row = rows[i] 495 if row.kind == "drive" and not yes("Erase %s?" % row.label.split(":")[0], 496 "Everything on this drive will be deleted, and Chamesle will be installed " 497 "on it. This can't be undone."): 498 continue 499 break 500 passphrase = None 501 # esc at the passphrase goes back to the question, it doesn't quietly install without encryption 502 while passphrase is None and yes("Encrypt Chamesle?", "With a passphrase you type every time the computer starts. If you forget it, your " 503 "files can't be recovered."): 504 while True: 505 p1 = ask("Encrypt Chamesle", "At least 8 characters.", "Passphrase:", True) 506 if p1 is None: 507 break 508 if len(p1) < 8: 509 say("Encrypt Chamesle", "The passphrase needs at least 8 characters.") 510 continue 511 if ask("Encrypt Chamesle", "Type it again.", "Confirm: ", True) != p1: 512 say("Encrypt Chamesle", "The passphrases don't match.") 513 continue 514 passphrase = p1 515 break 516 517 work(STEPS, row, passphrase, LANGUAGES[lang][1], kbds[kb][1:]) 518 say("Chamesle needs to restart to continue", "Take out the USB stick when the screen goes dark. After the " 519 "restart you'll set up your account. Press ENTER to restart.") 520 subprocess.run(["reboot"]) 521 522 523 def run_firstboot(): 524 while True: 525 try: 526 return firstboot_once() 527 except RuntimeError as e: 528 say("That didn't work", "%s. Press ENTER to try again." % str(e).rstrip(".")) 529 530 531 def firstboot_once(): 532 zs = account.zones() 533 names = [z.replace("_", " ").replace("/", " / ") for z in zs] 534 while True: 535 z = choose("Let's start with your time zone", "It sets your clock. Type a city to find yours.", names) 536 if z is not None: 537 break 538 if not account.online() and yes("Not connected", "You need the internet for updates. Set up a network now?"): 539 curses.endwin() 540 subprocess.run(["nmtui-connect"]) 541 scr.refresh() 542 while True: 543 name = ask("Who's going to use this PC?", "", "Your name:") or "" 544 user = ask("Who's going to use this PC?", "Lowercase letters and numbers, starting with a letter.", 545 "Username:", value=account.username_from(name)) 546 if not user: 547 continue 548 bad = account.bad_username(user) 549 if bad: 550 say("Who's going to use this PC?", bad) 551 continue 552 pw = ask("Who's going to use this PC?", "", "Password:", True) 553 if not pw: 554 continue 555 if ask("Who's going to use this PC?", "Type it again.", "Confirm: ", True) != pw: 556 say("Who's going to use this PC?", "The passwords don't match.") 557 continue 558 break 559 frame("Just a moment...", "") 560 scr.refresh() 561 account.make(zs[z], user, name, pw) 562 563 564 def main(s): 565 global scr 566 scr = s 567 curses.use_default_colors() 568 curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) 569 curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE) 570 curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_WHITE) 571 curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_CYAN) 572 curses.curs_set(0) 573 scr.keypad(True) 574 if sys.argv[1:2] == ["install"]: 575 run_install() 576 else: 577 run_firstboot() 578 579 580 if __name__ == "__main__": 581 # what the install prints goes to the log, not over the screen 582 log = open("/var/log/jiggity.log", "a", buffering=1) 583 os.dup2(log.fileno(), 2) 584 sys.stdout = sys.stderr = log 585 locale.setlocale(locale.LC_ALL, "") 586 curses.set_escdelay(25) 587 curses.wrapper(main)