Files
cnmcdee b6702c381e Phase 5: pdb step debugger (session + UI) + Install Libraries
- lightgui/debugger.py: PdbSession driving python3 -m pdb in a
  subprocess (start/run/restart, break/enable/disable/clear,
  continue, step into/over/out, stack, locals, watches, stop).
  State machine idle/running/stopped/exited; stop kills the whole
  process group (SIGTERM then SIGKILL) so Stop can never hang on a
  GUI app; Run from Stopped/Exited restarts with the current target
  and re-applies breakpoints; no temp breakpoints (stop-on-entry
  uses pdb's natural first stop, break-on-main is persistent).
- lightgui/debugger_ui.py: debugger window mirroring the C layout
  (toolbar, Target row, status, breakpoints left, locals/watches/
  stack right, output console). Breakpoint pane 420px / 320px
  location column; in-place row updates + id-based selection
  restore; checkbox toggles apply to the session first; watch and
  locals trees have search disabled (no search popup on click).
- lightgui/install_libs.py: Install Libraries flow (package to
  system site-packages, launcher to /usr/local/bin, .desktop to
  /usr/local/share/applications); pkexec first, sudo -S fallback
  with an Enter-submits password dialog; dry-run plan shown in the
  dialog. pkexec is not installed on the server (same honest limit
  as the C/Rust fix).
- app.py: Debug menu (Start Debugging, Toggle Breakpoint, Step
  Into/Over/Out, Continue, Stop) + Tools > Install Libraries;
  debugger stop scrolls the Code window to the stopped line.
- tests: 38 new tests (debugger session incl. breakpoint hit,
  step over/into/out, locals, watches, continue to end, stop
  kills the debuggee, restart from Exited, enable/disable;
  install dry-run command construction/file list/paths).
  Full suite: 239 tests pass.
2026-12-01 03:25:40 +00:00

352 lines
13 KiB
Python

"""Install Libraries — make the Python XFrame package globally
available so generated scripts run without PYTHONPATH.
Tools -> Install Libraries (mirrors the C 6568b6f + 5f12f04 and Rust
1eabec0 flow: build as the user, then install as root and report
the result in a scrollable log):
* the ``lightgui`` package is copied to the system site-packages
(``sysconfig`` purelib — on this server
/usr/local/lib/python3.14/dist-packages),
* a ``lightgui`` launcher is installed to /usr/local/bin (a shell
script that runs ``python3 -m lightgui``),
* a ``lightgui.desktop`` entry is installed to
/usr/local/share/applications so the app menu lists it.
There is nothing to build first (pure Python, no shared libraries,
so no ldconfig step — the C headers have no equivalent here).
The privileged step runs via pkexec when present (graphical root
password prompt), else via ``sudo -S`` with the password typed into
a dialog (the 5f12f04 fix: the password entry's activate signal
submits on Enter; the password is piped to sudo's stdin and wiped
immediately after, never written to disk or passed on a command
line).
Honest limit (same as the C/Rust fix): pkexec is NOT installed on
the server, so the real root-password prompt cannot be completed
live — only the prompt/piping/flow can be verified. Unit tests
cover the dry-run path only: command construction, file list and
target paths. No test performs a real privileged install.
The logic (paths, script text, command construction) is GTK-free
and unit-testable; the dialog at the bottom is the GTK half.
"""
import os
import shutil
import subprocess
import sysconfig
import tempfile
import threading
LAUNCHER_NAME = "lightgui"
DESKTOP_FILENAME = "lightgui.desktop"
LAUNCHER_PATH = "/usr/local/bin/lightgui"
DESKTOP_PATH = "/usr/local/share/applications/lightgui.desktop"
def repo_root():
"""Directory holding the ``lightgui`` package."""
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def site_packages():
"""System site-packages (purelib) for this interpreter."""
return sysconfig.get_paths()["purelib"]
def package_source(root=None):
"""The ``lightgui`` package directory to install."""
return os.path.join(repo_root() if root is None else root,
"lightgui")
def package_target(site=None):
"""Where the package lands: <site-packages>/lightgui."""
return os.path.join(site_packages() if site is None else site,
"lightgui")
def launcher_text():
"""Content of the /usr/local/bin/lightgui launcher."""
return ("#!/bin/sh\n"
"# LightGUI launcher (installed by Tools > Install Libraries).\n"
"# The lightgui package lives in the system site-packages,\n"
"# so the designer runs from anywhere without PYTHONPATH.\n"
"exec python3 -m lightgui \"$@\"\n")
def desktop_text():
"""Content of the lightgui.desktop entry."""
return ("[Desktop Entry]\n"
"Type=Application\n"
"Name=LightGUI\n"
"Comment=Visual GUI designer (Python/XFrame)\n"
"Exec=lightgui\n"
"Terminal=false\n"
"Categories=Development;GUIDesigner;\n")
def install_files(root=None, site=None):
"""[(source, destination)] installed by this flow — the file
list the dialog shows and the tests check. The package entry is
a directory (copied recursively); the others are files."""
root = repo_root() if root is None else root
return [(package_source(root), package_target(site)),
("<launcher>", LAUNCHER_PATH),
("<desktop file>", DESKTOP_PATH)]
def build_install_script(root=None, site=None):
"""Shell script (run as root) that performs the install. Pure
function of its inputs — this is what the dry-run shows and the
tests check. ``set -e`` so a failed copy aborts before the
launcher is installed; __pycache__ is dropped so no stale
bytecode ships."""
root = repo_root() if root is None else root
src = package_source(root)
dest = package_target(site)
launcher = launcher_text().replace("'", "'\\''")
desktop = desktop_text().replace("'", "'\\''")
lines = [
"#!/bin/sh",
"# LightGUI Install Libraries (generated; run as root).",
"set -e",
"echo 'Installing lightgui package to %s'" % dest,
"mkdir -p '%s'" % os.path.dirname(dest),
"rm -rf '%s'" % dest,
"cp -r '%s' '%s'" % (src, dest),
("find '%s' -name __pycache__ -type d "
"-exec rm -rf {} + 2>/dev/null || true" % dest),
"echo 'Installing launcher to %s'" % LAUNCHER_PATH,
"printf '%s' > '%s'" % (launcher, LAUNCHER_PATH),
"chmod 755 '%s'" % LAUNCHER_PATH,
"echo 'Installing desktop entry to %s'" % DESKTOP_PATH,
"mkdir -p '%s'" % os.path.dirname(DESKTOP_PATH),
"printf '%s' > '%s'" % (desktop, DESKTOP_PATH),
"chmod 644 '%s'" % DESKTOP_PATH,
("command -v update-desktop-database >/dev/null 2>&1 && "
"update-desktop-database /usr/local/share/applications "
"|| true"),
"echo 'LightGUI installed.'",
"echo 'Run it with: lightgui'",
]
return "\n".join(lines) + "\n"
def privileged_runner():
"""How the install is elevated: 'pkexec' when present, else
'sudo' when present, else None. (On the server pkexec is
missing, so this returns 'sudo'.)"""
if shutil.which("pkexec"):
return "pkexec"
if shutil.which("sudo"):
return "sudo"
return None
def install_command(script_path, runner=None):
"""argv that runs *script_path* as root: ``pkexec sh <script>``
or ``sudo -S sh <script>`` (sudo reads the password from stdin).
Pure construction — no execution, no password involved."""
if runner is None:
runner = privileged_runner()
if runner == "pkexec":
return ["pkexec", "sh", script_path]
if runner == "sudo":
return ["sudo", "-S", "sh", script_path]
return None
def write_install_script(path=None, root=None, site=None):
"""Write the install script to *path* (a temp file when None)
and return the path."""
if path is None:
handle, path = tempfile.mkstemp(prefix="lightgui_install_",
suffix=".sh")
os.close(handle)
with open(path, "w", encoding="utf-8") as handle:
handle.write(build_install_script(root=root, site=site))
return path
def run_install(password=None, root=None, site=None, runner=None):
"""Perform the install and return (ok, output). Writes the
install script to a temp file, runs it via pkexec or
``sudo -S`` (password fed on stdin, then wiped), captures the
combined output, and removes the script. Dry-run callers should
use build_install_script() instead — this one really installs.
Returns (False, message) when no elevation method exists."""
if runner is None:
runner = privileged_runner()
if runner is None:
return False, ("no pkexec and no sudo found — cannot "
"install as root")
script_path = write_install_script(root=root, site=site)
argv = install_command(script_path, runner=runner)
stdin_text = None
if runner == "sudo":
if password is None:
os.unlink(script_path)
return False, "sudo needs a root password"
stdin_text = password + "\n"
password = None # wiped: never kept past the handoff
try:
proc = subprocess.run(argv, input=stdin_text, text=True,
capture_output=True, timeout=300)
except OSError as exc:
return False, "cannot run install: %s" % exc
except subprocess.TimeoutExpired:
return False, "install timed out after 300s"
finally:
try:
os.unlink(script_path)
except OSError:
pass
output = (proc.stdout or "") + (proc.stderr or "")
return proc.returncode == 0, output
def is_installed(site=None):
"""True when the package target already exists."""
return os.path.isdir(package_target(site))
# --- GTK dialog ------------------------------------------------------------
def _password_dialog(parent):
"""Root-password dialog for the sudo fallback. The entry's
activate signal submits on Enter (the C 5f12f04 fix: the
default-widget chain does not fire under a nested dialog run).
Returns the password, or None on Cancel."""
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
dialog = Gtk.Dialog(title="Install Libraries — root password",
parent=parent,
flags=Gtk.DialogFlags.MODAL
| Gtk.DialogFlags.DESTROY_WITH_PARENT)
dialog.add_button("Cancel", Gtk.ResponseType.CANCEL)
dialog.add_button("Install", Gtk.ResponseType.OK)
area = dialog.get_content_area()
area.pack_start(Gtk.Label(
label="pkexec is not available, so the install uses sudo.\n"
"Enter the root password:",
xalign=0), False, False, 6)
entry = Gtk.Entry()
entry.set_visibility(False)
entry.set_activates_default(True)
# Enter submits (5f12f04): wire activate directly to OK.
entry.connect("activate",
lambda _e: dialog.response(Gtk.ResponseType.OK))
area.pack_start(entry, False, False, 6)
area.show_all()
password = None
if dialog.run() == Gtk.ResponseType.OK:
password = entry.get_text()
dialog.destroy()
return password
class InstallLibrariesDialog:
"""Tools -> Install Libraries dialog: shows the file list and
the exact install script (dry-run view), then installs as root
on Install and streams the result into the log. The log area
fills the dialog (the BuildConsole packing rule)."""
def __init__(self, parent=None):
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GLib
self._Gtk = Gtk
self._GLib = GLib
self._installing = False
self.window = Gtk.Dialog(
title="Install Libraries", parent=parent,
flags=Gtk.DialogFlags.MODAL
| Gtk.DialogFlags.DESTROY_WITH_PARENT)
self.window.set_default_size(700, 420)
self.window.add_button("Close", Gtk.ResponseType.CLOSE)
self.install_button = self.window.add_button(
"Install", Gtk.ResponseType.APPLY)
self.window.connect("response", self._on_response)
self.view = Gtk.TextView()
self.view.set_editable(False)
self.view.set_monospace(True)
self.view.set_wrap_mode(Gtk.WrapMode.CHAR)
self.buffer = self.view.get_buffer()
scroll = Gtk.ScrolledWindow()
scroll.set_policy(Gtk.PolicyType.AUTOMATIC,
Gtk.PolicyType.AUTOMATIC)
scroll.add(self.view)
content = self.window.get_content_area()
content.pack_start(scroll, True, True, 0)
content.show_all()
lines = ["Install Libraries — what will be installed:\n"]
for source, dest in install_files():
lines.append(" %s -> %s\n" % (source, dest))
lines.append("\nPrivileged step: %s\n"
% (privileged_runner() or "(none found)"))
lines.append("\nInstall script (run as root):\n")
lines.append(build_install_script())
self.buffer.set_text("".join(lines))
def show(self):
self.window.run()
self.window.destroy()
def _append(self, text):
end = self.buffer.get_end_iter()
self.buffer.insert(end, text)
end = self.buffer.get_end_iter()
self.view.scroll_to_iter(end, 0.0, False, 0.0, 0.0)
def _on_response(self, _dialog, response):
if response != self._Gtk.ResponseType.APPLY \
or self._installing:
return
runner = privileged_runner()
if runner is None:
self._append("\n[no pkexec and no sudo — cannot install]\n")
return
password = None
if runner == "sudo":
password = _password_dialog(self.window)
if password is None:
self._append("\n[cancelled — no password given]\n")
return
self._installing = True
self.install_button.set_sensitive(False)
self._append("\n$ %s\n" % " ".join(
install_command("<install-script>", runner=runner)))
thread = threading.Thread(
target=self._run_in_thread,
args=(password, runner), daemon=True)
thread.start()
def _run_in_thread(self, password, runner):
ok, output = run_install(password=password, runner=runner)
# The password local is dropped here (run_install already
# wiped its copy); nothing is retained.
self._GLib.idle_add(self._finish_install, ok, output)
return False
def _finish_install(self, ok, output):
self._append(output)
self._append("\n[Install %s]\n"
% ("succeeded — run it with: lightgui"
if ok else "FAILED"))
self._installing = False
self.install_button.set_sensitive(True)
return False
def show_install_libraries_dialog(parent=None):
"""Open the Tools -> Install Libraries dialog."""
InstallLibrariesDialog(parent=parent).show()