chamesle

chamesle.org: the site of Chamesle, a small Linux distribution
git clone https://github.com/tortr-rs/chamesle
Log | Files | Refs | README

firstboot.py (7996B)


      1 #!/usr/bin/python3
      2 # first boot setup: time zone, wi-fi, user account
      3 import re
      4 import subprocess
      5 import sys
      6 import threading
      7 
      8 import gi
      9 gi.require_version("Gtk", "3.0")
     10 from gi.repository import Gtk, GLib
     11 
     12 sys.path.insert(0, "/usr/lib/jiggity")
     13 import account
     14 import ui
     15 from account import zones, online
     16 from ui import _
     17 
     18 
     19 # button labels: kept in english to find the buttons by, translated when they're drawn
     20 def N_(s):
     21     return s
     22 
     23 
     24 class FirstBoot(ui.SetupWindow):
     25     def __init__(self):
     26         super().__init__("Chamesle")
     27         self.pages = [self.page_zone(), self.page_wifi(), self.page_account(), self.page_wait()]
     28         self.show_page(0)
     29 
     30     # time zone
     31     def page_zone(self):
     32         box = ui.page(_("Let's start with your time zone. Is this the right one?"),
     33                       _("It sets your clock. Type a city to find yours."))
     34         self.zone_filter = Gtk.SearchEntry(margin_top=10)
     35         box.pack_start(self.zone_filter, False, False, 0)
     36         self.zone_store = Gtk.ListStore(str, str)
     37         for z in zones():
     38             self.zone_store.append([z.replace("_", " ").replace("/", " / "), z])
     39         filt = self.zone_store.filter_new()
     40         filt.set_visible_func(lambda m, it, d: self.zone_filter.get_text().lower() in m[it][0].lower())
     41         self.zone_filter.connect("search-changed", lambda *a: filt.refilter())
     42         view = Gtk.TreeView(model=filt, headers_visible=False)
     43         view.append_column(Gtk.TreeViewColumn("", Gtk.CellRendererText(), text=0))
     44         self.zone_sel = view.get_selection()
     45         self.zone_sel.connect("changed", lambda s: self.set_button_sensitive("Yes", s.get_selected()[1] is not None))
     46         scroll = Gtk.ScrolledWindow(min_content_height=260)
     47         scroll.add(view)
     48         scroll.get_style_context().add_class("table")
     49         box.pack_start(scroll, True, True, 6)
     50         return box, [(N_("Yes"), self.after_zone)]
     51 
     52     def after_zone(self, *a):
     53         model, it = self.zone_sel.get_selected()
     54         self.zone = model[it][1]
     55         self.show_page(2 if online() else 1)
     56 
     57     # wi-fi
     58     def page_wifi(self):
     59         box = ui.page(_("Let's connect you to a network"), _("You need the internet for updates and the app store."))
     60         self.wifi_store = Gtk.ListStore(str, str, str)
     61         view = Gtk.TreeView(model=self.wifi_store, headers_visible=False)
     62         view.append_column(Gtk.TreeViewColumn("", Gtk.CellRendererText(), text=0))
     63         view.append_column(Gtk.TreeViewColumn("", Gtk.CellRendererText(xalign=1), text=1))
     64         self.wifi_sel = view.get_selection()
     65         self.wifi_sel.connect("changed", self.on_wifi)
     66         scroll = Gtk.ScrolledWindow(min_content_height=200, margin_top=10)
     67         scroll.add(view)
     68         scroll.get_style_context().add_class("table")
     69         box.pack_start(scroll, True, True, 0)
     70         row = Gtk.Box(spacing=10, margin_top=8)
     71         row.pack_start(Gtk.Label(label=_("Password:")), False, False, 0)
     72         self.wifi_pass = Gtk.Entry(visibility=False, width_chars=28)
     73         row.pack_start(self.wifi_pass, False, False, 0)
     74         box.pack_start(row, False, False, 0)
     75         self.wifi_note = Gtk.Label(xalign=0, wrap=True)
     76         self.wifi_note.get_style_context().add_class("note")
     77         box.pack_start(self.wifi_note, False, False, 0)
     78         return box, [(N_("Connect"), self.on_connect), (N_("Skip for now"), lambda *a: self.show_page(2))]
     79 
     80     def fill_wifi(self):
     81         self.wifi_store.clear()
     82         r = subprocess.run(["nmcli", "-t", "-f", "SSID,SIGNAL,SECURITY", "device", "wifi", "list", "--rescan", "yes"],
     83                            text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
     84         seen = set()
     85         for line in r.stdout.splitlines():
     86             f = re.split(r"(?<!\\):", line)
     87             if len(f) < 3 or not f[0] or f[0] in seen:
     88                 continue
     89             seen.add(f[0])
     90             self.wifi_store.append([f[0].replace("\\:", ":"), "%s%%%s" % (f[1], "  \U0001F512" if f[2] else ""), f[2]])
     91         self.wifi_note.set_text("" if len(self.wifi_store) else _("No Wi-Fi networks found. You can skip this and connect later."))
     92         self.on_wifi()
     93 
     94     def on_wifi(self, *a):
     95         self.set_button_sensitive("Connect", self.wifi_sel.get_selected()[1] is not None)
     96 
     97     def on_connect(self, *a):
     98         model, it = self.wifi_sel.get_selected()
     99         ssid, secure = model[it][0], model[it][2]
    100         cmd = ["nmcli", "device", "wifi", "connect", ssid]
    101         if secure:
    102             cmd += ["password", self.wifi_pass.get_text()]
    103         self.wifi_note.set_text(_("Connecting to %s...") % ssid)
    104 
    105         def go():
    106             ok = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
    107             GLib.idle_add(lambda: self.show_page(2) if ok else
    108                           self.wifi_note.set_text(_("Couldn't connect to %s. Check the password and try again.") % ssid))
    109         threading.Thread(target=go, daemon=True).start()
    110 
    111     # the account
    112     def page_account(self):
    113         box = ui.page(_("Who's going to use this PC?"), "")
    114         grid = Gtk.Grid(column_spacing=12, row_spacing=10, margin_top=14)
    115         self.name = Gtk.Entry(width_chars=30, placeholder_text=_("Your name"))
    116         self.user = Gtk.Entry(width_chars=30)
    117         self.pw1 = Gtk.Entry(width_chars=30, visibility=False)
    118         self.pw2 = Gtk.Entry(width_chars=30, visibility=False)
    119         for r, (text, e) in enumerate([(_("Name:"), self.name), (_("Username:"), self.user), (_("Password:"), self.pw1),
    120                                        (_("Confirm password:"), self.pw2)]):
    121             grid.attach(Gtk.Label(label=text, xalign=1), 0, r, 1, 1)
    122             grid.attach(e, 1, r, 1, 1)
    123             e.connect("changed", self.on_account)
    124         self.user_edited = False
    125         self.user.connect("key-press-event", lambda *a: setattr(self, "user_edited", True))
    126         box.pack_start(grid, False, False, 0)
    127         self.account_note = Gtk.Label(xalign=0, wrap=True, margin_top=10)
    128         self.account_note.get_style_context().add_class("note")
    129         box.pack_start(self.account_note, False, False, 0)
    130         return box, [(N_("Next"), self.on_done), (N_("Back"), lambda *a: self.show_page(0))]
    131 
    132     def on_account(self, entry):
    133         if entry is self.name and not self.user_edited:
    134             self.user.set_text(account.username_from(self.name.get_text()))
    135         u, p1, p2 = self.user.get_text(), self.pw1.get_text(), self.pw2.get_text()
    136         note = account.bad_username(u)
    137         ok = not note
    138         if ok and p2 and p1 != p2:
    139             note, ok = _("The passwords don't match."), False
    140         self.account_note.set_text(note)
    141         self.set_button_sensitive("Next", ok and bool(u and p1 and p1 == p2))
    142 
    143     def on_done(self, *a):
    144         self.show_page(3)
    145         threading.Thread(target=self.make_account, daemon=True).start()
    146 
    147     # just a moment
    148     def page_wait(self):
    149         box = ui.page(_("Just a moment..."), "")
    150         spinner = Gtk.Spinner(margin_top=40, halign=Gtk.Align.CENTER)
    151         spinner.set_size_request(48, 48)
    152         spinner.start()
    153         box.pack_start(spinner, False, False, 0)
    154         return box, []
    155 
    156     def make_account(self):
    157         try:
    158             account.make(self.zone, self.user.get_text(), self.name.get_text(), self.pw1.get_text())
    159         except Exception as e:
    160             print("firstboot:", e)
    161             GLib.idle_add(self.account_failed, str(e))
    162             return
    163         GLib.idle_add(Gtk.main_quit)
    164 
    165     def account_failed(self, why):
    166         self.show_page(2)
    167         self.account_note.set_text(_("That didn't work (%s). Try another username.") % why)
    168 
    169     def show_page(self, n):
    170         super().show_page(n)
    171         if n == 1:
    172             GLib.idle_add(self.fill_wifi)
    173         if n == 0:
    174             self.set_button_sensitive("Yes", False)
    175         if n == 2:
    176             self.set_button_sensitive("Next", False)
    177             self.name.grab_focus()
    178 
    179 
    180 if __name__ == "__main__":
    181     FirstBoot()
    182     Gtk.main()