chamesle-drivers (9383B)
1 #!/usr/bin/python3 2 # Driver Manager: finds hardware that works better with an extra driver and installs it 3 import gettext, os, re, subprocess, threading 4 5 import gi 6 gi.require_version("Gtk", "4.0") 7 gi.require_version("Adw", "1") 8 from gi.repository import Adw, GLib, Gtk 9 10 gettext.textdomain("chamesle") 11 _ = gettext.gettext 12 N_ = lambda s: s 13 14 HELPER = "/usr/libexec/chamesle-store-helper" 15 16 # nvidia chips by codename prefix (as named in the pci id database) -> the driver series that supports them 17 NVIDIA = [ 18 (r"^GF", "nvidia390", N_("GeForce 400 and 500 series")), 19 (r"^GK", "nvidia470", N_("GeForce 600 and 700 series")), 20 (r"^(GM|GP|GV)", "nvidia580", N_("GeForce 900 and 1000 series")), 21 (r"^(TU|GA|AD|GB|GH)", "nvidia", N_("GeForce 16, RTX and newer")), 22 ] 23 # broadcom wifi chips the in-kernel drivers don't handle, the wl driver does 24 BROADCOM_WL = {"4311", "4312", "4313", "4315", "4328", "4329", "432a", "432b", "432c", "432d", 25 "4353", "4357", "4358", "4359", "4365", "43a0", "43b1"} 26 27 28 def run(cmd): 29 return subprocess.run(cmd, capture_output=True, text=True).stdout 30 31 32 def installed(): 33 return set(run(["apk", "info", "--quiet"]).split()) 34 35 36 def pci_devices(): 37 # lspci -mm -nn: slot "class [code]" "vendor [id]" "device [id]" ... 38 out = [] 39 for line in run(["lspci", "-mm", "-nn"]).splitlines(): 40 f = re.findall(r'"([^"]*)"', line) 41 if len(f) < 3: 42 continue 43 slot = line.split()[0] 44 cls = re.search(r"\[(\w+)\]$", f[0]) 45 ven = re.search(r"\[(\w+)\]$", f[1]) 46 dev = re.search(r"\[(\w+)\]$", f[2]) 47 bound = os.path.exists("/sys/bus/pci/devices/0000:%s/driver" % slot) 48 out.append({"class": cls.group(1) if cls else "", "vendor": ven.group(1) if ven else "", 49 "device": dev.group(1) if dev else "", "name": re.sub(r"\s*\[\w+\]$", "", f[2]), 50 "bound": bound}) 51 return out 52 53 54 def dmi(key): 55 try: 56 return open("/sys/class/dmi/id/" + key).read().strip() 57 except OSError: 58 return "" 59 60 61 def find(): 62 """what this computer could use: [(title, description, [(label, package or None, recommended)])]""" 63 found = [] 64 for d in pci_devices(): 65 if d["vendor"] == "10de" and d["class"].startswith("03"): 66 chip = re.match(r"(\w+?\d+)", d["name"]) 67 pkg = desc = None 68 for pat, p, what in NVIDIA: 69 if chip and re.match(pat, chip.group(1)): 70 pkg, desc = p, what 71 title = "NVIDIA " + re.sub(r"^\w+\s*", "", d["name"]).strip("[] ") 72 if pkg: 73 found.append((title, _("The NVIDIA driver is faster and needed for most games (%s).") % _(desc), 74 [(_("NVIDIA driver (%s)") % pkg, pkg, True), (_("Open source driver (nouveau)"), None, False)])) 75 else: 76 found.append((title, _("This card is too old for the NVIDIA driver, the open source one is used."), 77 [(_("Open source driver (nouveau)"), None, True)])) 78 elif d["vendor"] == "14e4" and d["class"] == "0280" and d["device"] in BROADCOM_WL: 79 found.append(("Broadcom " + d["name"], _("This Wi-Fi chip needs Broadcom's driver to work."), 80 [(_("Broadcom STA driver (wl)"), "broadcom-wl-dkms", True), 81 (_("Don't install it"), None, False)])) 82 vendor, product = dmi("sys_vendor"), dmi("product_name") 83 if "VirtualBox" in product or "innotek" in vendor: 84 found.append(("VirtualBox", _("Shared clipboard, window resizing and shared folders with your PC."), 85 [(_("VirtualBox guest additions"), "virtualbox-ose-guest", True), (_("None"), None, False)])) 86 elif "VMware" in vendor or "VMware" in product: 87 found.append(("VMware", _("Shared clipboard, window resizing and better graphics."), 88 [(_("VMware tools"), "open-vm-tools", True), (_("None"), None, False)])) 89 if re.search(r"ID 03f0:", run(["lsusb"])): 90 found.append((_("HP printer or scanner"), _("HP's own drivers support more printers and scanners."), 91 [(_("HP drivers (hplip)"), "hplip", True), (_("None"), None, False)])) 92 return found 93 94 95 class Drivers(Adw.Application): 96 def __init__(self): 97 super().__init__(application_id="org.chamesle.Drivers") 98 99 def do_activate(self): 100 if self.get_active_window(): 101 self.get_active_window().present() 102 return 103 self.win = Adw.ApplicationWindow(application=self, title=_("Driver Manager"), default_width=720, default_height=560) 104 self.toasts = Adw.ToastOverlay() 105 view = Adw.ToolbarView() 106 view.add_top_bar(Adw.HeaderBar()) 107 self.apply = Gtk.Button(label=_("Apply changes"), css_classes=["suggested-action", "pill"], sensitive=False, 108 halign=Gtk.Align.CENTER, margin_top=6, margin_bottom=12) 109 self.apply.connect("clicked", lambda *a: self.do_apply()) 110 self.body = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=18) 111 page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) 112 page.append(Gtk.ScrolledWindow(vexpand=True, hscrollbar_policy=Gtk.PolicyType.NEVER, 113 child=Adw.Clamp(child=self.body, maximum_size=640, margin_top=18, 114 margin_start=12, margin_end=12, margin_bottom=12))) 115 page.append(self.apply) 116 view.set_content(page) 117 self.toasts.set_child(view) 118 self.win.set_content(self.toasts) 119 spin = Adw.StatusPage(title=_("Looking at your hardware")) 120 spin.set_child(Gtk.Spinner(spinning=True, width_request=32, height_request=32)) 121 self.body.append(spin) 122 self.win.present() 123 threading.Thread(target=lambda: GLib.idle_add(self.show, find(), installed()), daemon=True).start() 124 125 def show(self, found, have): 126 while self.body.get_first_child(): 127 self.body.remove(self.body.get_first_child()) 128 self.choices = [] 129 if not found: 130 self.body.append(Adw.StatusPage(icon_name="emblem-ok-symbolic", title=_("Nothing to do"), 131 description=_("Your hardware works with the drivers that are already installed."))) 132 return 133 for title, desc, options in found: 134 group = Adw.PreferencesGroup(title=GLib.markup_escape_text(title), description=desc) 135 first = None 136 current = next((i for i, (_, p, _) in enumerate(options) if p and p in have), None) 137 if current is None: 138 current = next(i for i, (_, p, _) in enumerate(options) if p is None) if any(p is None for _, p, _ in options) else 0 139 for i, (label, pkg, rec) in enumerate(options): 140 check = Gtk.CheckButton(group=first, active=(i == current)) 141 first = first or check 142 row = Adw.ActionRow(title=label, activatable_widget=check, 143 subtitle=" ยท ".join(s for s in (_("Recommended") if rec else "", _("installed") if pkg and pkg in have else "") if s)) 144 row.add_prefix(check) 145 check.connect("toggled", lambda *a: self.changed()) 146 group.add(row) 147 self.choices.append((check, pkg, i == current)) 148 self.body.append(group) 149 self.body.append(Gtk.Label(label=_("Installing a driver needs your password, and usually a restart after."), 150 css_classes=["dim-label", "caption"], wrap=True)) 151 152 def changed(self): 153 self.apply.set_sensitive(any(c.get_active() != was for c, _, was in self.choices)) 154 155 def do_apply(self): 156 add = [p for c, p, was in self.choices if c.get_active() and not was and p] 157 remove = [p for c, p, was in self.choices if was and not c.get_active() and p] 158 self.apply.set_sensitive(False) 159 self.toasts.add_toast(Adw.Toast(title=_("Working on it, this can take a few minutes"), timeout=0)) 160 161 def go(): 162 ok, err = True, "" 163 for cmd, pkgs in (("del", remove), ("driver", add)): 164 if pkgs: 165 r = subprocess.run(["pkexec", HELPER, cmd] + pkgs, capture_output=True, text=True) 166 if r.returncode: 167 ok, err = False, (r.stderr or r.stdout).strip()[-1500:] 168 break 169 GLib.idle_add(done, ok, err) 170 171 def done(ok, err): 172 if ok: 173 d = Adw.AlertDialog(heading=_("Done"), body=_("Restart the computer to start using the new driver.")) 174 d.add_response("later", _("Later")) 175 d.add_response("restart", _("Restart now")) 176 d.set_response_appearance("restart", Adw.ResponseAppearance.SUGGESTED) 177 d.connect("response", lambda d, r: r == "restart" and subprocess.Popen(["loginctl", "reboot"])) 178 else: 179 d = Adw.AlertDialog(heading=_("That didn't work"), body=err) 180 d.add_response("ok", _("OK")) 181 d.present(self.win) 182 threading.Thread(target=lambda: GLib.idle_add(self.show, find(), installed()), daemon=True).start() 183 threading.Thread(target=go, daemon=True).start() 184 185 186 if __name__ == "__main__": 187 Drivers().run(None)