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.
This commit is contained in:
1 parent
c22ff1059f
commit
b6702c381e
6 files changed
+2746
No files matched your search
+132
@@ -59,6 +59,7 @@ class Application:
|
||||
self._saved_snapshot = self.project.save_text()
|
||||
self.generated_path = None
|
||||
self._run_console = None
|
||||
self.debugger_window = None # Phase 5: lazy DebuggerWindow
|
||||
|
||||
self.window = Gtk.Window(title="LightGUI — Python/GTK")
|
||||
self.window.set_default_size(1280, 800)
|
||||
@@ -147,6 +148,35 @@ class Application:
|
||||
"toggled", lambda _i: self.inspector.toggle())
|
||||
view_menu.append(self._inspector_menu_item)
|
||||
|
||||
debug_menu = Gtk.Menu()
|
||||
debug_item = Gtk.MenuItem(label="Debug")
|
||||
debug_item.set_submenu(debug_menu)
|
||||
menubar.append(debug_item)
|
||||
for label, callback in (
|
||||
("Start Debugging", self.do_debug_start),
|
||||
("Toggle Breakpoint", self.do_debug_toggle_breakpoint),
|
||||
(None, None),
|
||||
("Step Into", self.do_debug_step_into),
|
||||
("Step Over", self.do_debug_step_over),
|
||||
("Step Out", self.do_debug_step_out),
|
||||
("Continue", self.do_debug_continue),
|
||||
("Stop", self.do_debug_stop)):
|
||||
if label is None:
|
||||
debug_menu.append(Gtk.SeparatorMenuItem())
|
||||
continue
|
||||
item = Gtk.MenuItem(label=label)
|
||||
item.connect("activate", lambda _i, cb=callback: cb())
|
||||
debug_menu.append(item)
|
||||
|
||||
tools_menu = Gtk.Menu()
|
||||
tools_item = Gtk.MenuItem(label="Tools")
|
||||
tools_item.set_submenu(tools_menu)
|
||||
menubar.append(tools_item)
|
||||
install_item = Gtk.MenuItem(label="Install Libraries\u2026")
|
||||
install_item.connect("activate",
|
||||
lambda _i: self.do_install_libraries())
|
||||
tools_menu.append(install_item)
|
||||
|
||||
help_menu = Gtk.Menu()
|
||||
help_item = Gtk.MenuItem(label="Help")
|
||||
help_item.set_submenu(help_menu)
|
||||
@@ -420,6 +450,107 @@ class Application:
|
||||
console.run_command([sys.executable, path])
|
||||
self.set_status("Running %s" % path)
|
||||
|
||||
# --- Debugger (Phase 5) -----------------------------------------------------------
|
||||
def open_debugger(self):
|
||||
"""Create (once) and show the debugger window, targeting the
|
||||
generated script. The window owns the pdb session."""
|
||||
if self.debugger_window is None:
|
||||
from lightgui.debugger_ui import DebuggerWindow
|
||||
self.debugger_window = DebuggerWindow(
|
||||
parent=self.window,
|
||||
target=self._ensure_generated(),
|
||||
on_status=self.set_status,
|
||||
on_stop_location=self._on_debug_stop_location)
|
||||
else:
|
||||
self.debugger_window.set_target(self._ensure_generated())
|
||||
self.debugger_window.show()
|
||||
return self.debugger_window
|
||||
|
||||
def _debugger(self):
|
||||
"""Debugger window, opened if needed (target = generated
|
||||
script)."""
|
||||
return self.open_debugger()
|
||||
|
||||
def do_debug_start(self):
|
||||
window = self.open_debugger()
|
||||
window._on_run()
|
||||
|
||||
def _current_code_location(self):
|
||||
"""(file_path, 1-based line) at the cursor in the current
|
||||
Code tab, or None when there is no usable tab."""
|
||||
view = self.code_window.current_view()
|
||||
if view is None or not view.file_path:
|
||||
return None
|
||||
mark = view.buffer.get_insert()
|
||||
line = view.buffer.get_iter_at_mark(mark).get_line() + 1
|
||||
return view.file_path, line
|
||||
|
||||
def do_debug_toggle_breakpoint(self):
|
||||
location = self._current_code_location()
|
||||
if location is None:
|
||||
self.set_status("Toggle Breakpoint needs the cursor in "
|
||||
"a saved Code tab - Generate first")
|
||||
return
|
||||
path, line = location
|
||||
window = self._debugger()
|
||||
now_set = window.toggle_breakpoint(path, line)
|
||||
self.set_status("Breakpoint %s at %s:%d"
|
||||
% ("set" if now_set else "cleared", path, line))
|
||||
|
||||
def do_debug_step_into(self):
|
||||
self._debugger()._on_step_into()
|
||||
|
||||
def do_debug_step_over(self):
|
||||
self._debugger()._on_step_over()
|
||||
|
||||
def do_debug_step_out(self):
|
||||
self._debugger()._on_step_out()
|
||||
|
||||
def do_debug_continue(self):
|
||||
self._debugger()._on_continue()
|
||||
|
||||
def do_debug_stop(self):
|
||||
if self.debugger_window is not None:
|
||||
self.debugger_window._on_stop()
|
||||
|
||||
def _on_debug_stop_location(self, file, line):
|
||||
"""Scroll the Code window to the stopped line (debugger poll
|
||||
callback). Only for files the Code window knows: the
|
||||
generated script or an open tab."""
|
||||
view = None
|
||||
for candidate in self.code_window.views():
|
||||
if candidate.file_path == file:
|
||||
view = candidate
|
||||
break
|
||||
if view is None:
|
||||
if self.generated_path and file == self.generated_path:
|
||||
self.refresh_code_view(force=True)
|
||||
view = self.code_window.generated_view
|
||||
else:
|
||||
return
|
||||
if view is None:
|
||||
return
|
||||
self.code_window.show()
|
||||
self._sync_code_menu_item()
|
||||
page = self.code_window.notebook.page_num(view)
|
||||
if page >= 0:
|
||||
self.code_window.notebook.set_current_page(page)
|
||||
line0 = max(0, min(line - 1, view.buffer.get_line_count() - 1))
|
||||
cursor = view.buffer.get_iter_at_line(line0)
|
||||
view.buffer.place_cursor(cursor)
|
||||
view.view.scroll_to_iter(cursor, 0.0, True, 0.0, 0.5)
|
||||
self.set_status("Stopped at %s:%d" % (file, line))
|
||||
|
||||
def _close_debugger(self):
|
||||
if self.debugger_window is not None:
|
||||
self.debugger_window.destroy()
|
||||
self.debugger_window = None
|
||||
|
||||
# --- Install Libraries (Phase 5) --------------------------------------------------
|
||||
def do_install_libraries(self):
|
||||
from lightgui import install_libs
|
||||
install_libs.show_install_libraries_dialog(self.window)
|
||||
|
||||
# --- Code window ---------------------------------------------------------------
|
||||
def _sync_code_menu_item(self):
|
||||
if getattr(self, "_code_menu_item", None) is not None:
|
||||
@@ -456,6 +587,7 @@ class Application:
|
||||
def do_quit(self):
|
||||
if not self.project_file.confirm_discard(self.window):
|
||||
return
|
||||
self._close_debugger()
|
||||
Gtk.main_quit()
|
||||
|
||||
def _on_window_delete(self, _window, _event):
|
||||
|
||||
@@ -0,0 +1,983 @@
|
||||
"""Step debugger — pdb session backend (no GTK dependency).
|
||||
|
||||
Drives ``python3 -m pdb`` on a generated Python script in a
|
||||
subprocess, mirroring the C GDB/MI session architecture
|
||||
(src/debugger.h / GdbSession): staged breakpoints, step
|
||||
into/over/out, continue, kill, restart, locals / watches / stack
|
||||
frames, target output capture. The UI (debugger_ui.py) polls this
|
||||
session; all pdb traffic stays here.
|
||||
|
||||
Protocol notes (verified against CPython 3.14 pdb, see the probe in
|
||||
the Phase 5 report):
|
||||
|
||||
* pdb stops at the first line on start and prints ``> file(1)func()``
|
||||
plus the source line, then the ``(Pdb) `` prompt. Every command's
|
||||
reply ends at the next prompt, so the session reads until the
|
||||
prompt (or process exit) with a timeout.
|
||||
* A breakpoint hit prints the same ``> file(line)func()`` marker;
|
||||
the stop reason is inferred: the current line matches a known
|
||||
breakpoint -> ``breakpoint-hit``; otherwise after a step command
|
||||
-> ``end-stepping-range``; the first stop -> ``entry``.
|
||||
* When the program finishes, pdb does NOT exit: it prints ``The
|
||||
program finished and will be restarted`` and waits at the first
|
||||
line again. That message is the exit event (state Exited); the
|
||||
pdb process itself is ended by sending ``quit`` or by killing it.
|
||||
* ``break`` (no args) lists breakpoints as ``N breakpoint keep
|
||||
yes|no at file:line`` with an optional ``breakpoint already hit
|
||||
N time(s)`` continuation line. ``clear N`` deletes silently;
|
||||
``disable``/``enable`` print confirmation.
|
||||
|
||||
The eight documented C debugger bugs, and how this session avoids
|
||||
each of them (the UI half is in debugger_ui.py):
|
||||
|
||||
1. Breakpoint pane too narrow — the UI gives the pane a 420px
|
||||
minimum and a 320px location column (see debugger_ui.py).
|
||||
2. List selection doesn't stick — the UI updates store rows in
|
||||
place by breakpoint id and re-selects the same id (no rebuild).
|
||||
3. Step Out in main() modal — there is no modal here: ``step_out``
|
||||
sends pdb ``return``; at module level (a single frame) it
|
||||
degrades to ``continue`` instead of blocking.
|
||||
4. Stop times out on a GUI app — ``stop()`` never waits on the pdb
|
||||
prompt: a stopped session gets ``quit``; anything else gets
|
||||
SIGTERM then SIGKILL to the whole process group, and the child
|
||||
is always reaped.
|
||||
5. Run from Stopped/Exited ignores Target — ``run()``/``restart()``
|
||||
always restart with the *current* stored target and re-apply
|
||||
every breakpoint; there is no stale-target path.
|
||||
6. break-on-main temp breakpoint persisted — there are no temp
|
||||
breakpoints at all: ``stop_on_entry`` uses pdb's natural first
|
||||
stop (no breakpoint is created), and ``break_on_main`` is a
|
||||
normal persistent breakpoint on the ``def main():`` line.
|
||||
7. Watch clicks open a search popup — the UI disables TreeView
|
||||
search on the watch/locals trees and uses no SearchEntry.
|
||||
8. Enabled-checkbox toggles ignored — the UI applies the toggle to
|
||||
the session first, then updates the store row directly.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
PDB_PROMPT = "(Pdb) "
|
||||
DEFAULT_TIMEOUT = 10.0
|
||||
|
||||
# States. Mirrors DbgState (C) minus Starting/Error, which pdb does
|
||||
# not distinguish: a failed start reports False + last_error and
|
||||
# stays Idle.
|
||||
STATE_IDLE = "idle"
|
||||
STATE_RUNNING = "running"
|
||||
STATE_STOPPED = "stopped"
|
||||
STATE_EXITED = "exited"
|
||||
|
||||
# Dunder names are never shown as locals (they drown the pane in
|
||||
# __builtins__ etc. — the probe showed a multi-KB __builtins__ repr).
|
||||
_LOCALS_QUERY = ("p [(k, type(v).__name__, repr(v)) for k, v in "
|
||||
"list(locals().items()) if not k.startswith('__')]")
|
||||
|
||||
_FRAME_RE = re.compile(r"^>?\s*(\S+)\((\d+)\)(.*)$")
|
||||
_BP_SET_RE = re.compile(r"Breakpoint (\d+) at (.+):(\d+)")
|
||||
_BP_ROW_RE = re.compile(
|
||||
r"^(\d+)\s+breakpoint\s+\w+\s+(yes|no)\s+at\s+(.+):(\d+)\s*$")
|
||||
_BP_HITS_RE = re.compile(r"breakpoint already hit (\d+) time")
|
||||
_LOCATION_RE = re.compile(r"^(.*?):(\d+)$")
|
||||
_FINISHED_RE = re.compile(r"The program finished")
|
||||
|
||||
|
||||
class DebuggerSettings:
|
||||
"""Session settings (C DebuggerSettings, pdb subset)."""
|
||||
|
||||
def __init__(self, stop_on_entry=True, break_on_main=False,
|
||||
default_args="", cmd_timeout_ms=5000,
|
||||
stop_timeout_ms=10000):
|
||||
self.stop_on_entry = stop_on_entry
|
||||
# Persistent breakpoint on the ``def main():`` line (not a
|
||||
# temp breakpoint — see the module docstring, bug 6).
|
||||
self.break_on_main = break_on_main
|
||||
self.default_args = default_args
|
||||
self.cmd_timeout_ms = cmd_timeout_ms
|
||||
self.stop_timeout_ms = stop_timeout_ms
|
||||
|
||||
|
||||
class Breakpoint:
|
||||
"""One breakpoint: pdb number (0 = staged, not yet inserted),
|
||||
``file:line`` location, enabled flag, hit count, and the
|
||||
optional condition / ignore count (pdb ``break loc, cond`` /
|
||||
``ignore N count``)."""
|
||||
|
||||
def __init__(self, location, bp_id=0, enabled=True, hits=0,
|
||||
condition="", ignore_count=0):
|
||||
self.id = bp_id
|
||||
self.location = location
|
||||
self.file = ""
|
||||
self.line = 0
|
||||
self.enabled = enabled
|
||||
self.hits = hits
|
||||
self.condition = condition
|
||||
self.ignore_count = ignore_count
|
||||
parsed = parse_breakpoint_location(location)
|
||||
if parsed is not None:
|
||||
self.file, self.line, _func = parsed
|
||||
|
||||
def __repr__(self):
|
||||
return ("Breakpoint(id=%r, location=%r, enabled=%r, hits=%r)"
|
||||
% (self.id, self.location, self.enabled, self.hits))
|
||||
|
||||
|
||||
class Variable:
|
||||
"""One local / watch value: name, type name, repr value."""
|
||||
|
||||
def __init__(self, name, type_name, value):
|
||||
self.name = name
|
||||
self.type_name = type_name
|
||||
self.value = value
|
||||
|
||||
def __repr__(self):
|
||||
return "Variable(%r, %r, %r)" % (self.name, self.type_name,
|
||||
self.value)
|
||||
|
||||
|
||||
class StackFrame:
|
||||
"""One frame from ``where``: level, function, file, line."""
|
||||
|
||||
def __init__(self, level, function, file, line):
|
||||
self.level = level
|
||||
self.function = function
|
||||
self.file = file
|
||||
self.line = line
|
||||
|
||||
def __repr__(self):
|
||||
return ("StackFrame(%r, %r, %r, %r)"
|
||||
% (self.level, self.function, self.file, self.line))
|
||||
|
||||
|
||||
class StopInfo:
|
||||
"""What the last stop was: reason (``breakpoint-hit`` /
|
||||
``end-stepping-range`` / ``entry`` / ``exited-normally`` /
|
||||
``exited``), the breakpoint id when applicable, the current
|
||||
frame, and the exit code once the program has finished."""
|
||||
|
||||
def __init__(self, reason="", breakpoint_id=0, frame=None,
|
||||
exit_code=-1, exited=False):
|
||||
self.reason = reason
|
||||
self.breakpoint_id = breakpoint_id
|
||||
self.frame = frame or StackFrame(0, "", "", 0)
|
||||
self.exit_code = exit_code
|
||||
self.exited = exited
|
||||
|
||||
def __repr__(self):
|
||||
return ("StopInfo(%r, bp=%r, frame=%r, exit=%r)"
|
||||
% (self.reason, self.breakpoint_id, self.frame,
|
||||
self.exit_code))
|
||||
|
||||
|
||||
def parse_breakpoint_location(text):
|
||||
"""Parse ``file:line`` (or a bare function name) into
|
||||
(file, line, function). Returns None when the text is not a
|
||||
plausible location. Mirrors C parse_breakpoint_location."""
|
||||
text = (text or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
match = _LOCATION_RE.match(text)
|
||||
if match:
|
||||
try:
|
||||
line = int(match.group(2))
|
||||
except ValueError:
|
||||
return None
|
||||
if line <= 0:
|
||||
return None
|
||||
return (match.group(1), line, "")
|
||||
if re.match(r"^[A-Za-z_][A-Za-z0-9_.]*$", text):
|
||||
return ("", 0, text)
|
||||
return None
|
||||
|
||||
|
||||
def repo_root():
|
||||
"""Directory holding the ``lightgui`` package (this file's
|
||||
parent's parent) — put on PYTHONPATH for the debuggee so a
|
||||
generated script can ``import lightgui``."""
|
||||
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def _run_env(extra=None):
|
||||
env = dict(os.environ)
|
||||
root = repo_root()
|
||||
parts = [p for p in env.get("PYTHONPATH", "").split(os.pathsep)
|
||||
if p]
|
||||
if root not in parts:
|
||||
parts.insert(0, root)
|
||||
env["PYTHONPATH"] = os.pathsep.join(parts)
|
||||
if extra:
|
||||
env.update(extra)
|
||||
return env
|
||||
|
||||
|
||||
def _parse_frame_line(line):
|
||||
"""Parse one pdb ``> file(line)func()`` / ``where`` line into a
|
||||
StackFrame (level 0), or None."""
|
||||
match = _FRAME_RE.match(line.strip())
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
line_no = int(match.group(2))
|
||||
except ValueError:
|
||||
return None
|
||||
func = match.group(3)
|
||||
# A --Return-- marker carries the return value:
|
||||
# ``helper()->11`` -> ``helper``.
|
||||
if "()->" in func:
|
||||
func = func.split("()->", 1)[0]
|
||||
elif func.endswith("()"):
|
||||
func = func[:-2]
|
||||
return StackFrame(0, func, match.group(1), line_no)
|
||||
|
||||
|
||||
class PdbSession:
|
||||
"""A pdb subprocess driving one target script.
|
||||
|
||||
Only one session runs at a time per instance. All public
|
||||
methods that talk to pdb return bool and set ``last_error`` on
|
||||
failure; ``state`` is one of idle/running/stopped/exited.
|
||||
"""
|
||||
|
||||
def __init__(self, settings=None, python=sys.executable):
|
||||
self.settings = settings or DebuggerSettings()
|
||||
self.python = python
|
||||
self.state = STATE_IDLE
|
||||
self.script_path = None
|
||||
self.args = ""
|
||||
self.last_error = ""
|
||||
self.last_stop = StopInfo()
|
||||
self._stop_seq = 0
|
||||
self._last_exec_response = ""
|
||||
self._breakpoints = [] # Breakpoint, live (id>0) or staged
|
||||
self._watch_exprs = []
|
||||
self._watches = []
|
||||
self._locals = []
|
||||
self._frames = []
|
||||
self._proc = None
|
||||
self._reader = None
|
||||
self._reader_stop = threading.Event()
|
||||
self._prompt_event = threading.Event()
|
||||
self._exited_event = threading.Event()
|
||||
self._lock = threading.Lock()
|
||||
self._raw = [] # all output text, in order
|
||||
self._resp = [] # output since the last command
|
||||
self._resp_start = 0 # index into _raw of current reply
|
||||
|
||||
# --- introspection ----------------------------------------------------
|
||||
|
||||
def stop_seq(self):
|
||||
"""Monotonic stop counter (C stop_seq): incremented on every
|
||||
fresh stop, so a UI poll can tell a new stop from a stale
|
||||
Stopped state."""
|
||||
return self._stop_seq
|
||||
|
||||
def breakpoints(self):
|
||||
return list(self._breakpoints)
|
||||
|
||||
def watches(self):
|
||||
return list(self._watches)
|
||||
|
||||
def locals(self):
|
||||
return list(self._locals)
|
||||
|
||||
def frames(self):
|
||||
return list(self._frames)
|
||||
|
||||
def target_output(self):
|
||||
"""All debuggee + pdb output so far."""
|
||||
with self._lock:
|
||||
return "".join(self._raw)
|
||||
|
||||
def clear_output(self):
|
||||
with self._lock:
|
||||
self._raw = []
|
||||
self._resp = []
|
||||
self._resp_start = 0
|
||||
|
||||
def is_alive(self):
|
||||
return self._proc is not None and self._proc.poll() is None
|
||||
|
||||
def target_running(self):
|
||||
return self.state == STATE_RUNNING
|
||||
|
||||
# --- lifecycle ----------------------------------------------------------
|
||||
|
||||
def start(self, script_path, args=None):
|
||||
"""Start pdb on *script_path* (re-applying every breakpoint
|
||||
kept from a previous run). Returns True on the initial stop
|
||||
(or, with stop_on_entry False, after the auto-continue).
|
||||
A live session is shut down first, so start() is also the
|
||||
clean restart path (bug 5: Run from Stopped/Exited always
|
||||
uses the current target)."""
|
||||
if not script_path or not os.path.isfile(script_path):
|
||||
self.last_error = "no such script: %s" % script_path
|
||||
return False
|
||||
self.shutdown()
|
||||
self.script_path = os.path.abspath(script_path)
|
||||
self.args = args if args is not None else self.settings.default_args
|
||||
argv = [self.python, "-u", "-m", "pdb", self.script_path]
|
||||
if self.args:
|
||||
argv.extend(self.args.split())
|
||||
try:
|
||||
self._proc = subprocess.Popen(
|
||||
argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, text=False,
|
||||
start_new_session=True, env=_run_env())
|
||||
except OSError as exc:
|
||||
self.last_error = "cannot start pdb: %s" % exc
|
||||
return False
|
||||
self._prompt_event.clear()
|
||||
self._exited_event.clear()
|
||||
self._reader_stop.clear()
|
||||
with self._lock:
|
||||
self._raw = []
|
||||
self._resp = []
|
||||
self._resp_start = 0
|
||||
self._reader = threading.Thread(target=self._reader_loop,
|
||||
daemon=True)
|
||||
self._reader.start()
|
||||
self.state = STATE_RUNNING
|
||||
if not self._wait_prompt(self.settings.stop_timeout_ms / 1000.0):
|
||||
self.last_error = "pdb did not reach its first prompt"
|
||||
self.state = STATE_IDLE
|
||||
self.shutdown()
|
||||
return False
|
||||
self.state = STATE_STOPPED
|
||||
self._note_stop("entry", self._last_response())
|
||||
# Re-apply kept breakpoints, then the break-on-main one.
|
||||
for bp in list(self._breakpoints):
|
||||
self._insert_live(bp)
|
||||
if self.settings.break_on_main:
|
||||
main_line = _find_main_def_line(self.script_path)
|
||||
if main_line:
|
||||
self.add_breakpoint("%s:%d" % (self.script_path,
|
||||
main_line))
|
||||
if not self.settings.stop_on_entry:
|
||||
# Short wait: a GUI target runs on past the entry stop
|
||||
# and the UI poll picks up its later stops.
|
||||
return self.cont(timeout_s=0.5)
|
||||
self.refresh_on_stop()
|
||||
return True
|
||||
|
||||
def run(self):
|
||||
"""(Re)run from the start with the current target — the C
|
||||
toolbar Run behaviour: from Idle it starts the target; from
|
||||
Stopped/Exited it restarts it cleanly (bug 5)."""
|
||||
if self.script_path is None:
|
||||
self.last_error = "no target — nothing to run"
|
||||
return False
|
||||
return self.start(self.script_path, self.args)
|
||||
|
||||
def restart(self):
|
||||
"""Kill (if running) and run the target again."""
|
||||
return self.run()
|
||||
|
||||
def shutdown(self):
|
||||
"""End the pdb process and reap it. Safe to call repeatedly;
|
||||
never blocks on the pdb prompt (bug 4)."""
|
||||
self.stop()
|
||||
if self._reader is not None:
|
||||
self._reader_stop.set()
|
||||
self._reader.join(timeout=2.0)
|
||||
self._reader = None
|
||||
self.state = STATE_IDLE
|
||||
|
||||
def stop(self):
|
||||
"""Terminate the debuggee. A session stopped at a prompt gets
|
||||
a clean ``quit``; anything else (running GUI app, hung
|
||||
target) gets SIGTERM to the whole process group, then
|
||||
SIGKILL, then a reap — so Stop can never hang (bug 4)."""
|
||||
proc = self._proc
|
||||
if proc is None:
|
||||
self.state = STATE_EXITED if self.script_path else STATE_IDLE
|
||||
return True
|
||||
if proc.poll() is not None:
|
||||
self._reap()
|
||||
return True
|
||||
# Clean quit when pdb is sitting at a prompt.
|
||||
if self._prompt_event.is_set():
|
||||
try:
|
||||
proc.stdin.write(b"quit\n")
|
||||
proc.stdin.flush()
|
||||
except (BrokenPipeError, OSError):
|
||||
pass
|
||||
try:
|
||||
proc.wait(timeout=2.0)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
if proc.poll() is None:
|
||||
try:
|
||||
os.killpg(proc.pid, signal.SIGTERM)
|
||||
except (ProcessLookupError, PermissionError, OSError):
|
||||
try:
|
||||
proc.terminate()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
proc.wait(timeout=2.0)
|
||||
except subprocess.TimeoutExpired:
|
||||
try:
|
||||
os.killpg(proc.pid, signal.SIGKILL)
|
||||
except (ProcessLookupError, PermissionError, OSError):
|
||||
try:
|
||||
proc.kill()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
proc.wait(timeout=2.0)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
self._reap()
|
||||
return True
|
||||
|
||||
def _reap(self):
|
||||
"""Mark the session exited once the child is gone."""
|
||||
proc = self._proc
|
||||
if proc is not None and proc.poll() is None:
|
||||
try:
|
||||
proc.wait(timeout=1.0)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
self._proc = None
|
||||
self._exited_event.set()
|
||||
self.state = STATE_EXITED
|
||||
|
||||
# --- reader -------------------------------------------------------------
|
||||
|
||||
def _reader_loop(self):
|
||||
"""Read pdb output byte-wise until the ``(Pdb) `` prompt (it
|
||||
has no trailing newline, so readline() would block) or EOF.
|
||||
Appends to the raw log and to the current command's reply;
|
||||
sets the prompt event on each prompt, the exited event on
|
||||
EOF."""
|
||||
fd = self._proc.stdout.fileno()
|
||||
buf = b""
|
||||
while not self._reader_stop.is_set():
|
||||
try:
|
||||
chunk = os.read(fd, 4096)
|
||||
except OSError:
|
||||
break
|
||||
if not chunk:
|
||||
break
|
||||
buf += chunk
|
||||
text = buf.decode("utf-8", "replace")
|
||||
buf = b""
|
||||
with self._lock:
|
||||
self._raw.append(text)
|
||||
self._resp.append(text)
|
||||
if text.endswith(PDB_PROMPT) or PDB_PROMPT in text:
|
||||
# Prompt is always at the end of a chunk boundary
|
||||
# once pdb is idle; require the tail match so target
|
||||
# output merely mentioning "(Pdb)" does not count.
|
||||
with self._lock:
|
||||
tail = "".join(self._raw)[-len(PDB_PROMPT):]
|
||||
if tail == PDB_PROMPT:
|
||||
self._prompt_event.set()
|
||||
self._exited_event.set()
|
||||
if self._proc is not None and self._proc.poll() is not None:
|
||||
self.state = STATE_EXITED
|
||||
|
||||
def _last_response(self):
|
||||
"""Text of the current command's reply (since the last
|
||||
command was sent), prompt stripped."""
|
||||
with self._lock:
|
||||
text = "".join(self._resp)
|
||||
if text.endswith(PDB_PROMPT):
|
||||
text = text[:-len(PDB_PROMPT)]
|
||||
return text
|
||||
|
||||
def _send(self, command):
|
||||
"""Send one pdb command; clears the prompt event and the
|
||||
reply buffer first. Returns False when there is no live
|
||||
process."""
|
||||
if self._proc is None or self._proc.poll() is not None:
|
||||
return False
|
||||
self._prompt_event.clear()
|
||||
with self._lock:
|
||||
self._resp = []
|
||||
try:
|
||||
self._proc.stdin.write((command + "\n").encode("utf-8"))
|
||||
self._proc.stdin.flush()
|
||||
except (BrokenPipeError, OSError):
|
||||
return False
|
||||
return True
|
||||
|
||||
def _wait_prompt(self, timeout_s):
|
||||
"""Wait for the next prompt or for the process to exit.
|
||||
Returns True when pdb is idle at a prompt (or the program
|
||||
finished and pdb is waiting at the first line again)."""
|
||||
deadline = time.time() + max(timeout_s, 0.1)
|
||||
while time.time() < deadline:
|
||||
if self._prompt_event.wait(timeout=0.1):
|
||||
return True
|
||||
if self._exited_event.is_set() \
|
||||
and self._proc is not None \
|
||||
and self._proc.poll() is not None:
|
||||
return True
|
||||
if self._proc is not None and self._proc.poll() is not None:
|
||||
return True
|
||||
return self._prompt_event.is_set()
|
||||
|
||||
def _note_stop(self, reason, response):
|
||||
"""Record a stop from a command's *response*: current frame,
|
||||
breakpoint hit, finished-program detection. Increments the
|
||||
stop sequence."""
|
||||
frame = None
|
||||
for line in reversed(response.splitlines()):
|
||||
parsed = _parse_frame_line(line)
|
||||
if parsed is not None:
|
||||
frame = parsed
|
||||
break
|
||||
bp_id = 0
|
||||
if frame is not None:
|
||||
for bp in self._breakpoints:
|
||||
if bp.id and bp.file == frame.file \
|
||||
and bp.line == frame.line and bp.enabled:
|
||||
bp_id = bp.id
|
||||
reason = "breakpoint-hit"
|
||||
break
|
||||
exited = False
|
||||
exit_code = -1
|
||||
if _FINISHED_RE.search(response):
|
||||
exited = True
|
||||
reason = "exited-normally"
|
||||
if "Traceback (most recent call last)" not in response:
|
||||
exit_code = 0
|
||||
self._stop_seq += 1
|
||||
self.last_stop = StopInfo(reason, bp_id, frame, exit_code,
|
||||
exited)
|
||||
self.state = STATE_EXITED if exited else STATE_STOPPED
|
||||
if frame is not None:
|
||||
self._frames = [frame]
|
||||
|
||||
# --- execution control ----------------------------------------------------
|
||||
|
||||
def _exec(self, command, timeout_s=None):
|
||||
"""Send an execution command (continue/step/...) and wait
|
||||
for the next stop. Returns False + last_error when pdb does
|
||||
not stop in time; the session is then left Running and the
|
||||
caller may still stop() it."""
|
||||
if self.state not in (STATE_STOPPED, STATE_EXITED):
|
||||
self.last_error = "cannot %s while %s" % (command,
|
||||
self.state)
|
||||
return False
|
||||
if self.state == STATE_EXITED:
|
||||
# Continuing a finished program restarts it from line 1
|
||||
# (pdb behaviour); a clean restart is run()/restart().
|
||||
self.last_error = ("program has exited — use Run to "
|
||||
"start it again")
|
||||
return False
|
||||
if timeout_s is None:
|
||||
timeout_s = self.settings.stop_timeout_ms / 1000.0
|
||||
self.state = STATE_RUNNING
|
||||
if not self._send(command):
|
||||
self.last_error = "pdb process is gone"
|
||||
self.state = STATE_EXITED
|
||||
return False
|
||||
if not self._wait_prompt(timeout_s):
|
||||
# Still running (e.g. sitting in Gtk.main()) — not an
|
||||
# error; the UI poll picks up the stop when it lands.
|
||||
self.last_error = ""
|
||||
self._last_exec_response = ""
|
||||
return True
|
||||
response = self._last_response()
|
||||
self._last_exec_response = response
|
||||
reason = "end-stepping-range" if command != "continue" \
|
||||
else "breakpoint-hit"
|
||||
self._note_stop(reason, response)
|
||||
if self.state == STATE_STOPPED:
|
||||
self.refresh_on_stop()
|
||||
return True
|
||||
|
||||
def cont(self, timeout_s=None):
|
||||
"""Continue until the next breakpoint, or exit. *timeout_s*
|
||||
bounds how long the caller waits for the stop; a running
|
||||
target (e.g. a GUI app in Gtk.main()) returns promptly with
|
||||
state Running and the UI poll picks up the stop when it
|
||||
lands."""
|
||||
return self._exec("continue", timeout_s)
|
||||
|
||||
def step_into(self, timeout_s=None):
|
||||
"""Step into the called function (pdb ``step``)."""
|
||||
return self._exec("step", timeout_s)
|
||||
|
||||
def step_over(self, timeout_s=None):
|
||||
"""Step over the current line (pdb ``next``)."""
|
||||
return self._exec("next", timeout_s)
|
||||
|
||||
def step_out(self, timeout_s=None):
|
||||
"""Step out of the current function (pdb ``return``). At
|
||||
module level there is no caller, so this degrades to
|
||||
``continue`` instead of blocking (bug 3: no modal). pdb
|
||||
stops once more at the ``--Return--`` event inside the same
|
||||
function, so one extra ``next`` lands in the caller — the
|
||||
GDB ``finish`` behaviour."""
|
||||
# ``where`` lists bdb.py frames too, so the frame count
|
||||
# cannot decide this: the current frame's function can. At
|
||||
# module level there is no caller, so Step Out degrades to
|
||||
# Continue (which still stops at breakpoints) instead of
|
||||
# blocking (bug 3: no modal).
|
||||
if self.last_stop.frame \
|
||||
and self.last_stop.frame.function in ("<module>", ""):
|
||||
return self._exec("continue", timeout_s)
|
||||
if not self._exec("return", timeout_s):
|
||||
return False
|
||||
if "--Return--" in self._last_exec_response:
|
||||
return self._exec("next", timeout_s)
|
||||
return True
|
||||
|
||||
def wait_for_stop(self, timeout_ms=-1):
|
||||
"""Wait until the target stops (breakpoint/step/exit) or
|
||||
*timeout_ms* elapses. True when a stop arrived."""
|
||||
if timeout_ms < 0:
|
||||
timeout_ms = self.settings.stop_timeout_ms
|
||||
before = self._stop_seq
|
||||
ok = self._wait_prompt(timeout_ms / 1000.0)
|
||||
if ok and self._stop_seq == before \
|
||||
and self._prompt_event.is_set():
|
||||
self._note_stop("end-stepping-range",
|
||||
self._last_response())
|
||||
self.refresh_on_stop()
|
||||
return ok and self._stop_seq > before
|
||||
|
||||
def poll_events(self):
|
||||
"""Non-blocking drain for the UI poll tick: if a fresh stop
|
||||
landed since the last poll, record it and refresh panes.
|
||||
Returns True when a new stop was picked up."""
|
||||
if not self._prompt_event.is_set():
|
||||
return False
|
||||
if self.state != STATE_RUNNING:
|
||||
return False
|
||||
self._note_stop("end-stepping-range", self._last_response())
|
||||
if self.state == STATE_STOPPED:
|
||||
self.refresh_on_stop()
|
||||
return True
|
||||
|
||||
# --- breakpoints ----------------------------------------------------------
|
||||
|
||||
def _insert_live(self, bp):
|
||||
"""Insert a staged/kept breakpoint into the live pdb. On
|
||||
success the Breakpoint gains its pdb id; on failure it stays
|
||||
staged (id 0) and last_error is set."""
|
||||
if self._proc is None or self.state != STATE_STOPPED:
|
||||
return False
|
||||
cmd = "break %s" % bp.location
|
||||
if bp.condition:
|
||||
cmd += ", %s" % bp.condition
|
||||
if not self._send(cmd):
|
||||
return False
|
||||
if not self._wait_prompt(
|
||||
self.settings.cmd_timeout_ms / 1000.0):
|
||||
self.last_error = "pdb did not answer break"
|
||||
return False
|
||||
response = self._last_response()
|
||||
match = _BP_SET_RE.search(response)
|
||||
if not match:
|
||||
self.last_error = response.strip().splitlines()[-1] \
|
||||
if response.strip() else "breakpoint rejected"
|
||||
return False
|
||||
bp.id = int(match.group(1))
|
||||
bp.file = match.group(2)
|
||||
bp.line = int(match.group(3))
|
||||
if bp.ignore_count:
|
||||
self._send("ignore %d %d" % (bp.id, bp.ignore_count))
|
||||
self._wait_prompt(self.settings.cmd_timeout_ms / 1000.0)
|
||||
if not bp.enabled:
|
||||
self._send("disable %d" % bp.id)
|
||||
self._wait_prompt(self.settings.cmd_timeout_ms / 1000.0)
|
||||
return True
|
||||
|
||||
def add_breakpoint(self, location, condition="", ignore_count=0,
|
||||
enabled=True):
|
||||
"""Add a breakpoint at ``file:line``. Before start (or when
|
||||
the session is not stopped) it is staged for the next Run;
|
||||
live, it is inserted into pdb at once. Returns the
|
||||
Breakpoint, or None + last_error when the location does not
|
||||
parse or pdb rejects it."""
|
||||
parsed = parse_breakpoint_location(location)
|
||||
if parsed is None:
|
||||
self.last_error = "bad breakpoint location: %r" % location
|
||||
return None
|
||||
existing = self.find_breakpoint(location)
|
||||
if existing is not None:
|
||||
self.last_error = "breakpoint already set at %s" % location
|
||||
return existing
|
||||
bp = Breakpoint(location, enabled=enabled,
|
||||
condition=condition, ignore_count=ignore_count)
|
||||
bp.file, bp.line, _func = parsed
|
||||
if self.state == STATE_STOPPED and self.is_alive():
|
||||
if not self._insert_live(bp):
|
||||
return None
|
||||
self._breakpoints.append(bp)
|
||||
return bp
|
||||
|
||||
def find_breakpoint(self, location):
|
||||
"""Breakpoint at *location* (``file:line``), or None. The
|
||||
file part is compared by basename + absolute path, so a
|
||||
breakpoint set as ``script.py:6`` matches the resolved
|
||||
``/abs/path/script.py:6``."""
|
||||
parsed = parse_breakpoint_location(location)
|
||||
if parsed is None:
|
||||
return None
|
||||
want_file, want_line, _func = parsed
|
||||
for bp in self._breakpoints:
|
||||
if bp.line != want_line:
|
||||
continue
|
||||
if bp.file == want_file or (
|
||||
want_file and os.path.basename(bp.file)
|
||||
== os.path.basename(want_file)):
|
||||
return bp
|
||||
return None
|
||||
|
||||
def remove_breakpoint(self, bp_id):
|
||||
"""Remove breakpoint *bp_id* (live or staged). Returns False
|
||||
when the id is unknown."""
|
||||
bp = next((b for b in self._breakpoints if b.id == bp_id),
|
||||
None)
|
||||
if bp is None:
|
||||
# Staged breakpoints have id 0; match by object identity
|
||||
# is handled by remove_staged_breakpoint().
|
||||
self.last_error = "no breakpoint %r" % bp_id
|
||||
return False
|
||||
if bp.id and self.state == STATE_STOPPED and self.is_alive():
|
||||
if not self._send("clear %d" % bp.id):
|
||||
return False
|
||||
self._wait_prompt(self.settings.cmd_timeout_ms / 1000.0)
|
||||
self._breakpoints.remove(bp)
|
||||
return True
|
||||
|
||||
def remove_staged_breakpoint(self, location):
|
||||
"""Erase a staged (not yet inserted, id 0) breakpoint by
|
||||
location. False when not staged."""
|
||||
bp = self.find_breakpoint(location)
|
||||
if bp is None or bp.id != 0:
|
||||
return False
|
||||
self._breakpoints.remove(bp)
|
||||
return True
|
||||
|
||||
def toggle_breakpoint(self, file, line):
|
||||
"""Toggle a breakpoint at (*file*, *line*). Returns True when
|
||||
a breakpoint is now set there (C debugger_toggle_breakpoint).
|
||||
With a live session the change applies at once; otherwise it
|
||||
is staged for the next Run."""
|
||||
location = "%s:%d" % (file, line)
|
||||
bp = self.find_breakpoint(location)
|
||||
if bp is not None:
|
||||
if bp.id == 0:
|
||||
self.remove_staged_breakpoint(location)
|
||||
else:
|
||||
self.remove_breakpoint(bp.id)
|
||||
return False
|
||||
return self.add_breakpoint(location) is not None
|
||||
|
||||
def has_breakpoint(self, file, line):
|
||||
return self.find_breakpoint("%s:%d" % (file, line)) is not None
|
||||
|
||||
def breakpoint_lines(self, file):
|
||||
"""1-based lines in *file* that currently have breakpoints."""
|
||||
lines = []
|
||||
for bp in self._breakpoints:
|
||||
if bp.file == file or (file and os.path.basename(bp.file)
|
||||
== os.path.basename(file)):
|
||||
lines.append(bp.line)
|
||||
return sorted(lines)
|
||||
|
||||
def enable_breakpoint(self, bp_id, enable):
|
||||
"""Enable/disable breakpoint *bp_id*. Live: pdb
|
||||
enable/disable; staged: the flag is stored and applied on
|
||||
insert. Returns False when the id is unknown."""
|
||||
bp = next((b for b in self._breakpoints if b.id == bp_id),
|
||||
None)
|
||||
if bp is None:
|
||||
if bp_id == 0:
|
||||
return False
|
||||
self.last_error = "no breakpoint %r" % bp_id
|
||||
return False
|
||||
if bp.id and self.state == STATE_STOPPED and self.is_alive():
|
||||
if not self._send("enable %d" % bp.id if enable
|
||||
else "disable %d" % bp.id):
|
||||
return False
|
||||
if not self._wait_prompt(
|
||||
self.settings.cmd_timeout_ms / 1000.0):
|
||||
self.last_error = "pdb did not answer enable/disable"
|
||||
return False
|
||||
bp.enabled = bool(enable)
|
||||
return True
|
||||
|
||||
def refresh_breakpoints(self):
|
||||
"""Re-list breakpoints from pdb (live only) and sync ids,
|
||||
enabled flags and hit counts. Staged entries are untouched."""
|
||||
if self.state != STATE_STOPPED or not self.is_alive():
|
||||
return False
|
||||
if not self._send("break"):
|
||||
return False
|
||||
if not self._wait_prompt(
|
||||
self.settings.cmd_timeout_ms / 1000.0):
|
||||
return False
|
||||
response = self._last_response()
|
||||
listed = {}
|
||||
last_id = None
|
||||
for line in response.splitlines():
|
||||
row = _BP_ROW_RE.match(line.strip())
|
||||
if row:
|
||||
last_id = int(row.group(1))
|
||||
listed[last_id] = {
|
||||
"enabled": row.group(2) == "yes",
|
||||
"file": row.group(3),
|
||||
"line": int(row.group(4)),
|
||||
"hits": 0,
|
||||
}
|
||||
continue
|
||||
hits = _BP_HITS_RE.search(line)
|
||||
if hits and last_id in listed:
|
||||
listed[last_id]["hits"] = int(hits.group(1))
|
||||
for bp in self._breakpoints:
|
||||
if bp.id and bp.id in listed:
|
||||
info = listed[bp.id]
|
||||
bp.enabled = info["enabled"]
|
||||
bp.hits = info["hits"]
|
||||
bp.file = info["file"]
|
||||
bp.line = info["line"]
|
||||
return True
|
||||
|
||||
# --- inspection (valid while stopped) ---------------------------------------
|
||||
|
||||
def _eval(self, command, timeout_s=None):
|
||||
"""Send a query command (``p ...`` / ``where``) while
|
||||
stopped and return its reply text, or None."""
|
||||
if self.state != STATE_STOPPED or not self.is_alive():
|
||||
return None
|
||||
if timeout_s is None:
|
||||
timeout_s = self.settings.cmd_timeout_ms / 1000.0
|
||||
if not self._send(command):
|
||||
return None
|
||||
if not self._wait_prompt(timeout_s):
|
||||
return None
|
||||
return self._last_response()
|
||||
|
||||
def evaluate(self, expr):
|
||||
"""Evaluate *expr* in the current frame. Returns
|
||||
(value_repr, error): on failure value is None and error
|
||||
holds pdb's ``*** ...`` message."""
|
||||
expr = (expr or "").strip()
|
||||
if not expr:
|
||||
return None, "empty expression"
|
||||
response = self._eval("p %s" % expr)
|
||||
if response is None:
|
||||
return None, "not stopped at a breakpoint"
|
||||
lines = [ln for ln in response.splitlines() if ln.strip()]
|
||||
for line in lines:
|
||||
if line.startswith("***"):
|
||||
return None, line[3:].strip()
|
||||
if not lines:
|
||||
return None, "no result"
|
||||
return lines[0], ""
|
||||
|
||||
def list_locals(self):
|
||||
"""Locals of the current frame as [Variable]. Dunder names
|
||||
are excluded by the query itself; on any parse failure the
|
||||
raw reply is returned as a single variable."""
|
||||
response = self._eval(_LOCALS_QUERY)
|
||||
if response is None:
|
||||
return []
|
||||
text = response.strip()
|
||||
try:
|
||||
items = ast.literal_eval(text)
|
||||
except (ValueError, SyntaxError):
|
||||
items = None
|
||||
if not isinstance(items, list):
|
||||
return [Variable("<locals>", "", text)] if text else []
|
||||
out = []
|
||||
for item in items:
|
||||
if isinstance(item, (list, tuple)) and len(item) == 3:
|
||||
out.append(Variable(str(item[0]), str(item[1]),
|
||||
str(item[2])))
|
||||
return out
|
||||
|
||||
def list_frames(self):
|
||||
"""Stack frames from ``where`` (all frames, innermost last
|
||||
in pdb's listing — reversed here so level 0 is innermost)."""
|
||||
response = self._eval("where")
|
||||
if response is None:
|
||||
return []
|
||||
frames = []
|
||||
for line in response.splitlines():
|
||||
parsed = _parse_frame_line(line)
|
||||
if parsed is not None:
|
||||
frames.append(parsed)
|
||||
frames.reverse()
|
||||
for i, frame in enumerate(frames):
|
||||
frame.level = i
|
||||
return frames
|
||||
|
||||
def add_watch(self, expr):
|
||||
"""Add a watch expression (kept in-session, refreshed by
|
||||
refresh_watches). False when empty or already watched."""
|
||||
expr = (expr or "").strip()
|
||||
if not expr or expr in self._watch_exprs:
|
||||
return False
|
||||
self._watch_exprs.append(expr)
|
||||
self.refresh_watches()
|
||||
return True
|
||||
|
||||
def remove_watch(self, expr):
|
||||
if expr in self._watch_exprs:
|
||||
self._watch_exprs.remove(expr)
|
||||
self._watches = [w for w in self._watches
|
||||
if w.name != expr]
|
||||
return True
|
||||
return False
|
||||
|
||||
def watch_exprs(self):
|
||||
return list(self._watch_exprs)
|
||||
|
||||
def refresh_watches(self):
|
||||
if self.state != STATE_STOPPED:
|
||||
return False
|
||||
out = []
|
||||
for expr in self._watch_exprs:
|
||||
value, err = self.evaluate(expr)
|
||||
out.append(Variable(expr, "",
|
||||
value if err == "" else
|
||||
"*** %s" % err))
|
||||
self._watches = out
|
||||
return True
|
||||
|
||||
def refresh_on_stop(self):
|
||||
"""Refresh locals + frames + watches after a stop (best
|
||||
effort; a failure leaves the previous values in place)."""
|
||||
if self.state != STATE_STOPPED:
|
||||
return
|
||||
try:
|
||||
self._locals = self.list_locals()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = self.list_frames()
|
||||
if frames:
|
||||
self._frames = frames
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self.refresh_watches()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _find_main_def_line(script_path):
|
||||
"""Line number of ``def main(...):`` in *script_path*, or None
|
||||
(used by the break_on_main setting)."""
|
||||
try:
|
||||
with open(script_path, "r", encoding="utf-8") as handle:
|
||||
for number, line in enumerate(handle, start=1):
|
||||
if re.match(r"def\s+main\s*\(", line):
|
||||
return number
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
@@ -0,0 +1,744 @@
|
||||
"""Debugger window — GTK UI over the pdb session (debugger.py).
|
||||
|
||||
Mirrors the C debugger window layout (src/debugger_ui.cpp): a
|
||||
toolbar (Run / Continue / Step Over / Step Into / Step Out / Stop /
|
||||
Restart / Settings), a Target row (script + args + Browse), a status
|
||||
line, a middle pane with the breakpoint list on the left and
|
||||
Locals / Watches / Stack on the right, and the debuggee's output
|
||||
console at the bottom. The window polls the session on a 200ms GTK
|
||||
timeout; all pdb traffic stays in the backend.
|
||||
|
||||
Placement note (vs C): the C window is a separate top-level window
|
||||
opened from the Debug menu, and so is this one — same placement. It
|
||||
is opened from the Code window's Debug menu (the menu bar lives in
|
||||
the Code window in this port) and its target defaults to the
|
||||
generated script.
|
||||
|
||||
The eight documented C debugger bugs, UI half (session half in
|
||||
debugger.py):
|
||||
|
||||
1. Breakpoint pane too narrow — the pane requests 420px wide and
|
||||
the Location column 320px minimum, so ``file:line`` is readable.
|
||||
2. List selection doesn't stick — _refresh_breakpoints() updates
|
||||
store rows IN PLACE by breakpoint id (never rebuilds the model)
|
||||
and re-selects the previously selected id afterwards; the 150ms
|
||||
poll rebuild that lost selection in C cannot happen here.
|
||||
3. Step Out in main() modal — no modal exists; session.step_out()
|
||||
degrades to Continue at module level.
|
||||
4. Stop times out on a GUI app — session.stop() kills the process
|
||||
group; the Stop button just calls it.
|
||||
5. Run from Stopped/Exited ignores Target — Run always restarts
|
||||
with the current target entry / stored target.
|
||||
6. break-on-main temp breakpoint persisted — no temp breakpoints
|
||||
exist (see debugger.py).
|
||||
7. Watch clicks open a search popup — the watch and locals trees
|
||||
have search disabled (set_enable_search(False)) and there is no
|
||||
SearchEntry anywhere in this window, so clicking a row can only
|
||||
select it.
|
||||
8. Enabled-checkbox toggles ignored — the toggle handler applies
|
||||
the change to the session FIRST and then updates the store row
|
||||
directly; the row is never rebuilt under it.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import gi
|
||||
|
||||
gi.require_version("Gtk", "3.0")
|
||||
gi.require_version("Gdk", "3.0")
|
||||
|
||||
from gi.repository import Gdk, GLib, Gtk # noqa: E402
|
||||
|
||||
from lightgui.debugger import (PdbSession, STATE_EXITED, STATE_IDLE, # noqa: E402
|
||||
STATE_RUNNING, STATE_STOPPED,
|
||||
parse_breakpoint_location)
|
||||
|
||||
# The UI never waits longer than this for a stop after an exec
|
||||
# command; a longer-running target is picked up by the poll.
|
||||
UI_EXEC_TIMEOUT_S = 0.5
|
||||
|
||||
# Bug 1: breakpoint pane wide enough to read file:line.
|
||||
BP_PANE_MIN_WIDTH = 420
|
||||
BP_LOCATION_MIN_WIDTH = 320
|
||||
|
||||
|
||||
class DebuggerWindow:
|
||||
"""The debugger top-level window. Owns one PdbSession."""
|
||||
|
||||
def __init__(self, parent=None, target=None, on_status=None,
|
||||
on_stop_location=None):
|
||||
self.session = PdbSession()
|
||||
self.on_status = on_status
|
||||
# Called with (file, line) on every fresh stop, so the app
|
||||
# can scroll the Code window to the stopped line.
|
||||
self.on_stop_location = on_stop_location
|
||||
self._selected_bp_id = None
|
||||
self._output_shown = 0
|
||||
self._last_stop_seq = 0
|
||||
self._poll_id = None
|
||||
|
||||
self.window = Gtk.Window(title="LightGUI — Debugger")
|
||||
self.window.set_default_size(1100, 700)
|
||||
if parent is not None:
|
||||
self.window.set_transient_for(parent)
|
||||
self.window.connect("delete-event", self._on_delete)
|
||||
self.window.connect("key-press-event", self._on_key_press)
|
||||
|
||||
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
|
||||
self.window.add(vbox)
|
||||
|
||||
toolbar = self._build_toolbar()
|
||||
vbox.pack_start(toolbar, False, False, 0)
|
||||
vbox.pack_start(self._build_target_row(), False, False, 0)
|
||||
|
||||
self.status_label = Gtk.Label(label="Idle", xalign=0)
|
||||
self.status_label.set_margin_start(6)
|
||||
vbox.pack_start(self.status_label, False, False, 0)
|
||||
self.source_label = Gtk.Label(label="", xalign=0)
|
||||
self.source_label.set_margin_start(6)
|
||||
vbox.pack_start(self.source_label, False, False, 0)
|
||||
|
||||
mid = Gtk.Paned(orientation=Gtk.Orientation.HORIZONTAL)
|
||||
mid.set_position(430)
|
||||
mid.pack1(self._build_breakpoint_pane(), True, False)
|
||||
mid.pack2(self._build_inspect_pane(), True, False)
|
||||
vbox.pack_start(mid, True, True, 0)
|
||||
|
||||
vbox.pack_start(Gtk.Label(label="Output", xalign=0),
|
||||
False, False, 0)
|
||||
self.output_view = Gtk.TextView()
|
||||
self.output_view.set_editable(False)
|
||||
self.output_view.set_monospace(True)
|
||||
self.output_buffer = self.output_view.get_buffer()
|
||||
output_scroll = Gtk.ScrolledWindow()
|
||||
output_scroll.set_policy(Gtk.PolicyType.AUTOMATIC,
|
||||
Gtk.PolicyType.AUTOMATIC)
|
||||
output_scroll.set_size_request(-1, 150)
|
||||
output_scroll.add(self.output_view)
|
||||
vbox.pack_start(output_scroll, False, True, 0)
|
||||
|
||||
vbox.show_all()
|
||||
if target:
|
||||
self.set_target(target)
|
||||
self._update_buttons()
|
||||
self._poll_id = GLib.timeout_add(200, self._poll)
|
||||
|
||||
# --- construction -------------------------------------------------------
|
||||
|
||||
def _build_toolbar(self):
|
||||
toolbar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
|
||||
spacing=4)
|
||||
toolbar.set_margin_start(4)
|
||||
toolbar.set_margin_end(4)
|
||||
toolbar.set_margin_top(4)
|
||||
toolbar.set_margin_bottom(4)
|
||||
self._toolbar_buttons = {}
|
||||
for label, name, callback in (
|
||||
("Run", "run", self._on_run),
|
||||
("Continue (F5)", "continue", self._on_continue),
|
||||
("Step Over (F10)", "step_over", self._on_step_over),
|
||||
("Step Into (F11)", "step_into", self._on_step_into),
|
||||
("Step Out", "step_out", self._on_step_out),
|
||||
("Stop", "stop", self._on_stop),
|
||||
("Restart", "restart", self._on_restart),
|
||||
("Settings", "settings", self._on_settings)):
|
||||
button = Gtk.Button(label=label)
|
||||
button.connect("clicked", lambda _b, cb=callback: cb())
|
||||
toolbar.pack_start(button, False, False, 0)
|
||||
self._toolbar_buttons[name] = button
|
||||
return toolbar
|
||||
|
||||
def _build_target_row(self):
|
||||
row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=4)
|
||||
row.set_margin_start(4)
|
||||
row.set_margin_end(4)
|
||||
row.set_margin_bottom(4)
|
||||
row.pack_start(Gtk.Label(label="Target:"), False, False, 0)
|
||||
self.target_entry = Gtk.Entry()
|
||||
self.target_entry.set_hexpand(True)
|
||||
row.pack_start(self.target_entry, True, True, 0)
|
||||
browse = Gtk.Button(label="Browse…")
|
||||
browse.connect("clicked", self._on_browse)
|
||||
row.pack_start(browse, False, False, 0)
|
||||
row.pack_start(Gtk.Label(label="Args:"), False, False, 0)
|
||||
self.args_entry = Gtk.Entry()
|
||||
self.args_entry.set_hexpand(True)
|
||||
row.pack_start(self.args_entry, True, True, 0)
|
||||
return row
|
||||
|
||||
def _build_breakpoint_pane(self):
|
||||
"""Left pane: add/edit/remove row + breakpoint list. Bug 1:
|
||||
420px minimum width, 320px Location column."""
|
||||
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
|
||||
box.set_margin_start(4)
|
||||
box.set_margin_end(4)
|
||||
|
||||
row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=4)
|
||||
self.bp_entry = Gtk.Entry()
|
||||
self.bp_entry.set_placeholder_text("file.py:line")
|
||||
self.bp_entry.set_hexpand(True)
|
||||
self.bp_entry.connect("activate", lambda _e: self._on_bp_add())
|
||||
row.pack_start(self.bp_entry, True, True, 0)
|
||||
self.bp_add_button = Gtk.Button(label="Add")
|
||||
self.bp_add_button.connect("clicked",
|
||||
lambda _b: self._on_bp_add())
|
||||
row.pack_start(self.bp_add_button, False, False, 0)
|
||||
self.bp_edit_button = Gtk.Button(label="Edit…")
|
||||
self.bp_edit_button.connect("clicked",
|
||||
lambda _b: self._on_bp_edit())
|
||||
row.pack_start(self.bp_edit_button, False, False, 0)
|
||||
self.bp_remove_button = Gtk.Button(label="Remove")
|
||||
self.bp_remove_button.connect("clicked",
|
||||
lambda _b: self._on_bp_remove())
|
||||
row.pack_start(self.bp_remove_button, False, False, 0)
|
||||
box.pack_start(row, False, False, 0)
|
||||
|
||||
# Columns: id, enabled, location, hits.
|
||||
self.bp_store = Gtk.ListStore(int, bool, str, int)
|
||||
tree = Gtk.TreeView(model=self.bp_store)
|
||||
tree.set_headers_visible(True)
|
||||
tree.set_enable_search(False)
|
||||
toggle = Gtk.CellRendererToggle()
|
||||
toggle.connect("toggled", self._on_bp_toggled)
|
||||
col = Gtk.TreeViewColumn("On", toggle, active=1)
|
||||
col.set_min_width(40)
|
||||
tree.append_column(col)
|
||||
text = Gtk.CellRendererText()
|
||||
col = Gtk.TreeViewColumn("Location", text, text=2)
|
||||
col.set_min_width(BP_LOCATION_MIN_WIDTH)
|
||||
col.set_expand(True)
|
||||
tree.append_column(col)
|
||||
hits = Gtk.CellRendererText()
|
||||
col = Gtk.TreeViewColumn("Hits", hits, text=3)
|
||||
col.set_min_width(48)
|
||||
tree.append_column(col)
|
||||
tree.get_selection().connect("changed",
|
||||
self._on_bp_selection_changed)
|
||||
self.bp_tree = tree
|
||||
|
||||
scrolled = Gtk.ScrolledWindow()
|
||||
scrolled.set_policy(Gtk.PolicyType.AUTOMATIC,
|
||||
Gtk.PolicyType.AUTOMATIC)
|
||||
scrolled.set_size_request(BP_PANE_MIN_WIDTH, -1)
|
||||
scrolled.add(tree)
|
||||
box.pack_start(scrolled, True, True, 0)
|
||||
box.pack_start(Gtk.Label(label="Breakpoints", xalign=0),
|
||||
False, False, 0)
|
||||
return box
|
||||
|
||||
def _build_inspect_pane(self):
|
||||
"""Right pane: Locals, Watches (entry row + list), Stack."""
|
||||
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
|
||||
box.set_margin_start(4)
|
||||
box.set_margin_end(4)
|
||||
|
||||
box.pack_start(Gtk.Label(label="Locals", xalign=0),
|
||||
False, False, 0)
|
||||
# Columns: name, type, value.
|
||||
self.locals_store = Gtk.ListStore(str, str, str)
|
||||
tree = Gtk.TreeView(model=self.locals_store)
|
||||
# Bug 7: no search popup — search disabled, no SearchEntry.
|
||||
tree.set_enable_search(False)
|
||||
for title, index in (("Name", 0), ("Type", 1), ("Value", 2)):
|
||||
renderer = Gtk.CellRendererText()
|
||||
col = Gtk.TreeViewColumn(title, renderer, text=index)
|
||||
if index == 2:
|
||||
col.set_expand(True)
|
||||
tree.append_column(col)
|
||||
locals_scroll = Gtk.ScrolledWindow()
|
||||
locals_scroll.set_policy(Gtk.PolicyType.AUTOMATIC,
|
||||
Gtk.PolicyType.AUTOMATIC)
|
||||
locals_scroll.set_size_request(-1, 140)
|
||||
locals_scroll.add(tree)
|
||||
box.pack_start(locals_scroll, True, True, 0)
|
||||
|
||||
watch_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
|
||||
spacing=4)
|
||||
self.watch_entry = Gtk.Entry()
|
||||
self.watch_entry.set_placeholder_text("watch expression")
|
||||
self.watch_entry.set_hexpand(True)
|
||||
self.watch_entry.connect("activate",
|
||||
lambda _e: self._on_watch_add())
|
||||
watch_row.pack_start(self.watch_entry, True, True, 0)
|
||||
watch_add = Gtk.Button(label="Add Watch")
|
||||
watch_add.connect("clicked", lambda _b: self._on_watch_add())
|
||||
watch_row.pack_start(watch_add, False, False, 0)
|
||||
watch_remove = Gtk.Button(label="Remove")
|
||||
watch_remove.connect("clicked",
|
||||
lambda _b: self._on_watch_remove())
|
||||
watch_row.pack_start(watch_remove, False, False, 0)
|
||||
box.pack_start(watch_row, False, False, 0)
|
||||
|
||||
# Columns: expression, value.
|
||||
self.watch_store = Gtk.ListStore(str, str)
|
||||
self.watch_tree = Gtk.TreeView(model=self.watch_store)
|
||||
# Bug 7: clicking a watch row must NOT open a search popup.
|
||||
self.watch_tree.set_enable_search(False)
|
||||
for title, index in (("Watch", 0), ("Value", 1)):
|
||||
renderer = Gtk.CellRendererText()
|
||||
col = Gtk.TreeViewColumn(title, renderer, text=index)
|
||||
if index == 1:
|
||||
col.set_expand(True)
|
||||
self.watch_tree.append_column(col)
|
||||
watch_scroll = Gtk.ScrolledWindow()
|
||||
watch_scroll.set_policy(Gtk.PolicyType.AUTOMATIC,
|
||||
Gtk.PolicyType.AUTOMATIC)
|
||||
watch_scroll.set_size_request(-1, 120)
|
||||
watch_scroll.add(self.watch_tree)
|
||||
box.pack_start(watch_scroll, True, True, 0)
|
||||
|
||||
box.pack_start(Gtk.Label(label="Stack", xalign=0),
|
||||
False, False, 0)
|
||||
# Columns: level, function, location.
|
||||
self.stack_store = Gtk.ListStore(int, str, str)
|
||||
stack_tree = Gtk.TreeView(model=self.stack_store)
|
||||
stack_tree.set_enable_search(False)
|
||||
for title, index in (("Lvl", 0), ("Function", 1),
|
||||
("Location", 2)):
|
||||
renderer = Gtk.CellRendererText()
|
||||
col = Gtk.TreeViewColumn(title, renderer, text=index)
|
||||
if index == 2:
|
||||
col.set_expand(True)
|
||||
stack_tree.append_column(col)
|
||||
stack_scroll = Gtk.ScrolledWindow()
|
||||
stack_scroll.set_policy(Gtk.PolicyType.AUTOMATIC,
|
||||
Gtk.PolicyType.AUTOMATIC)
|
||||
stack_scroll.set_size_request(-1, 120)
|
||||
stack_scroll.add(stack_tree)
|
||||
box.pack_start(stack_scroll, True, True, 0)
|
||||
return box
|
||||
|
||||
# --- visibility / target --------------------------------------------------
|
||||
|
||||
def show(self):
|
||||
self.window.show_all()
|
||||
self.window.present()
|
||||
|
||||
def hide(self):
|
||||
self.window.hide()
|
||||
|
||||
def is_visible(self):
|
||||
return self.window.get_visible()
|
||||
|
||||
def set_target(self, path):
|
||||
if path:
|
||||
self.target_entry.set_text(path)
|
||||
|
||||
def get_target(self):
|
||||
return self.target_entry.get_text().strip()
|
||||
|
||||
def toggle_breakpoint(self, file, line):
|
||||
"""Toggle a breakpoint at (*file*, *line*) — the shared
|
||||
session entry point for the Code window / Debug menu. With
|
||||
a live session the change applies at once, otherwise it is
|
||||
staged. Returns True when a breakpoint is now set."""
|
||||
now_set = self.session.toggle_breakpoint(file, line)
|
||||
self._refresh_breakpoints()
|
||||
self._update_buttons()
|
||||
return now_set
|
||||
|
||||
def has_breakpoint(self, file, line):
|
||||
return self.session.has_breakpoint(file, line)
|
||||
|
||||
def breakpoint_lines(self, file):
|
||||
return self.session.breakpoint_lines(file)
|
||||
|
||||
# --- toolbar actions -------------------------------------------------------
|
||||
|
||||
def _on_run(self):
|
||||
state = self.session.state
|
||||
if state == STATE_IDLE:
|
||||
target = self.get_target()
|
||||
if not target:
|
||||
self._status("No target — Generate first, or Browse "
|
||||
"to a script")
|
||||
return
|
||||
self._output_shown = 0
|
||||
self.output_buffer.set_text("")
|
||||
self.session.clear_output()
|
||||
if not self.session.start(target,
|
||||
self.args_entry.get_text()):
|
||||
self._status("Start failed: %s"
|
||||
% self.session.last_error)
|
||||
else:
|
||||
self._status("Stopped at entry — %s"
|
||||
% self._frame_text())
|
||||
else:
|
||||
# Bug 5: Run from Stopped/Exited restarts with the
|
||||
# CURRENT target (session.run re-uses the stored one).
|
||||
self._output_shown = 0
|
||||
self.output_buffer.set_text("")
|
||||
self.session.clear_output()
|
||||
if not self.session.run():
|
||||
self._status("Run failed: %s"
|
||||
% self.session.last_error)
|
||||
else:
|
||||
self._status("Restarted — %s" % self._frame_text())
|
||||
self._after_state_change()
|
||||
|
||||
def _on_continue(self):
|
||||
if self.session.cont(timeout_s=UI_EXEC_TIMEOUT_S):
|
||||
self._status("Continued — %s" % self._frame_text())
|
||||
else:
|
||||
self._status("Continue failed: %s"
|
||||
% self.session.last_error)
|
||||
self._after_state_change()
|
||||
|
||||
def _on_step_over(self):
|
||||
if self.session.step_over(timeout_s=UI_EXEC_TIMEOUT_S):
|
||||
self._status("Stepped over — %s" % self._frame_text())
|
||||
else:
|
||||
self._status("Step Over failed: %s"
|
||||
% self.session.last_error)
|
||||
self._after_state_change()
|
||||
|
||||
def _on_step_into(self):
|
||||
if self.session.step_into(timeout_s=UI_EXEC_TIMEOUT_S):
|
||||
self._status("Stepped into — %s" % self._frame_text())
|
||||
else:
|
||||
self._status("Step Into failed: %s"
|
||||
% self.session.last_error)
|
||||
self._after_state_change()
|
||||
|
||||
def _on_step_out(self):
|
||||
if self.session.step_out(timeout_s=UI_EXEC_TIMEOUT_S):
|
||||
self._status("Stepped out — %s" % self._frame_text())
|
||||
else:
|
||||
self._status("Step Out failed: %s"
|
||||
% self.session.last_error)
|
||||
self._after_state_change()
|
||||
|
||||
def _on_stop(self):
|
||||
# Bug 4: session.stop() kills the process group when the
|
||||
# debuggee is running, so this cannot hang on a GUI app.
|
||||
self.session.stop()
|
||||
self._status("Stopped")
|
||||
self._after_state_change()
|
||||
|
||||
def _on_restart(self):
|
||||
if not self.session.restart():
|
||||
self._status("Restart failed: %s"
|
||||
% self.session.last_error)
|
||||
else:
|
||||
self._status("Restarted — %s" % self._frame_text())
|
||||
self._after_state_change()
|
||||
|
||||
def _on_settings(self):
|
||||
dialog = Gtk.Dialog(title="Debugger Settings",
|
||||
parent=self.window,
|
||||
flags=Gtk.DialogFlags.MODAL
|
||||
| Gtk.DialogFlags.DESTROY_WITH_PARENT)
|
||||
dialog.add_button("Close", Gtk.ResponseType.CLOSE)
|
||||
area = dialog.get_content_area()
|
||||
settings = self.session.settings
|
||||
stop_entry = Gtk.CheckButton(
|
||||
label="Stop on entry (stop at the first line on start)")
|
||||
stop_entry.set_active(settings.stop_on_entry)
|
||||
area.pack_start(stop_entry, False, False, 4)
|
||||
break_main = Gtk.CheckButton(
|
||||
label="Break on main (persistent breakpoint on def main)")
|
||||
break_main.set_active(settings.break_on_main)
|
||||
area.pack_start(break_main, False, False, 4)
|
||||
area.show_all()
|
||||
dialog.run()
|
||||
settings.stop_on_entry = stop_entry.get_active()
|
||||
settings.break_on_main = break_main.get_active()
|
||||
dialog.destroy()
|
||||
|
||||
def _on_browse(self):
|
||||
dialog = Gtk.FileChooserDialog(
|
||||
title="Choose script to debug", parent=self.window,
|
||||
action=Gtk.FileChooserAction.OPEN,
|
||||
buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
|
||||
Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT))
|
||||
if dialog.run() == Gtk.ResponseType.ACCEPT:
|
||||
self.set_target(dialog.get_filename())
|
||||
dialog.destroy()
|
||||
|
||||
def _on_key_press(self, _window, event):
|
||||
key_name = Gdk.keyval_name(event.keyval)
|
||||
if key_name == "F5":
|
||||
self._on_continue()
|
||||
return True
|
||||
if key_name == "F10":
|
||||
self._on_step_over()
|
||||
return True
|
||||
if key_name == "F11":
|
||||
self._on_step_into()
|
||||
return True
|
||||
return False
|
||||
|
||||
# --- breakpoints ------------------------------------------------------------
|
||||
|
||||
def _on_bp_add(self):
|
||||
location = self.bp_entry.get_text().strip()
|
||||
if not location:
|
||||
return
|
||||
if parse_breakpoint_location(location) is None:
|
||||
self._status("Bad breakpoint location: %r (want "
|
||||
"file.py:line)" % location)
|
||||
return
|
||||
bp = self.session.add_breakpoint(location)
|
||||
if bp is None:
|
||||
self._status("Cannot set breakpoint: %s"
|
||||
% self.session.last_error)
|
||||
else:
|
||||
self.bp_entry.set_text("")
|
||||
self._status("Breakpoint %s at %s"
|
||||
% (bp.id or "(staged)", location))
|
||||
self._refresh_breakpoints()
|
||||
self._update_buttons()
|
||||
|
||||
def _on_bp_remove(self):
|
||||
bp_id = self._selected_bp_id
|
||||
if bp_id is None:
|
||||
return
|
||||
if self.session.remove_breakpoint(bp_id):
|
||||
self._selected_bp_id = None
|
||||
else:
|
||||
self._status("Cannot remove breakpoint: %s"
|
||||
% self.session.last_error)
|
||||
self._refresh_breakpoints()
|
||||
self._update_buttons()
|
||||
|
||||
def _on_bp_edit(self):
|
||||
bp_id = self._selected_bp_id
|
||||
if bp_id is None:
|
||||
return
|
||||
bp = next((b for b in self.session.breakpoints()
|
||||
if b.id == bp_id), None)
|
||||
if bp is None:
|
||||
return
|
||||
dialog = Gtk.Dialog(title="Edit Breakpoint %d" % bp_id,
|
||||
parent=self.window,
|
||||
flags=Gtk.DialogFlags.MODAL
|
||||
| Gtk.DialogFlags.DESTROY_WITH_PARENT)
|
||||
dialog.add_button("Cancel", Gtk.ResponseType.CANCEL)
|
||||
dialog.add_button("Apply", Gtk.ResponseType.APPLY)
|
||||
area = dialog.get_content_area()
|
||||
area.pack_start(Gtk.Label(label="Location: %s" % bp.location,
|
||||
xalign=0), False, False, 4)
|
||||
cond_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
|
||||
spacing=4)
|
||||
cond_row.pack_start(Gtk.Label(label="Condition:"),
|
||||
False, False, 0)
|
||||
cond_entry = Gtk.Entry()
|
||||
cond_entry.set_text(bp.condition)
|
||||
cond_entry.set_hexpand(True)
|
||||
cond_row.pack_start(cond_entry, True, True, 0)
|
||||
area.pack_start(cond_row, False, False, 4)
|
||||
ignore_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
|
||||
spacing=4)
|
||||
ignore_row.pack_start(Gtk.Label(label="Ignore first N hits:"),
|
||||
False, False, 0)
|
||||
ignore_entry = Gtk.Entry()
|
||||
ignore_entry.set_text(str(bp.ignore_count))
|
||||
ignore_row.pack_start(ignore_entry, False, False, 0)
|
||||
area.pack_start(ignore_row, False, False, 4)
|
||||
area.show_all()
|
||||
if dialog.run() == Gtk.ResponseType.APPLY:
|
||||
try:
|
||||
ignore = int(ignore_entry.get_text().strip() or 0)
|
||||
except ValueError:
|
||||
ignore = bp.ignore_count
|
||||
bp.condition = cond_entry.get_text().strip()
|
||||
bp.ignore_count = max(0, ignore)
|
||||
# Live: re-insert with the new options (pdb has no
|
||||
# in-place edit); staged: the stored options are used
|
||||
# on the next Run.
|
||||
if bp.id and self.session.state == STATE_STOPPED:
|
||||
self.session.remove_breakpoint(bp.id)
|
||||
new_bp = self.session.add_breakpoint(
|
||||
bp.location, condition=bp.condition,
|
||||
ignore_count=bp.ignore_count,
|
||||
enabled=bp.enabled)
|
||||
if new_bp is not None:
|
||||
# Re-inserted under a new pdb id: keep the
|
||||
# selection on the new row.
|
||||
self._selected_bp_id = new_bp.id
|
||||
dialog.destroy()
|
||||
self._refresh_breakpoints()
|
||||
|
||||
def _on_bp_toggled(self, _renderer, path):
|
||||
"""Bug 8: apply the toggle to the session FIRST, then update
|
||||
the store row directly — never rebuild the model under the
|
||||
click, so the toggle cannot be lost."""
|
||||
tree_iter = self.bp_store.get_iter(path)
|
||||
bp_id = self.bp_store.get_value(tree_iter, 0)
|
||||
current = self.bp_store.get_value(tree_iter, 1)
|
||||
if self.session.enable_breakpoint(bp_id, not current):
|
||||
self.bp_store.set_value(tree_iter, 1, not current)
|
||||
else:
|
||||
self._status("Cannot toggle breakpoint: %s"
|
||||
% self.session.last_error)
|
||||
|
||||
def _on_bp_selection_changed(self, selection):
|
||||
_model, tree_iter = selection.get_selected()
|
||||
if tree_iter is None:
|
||||
self._selected_bp_id = None
|
||||
else:
|
||||
self._selected_bp_id = self.bp_store.get_value(tree_iter, 0)
|
||||
self._update_buttons()
|
||||
|
||||
def _refresh_breakpoints(self):
|
||||
"""Bug 2: update rows IN PLACE by breakpoint id — add rows
|
||||
for new breakpoints, drop rows for removed ones, update the
|
||||
rest. The model is never rebuilt, so the selection (kept as
|
||||
an id) survives every refresh."""
|
||||
wanted = {bp.id: bp for bp in self.session.breakpoints()}
|
||||
# Staged breakpoints share id 0; key them by location.
|
||||
staged = {bp.location: bp for bp in self.session.breakpoints()
|
||||
if bp.id == 0}
|
||||
existing = {}
|
||||
tree_iter = self.bp_store.get_iter_first()
|
||||
while tree_iter is not None:
|
||||
bp_id = self.bp_store.get_value(tree_iter, 0)
|
||||
location = self.bp_store.get_value(tree_iter, 2)
|
||||
existing[(bp_id, location)] = tree_iter
|
||||
tree_iter = self.bp_store.iter_next(tree_iter)
|
||||
for bp in self.session.breakpoints():
|
||||
key = (bp.id, bp.location)
|
||||
row = (bp.id, bp.enabled, bp.location, bp.hits)
|
||||
if key in existing:
|
||||
tree_iter = existing.pop(key)
|
||||
self.bp_store.set_row(tree_iter, row)
|
||||
else:
|
||||
self.bp_store.append(row)
|
||||
for tree_iter in existing.values():
|
||||
self.bp_store.remove(tree_iter)
|
||||
# Restore the selection by id (bug 2).
|
||||
if self._selected_bp_id is not None:
|
||||
tree_iter = self.bp_store.get_iter_first()
|
||||
while tree_iter is not None:
|
||||
if self.bp_store.get_value(tree_iter, 0) \
|
||||
== self._selected_bp_id:
|
||||
self.bp_tree.get_selection().select_iter(tree_iter)
|
||||
break
|
||||
tree_iter = self.bp_store.iter_next(tree_iter)
|
||||
|
||||
# --- watches ------------------------------------------------------------------
|
||||
|
||||
def _on_watch_add(self):
|
||||
expr = self.watch_entry.get_text().strip()
|
||||
if not expr:
|
||||
return
|
||||
if self.session.add_watch(expr):
|
||||
self.watch_entry.set_text("")
|
||||
self._refresh_watches()
|
||||
self._update_buttons()
|
||||
|
||||
def _on_watch_remove(self):
|
||||
selection = self.watch_tree.get_selection()
|
||||
_model, tree_iter = selection.get_selected()
|
||||
if tree_iter is None:
|
||||
return
|
||||
expr = self.watch_store.get_value(tree_iter, 0)
|
||||
self.session.remove_watch(expr)
|
||||
self._refresh_watches()
|
||||
|
||||
def _refresh_watches(self):
|
||||
self.watch_store.clear()
|
||||
for watch in self.session.watches():
|
||||
self.watch_store.append([watch.name, watch.value])
|
||||
|
||||
# --- refresh / poll ---------------------------------------------------------------
|
||||
|
||||
def _refresh_locals(self):
|
||||
self.locals_store.clear()
|
||||
for var in self.session.locals():
|
||||
self.locals_store.append([var.name, var.type_name,
|
||||
var.value])
|
||||
|
||||
def _refresh_stack(self):
|
||||
self.stack_store.clear()
|
||||
for frame in self.session.frames():
|
||||
self.stack_store.append(
|
||||
[frame.level, frame.function,
|
||||
"%s:%d" % (frame.file, frame.line)])
|
||||
|
||||
def _refresh_all(self):
|
||||
self._refresh_breakpoints()
|
||||
self._refresh_locals()
|
||||
self._refresh_watches()
|
||||
self._refresh_stack()
|
||||
|
||||
def _frame_text(self):
|
||||
stop = self.session.last_stop
|
||||
frame = stop.frame
|
||||
if not frame.file:
|
||||
return "state: %s" % self.session.state
|
||||
return "%s:%d %s (%s)" % (os.path.basename(frame.file),
|
||||
frame.line, frame.function,
|
||||
stop.reason or self.session.state)
|
||||
|
||||
def _status(self, text):
|
||||
self.status_label.set_text(text)
|
||||
if self.on_status is not None:
|
||||
self.on_status(text)
|
||||
|
||||
def _after_state_change(self):
|
||||
self._refresh_all()
|
||||
self._update_buttons()
|
||||
self._drain_output()
|
||||
|
||||
def _drain_output(self):
|
||||
"""Append new debuggee output to the console."""
|
||||
text = self.session.target_output()
|
||||
if len(text) > self._output_shown:
|
||||
chunk = text[self._output_shown:]
|
||||
self._output_shown = len(text)
|
||||
end = self.output_buffer.get_end_iter()
|
||||
self.output_buffer.insert(end, chunk)
|
||||
end = self.output_buffer.get_end_iter()
|
||||
self.output_view.scroll_to_iter(end, 0.0, False, 0.0, 0.0)
|
||||
|
||||
def _poll(self):
|
||||
"""200ms poll: drain output; on a fresh stop, refresh the
|
||||
panes and tell the app where execution stopped."""
|
||||
if not self.is_visible():
|
||||
return True
|
||||
self._drain_output()
|
||||
if self.session.poll_events():
|
||||
self._after_state_change()
|
||||
stop = self.session.last_stop
|
||||
self._status("Stopped — %s" % self._frame_text())
|
||||
if stop.frame.file and self.on_stop_location is not None:
|
||||
self.on_stop_location(stop.frame.file, stop.frame.line)
|
||||
elif self.session.state == STATE_RUNNING:
|
||||
self.status_label.set_text("Running…")
|
||||
self._update_buttons()
|
||||
return True
|
||||
|
||||
def _update_buttons(self):
|
||||
state = self.session.state
|
||||
buttons = self._toolbar_buttons
|
||||
buttons["run"].set_sensitive(state in (STATE_IDLE,
|
||||
STATE_STOPPED,
|
||||
STATE_EXITED))
|
||||
for name in ("continue", "step_over", "step_into", "step_out"):
|
||||
buttons[name].set_sensitive(state == STATE_STOPPED)
|
||||
buttons["stop"].set_sensitive(state in (STATE_RUNNING,
|
||||
STATE_STOPPED))
|
||||
buttons["restart"].set_sensitive(state != STATE_IDLE)
|
||||
# Breakpoint add/remove needs pdb at a prompt (or no session
|
||||
# yet, when the entry is staged for the next Run).
|
||||
can_edit_bp = state in (STATE_IDLE, STATE_STOPPED, STATE_EXITED)
|
||||
self.bp_add_button.set_sensitive(can_edit_bp)
|
||||
self.bp_edit_button.set_sensitive(
|
||||
can_edit_bp and self._selected_bp_id is not None)
|
||||
self.bp_remove_button.set_sensitive(
|
||||
can_edit_bp and self._selected_bp_id is not None)
|
||||
|
||||
def _on_delete(self, _window, _event):
|
||||
# Closing the window hides it; the session keeps its
|
||||
# breakpoints (C behaviour) and is only ended by Stop or
|
||||
# when the designer quits.
|
||||
self.hide()
|
||||
return True
|
||||
|
||||
def destroy(self):
|
||||
if self._poll_id is not None:
|
||||
GLib.source_remove(self._poll_id)
|
||||
self._poll_id = None
|
||||
self.session.shutdown()
|
||||
self.window.destroy()
|
||||
@@ -0,0 +1,351 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,379 @@
|
||||
"""Tests for lightgui.debugger (Phase 5): the pdb session against
|
||||
small test scripts, plus breakpoint enable/disable toggling.
|
||||
|
||||
Logic tests run anywhere (pdb is stdlib). The debugger-window
|
||||
widget tests need a display and are skipped when Gtk cannot
|
||||
initialise (run under Xvfb, :99).
|
||||
"""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from lightgui.debugger import (
|
||||
Breakpoint, DebuggerSettings, PdbSession, STATE_EXITED,
|
||||
STATE_IDLE, STATE_STOPPED, parse_breakpoint_location)
|
||||
|
||||
SCRIPT = """\
|
||||
x = 1
|
||||
y = 2
|
||||
def helper(a):
|
||||
b = a + 10
|
||||
return b
|
||||
z = helper(x)
|
||||
total = y + z
|
||||
print("total", total)
|
||||
"""
|
||||
|
||||
# Line numbers in SCRIPT (1-based): helper def 3, b = a + 10 is 4,
|
||||
# z = helper(x) is 6, total = y + z is 7, print is 8.
|
||||
SLEEPER = """\
|
||||
import time
|
||||
print("awake")
|
||||
time.sleep(60)
|
||||
print("done")
|
||||
"""
|
||||
|
||||
|
||||
def _write_script(folder, name, text):
|
||||
path = os.path.join(folder, name)
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
handle.write(text)
|
||||
return path
|
||||
|
||||
|
||||
class LocationTests(unittest.TestCase):
|
||||
def test_file_line(self):
|
||||
self.assertEqual(parse_breakpoint_location("/tmp/a.py:12"),
|
||||
("/tmp/a.py", 12, ""))
|
||||
|
||||
def test_function_name(self):
|
||||
self.assertEqual(parse_breakpoint_location("main"),
|
||||
("", 0, "main"))
|
||||
|
||||
def test_bad_locations(self):
|
||||
for bad in ("", " ", "a.py:0", "a.py:-3", "a.py:x",
|
||||
"a.py:", "12"):
|
||||
self.assertIsNone(parse_breakpoint_location(bad),
|
||||
bad)
|
||||
|
||||
|
||||
class SessionTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.script = _write_script(self.tmp.name, "t.py", SCRIPT)
|
||||
self.session = PdbSession()
|
||||
|
||||
def tearDown(self):
|
||||
self.session.shutdown()
|
||||
# No pdb subprocess may survive a test.
|
||||
self.assertFalse(self.session.is_alive())
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_start_stops_at_entry(self):
|
||||
self.assertTrue(self.session.start(self.script))
|
||||
self.assertEqual(self.session.state, STATE_STOPPED)
|
||||
self.assertEqual(self.session.last_stop.reason, "entry")
|
||||
self.assertEqual(self.session.last_stop.frame.line, 1)
|
||||
self.assertEqual(self.session.last_stop.frame.function,
|
||||
"<module>")
|
||||
|
||||
def test_start_missing_script(self):
|
||||
self.assertFalse(
|
||||
self.session.start(os.path.join(self.tmp.name, "nope.py")))
|
||||
self.assertEqual(self.session.state, STATE_IDLE)
|
||||
self.assertIn("no such script", self.session.last_error)
|
||||
|
||||
def test_breakpoint_hit_and_step_over(self):
|
||||
self.assertTrue(self.session.start(self.script))
|
||||
bp = self.session.add_breakpoint("%s:6" % self.script)
|
||||
self.assertIsNotNone(bp)
|
||||
self.assertGreater(bp.id, 0)
|
||||
self.assertTrue(self.session.cont())
|
||||
self.assertEqual(self.session.state, STATE_STOPPED)
|
||||
self.assertEqual(self.session.last_stop.reason,
|
||||
"breakpoint-hit")
|
||||
self.assertEqual(self.session.last_stop.breakpoint_id, bp.id)
|
||||
self.assertEqual(self.session.last_stop.frame.line, 6)
|
||||
# Step over the helper() call: lands on line 7 BEFORE it
|
||||
# executes, so z is set but total is not yet defined.
|
||||
self.assertTrue(self.session.step_over())
|
||||
self.assertEqual(self.session.last_stop.frame.line, 7)
|
||||
value, err = self.session.evaluate("z")
|
||||
self.assertEqual(err, "")
|
||||
self.assertEqual(value, "11")
|
||||
value, err = self.session.evaluate("total")
|
||||
self.assertIsNone(value)
|
||||
self.assertIn("NameError", err)
|
||||
# One more step executes line 7: total is now 13.
|
||||
self.assertTrue(self.session.step_over())
|
||||
self.assertEqual(self.session.last_stop.frame.line, 8)
|
||||
value, err = self.session.evaluate("total")
|
||||
self.assertEqual(err, "")
|
||||
self.assertEqual(value, "13")
|
||||
|
||||
def test_step_into_and_step_out(self):
|
||||
self.assertTrue(self.session.start(self.script))
|
||||
self.session.add_breakpoint("%s:6" % self.script)
|
||||
self.assertTrue(self.session.cont())
|
||||
self.assertEqual(self.session.last_stop.frame.line, 6)
|
||||
# Step into helper(): pdb stops at the --Call-- line, the
|
||||
# def line (3), with the argument already bound.
|
||||
self.assertTrue(self.session.step_into())
|
||||
self.assertEqual(self.session.last_stop.frame.function,
|
||||
"helper")
|
||||
self.assertEqual(self.session.last_stop.frame.line, 3)
|
||||
value, _err = self.session.evaluate("a")
|
||||
self.assertEqual(value, "1")
|
||||
# Step over the def line: inside the body, line 4.
|
||||
self.assertTrue(self.session.step_over())
|
||||
self.assertEqual(self.session.last_stop.frame.line, 4)
|
||||
# Step out of helper(): back at the call site, line 7.
|
||||
self.assertTrue(self.session.step_out())
|
||||
self.assertEqual(self.session.last_stop.frame.function,
|
||||
"<module>")
|
||||
self.assertEqual(self.session.last_stop.frame.line, 7)
|
||||
|
||||
def test_step_out_at_module_level_does_not_block(self):
|
||||
self.assertTrue(self.session.start(self.script))
|
||||
# At module level, Step Out degrades to Continue: runs to
|
||||
# the end instead of blocking.
|
||||
self.assertTrue(self.session.step_out())
|
||||
self.assertEqual(self.session.state, STATE_EXITED)
|
||||
self.assertIn("total 13", self.session.target_output())
|
||||
|
||||
def test_locals_evaluation(self):
|
||||
self.assertTrue(self.session.start(self.script))
|
||||
self.session.add_breakpoint("%s:7" % self.script)
|
||||
self.assertTrue(self.session.cont())
|
||||
local_map = {var.name: var.value
|
||||
for var in self.session.locals()}
|
||||
self.assertEqual(local_map.get("x"), "1")
|
||||
self.assertEqual(local_map.get("y"), "2")
|
||||
self.assertEqual(local_map.get("z"), "11")
|
||||
# Dunder names are never shown.
|
||||
self.assertNotIn("__builtins__", local_map)
|
||||
self.assertNotIn("__name__", local_map)
|
||||
|
||||
def test_watch_evaluation(self):
|
||||
self.assertTrue(self.session.start(self.script))
|
||||
self.assertTrue(self.session.add_watch("x + y"))
|
||||
self.assertFalse(self.session.add_watch("x + y")) # duplicate
|
||||
self.session.add_breakpoint("%s:7" % self.script)
|
||||
self.assertTrue(self.session.cont())
|
||||
watches = {w.name: w.value for w in self.session.watches()}
|
||||
self.assertEqual(watches.get("x + y"), "3")
|
||||
self.assertTrue(self.session.remove_watch("x + y"))
|
||||
self.assertFalse(self.session.remove_watch("x + y"))
|
||||
|
||||
def test_evaluate_unknown_name(self):
|
||||
self.assertTrue(self.session.start(self.script))
|
||||
value, err = self.session.evaluate("no_such_name")
|
||||
self.assertIsNone(value)
|
||||
self.assertIn("NameError", err)
|
||||
|
||||
def test_stack_trace(self):
|
||||
self.assertTrue(self.session.start(self.script))
|
||||
self.session.add_breakpoint("%s:4" % self.script)
|
||||
self.assertTrue(self.session.cont())
|
||||
frames = self.session.frames()
|
||||
self.assertTrue(any(f.function == "helper" for f in frames))
|
||||
self.assertTrue(any(f.function == "<module>" for f in frames))
|
||||
self.assertEqual(frames[0].function, "helper")
|
||||
|
||||
def test_continue_to_end(self):
|
||||
self.assertTrue(self.session.start(self.script))
|
||||
self.assertTrue(self.session.cont())
|
||||
self.assertEqual(self.session.state, STATE_EXITED)
|
||||
self.assertEqual(self.session.last_stop.reason,
|
||||
"exited-normally")
|
||||
self.assertEqual(self.session.last_stop.exit_code, 0)
|
||||
self.assertIn("total 13", self.session.target_output())
|
||||
|
||||
def test_restart_from_exited(self):
|
||||
self.assertTrue(self.session.start(self.script))
|
||||
self.session.add_breakpoint("%s:6" % self.script)
|
||||
self.assertTrue(self.session.cont())
|
||||
self.assertTrue(self.session.cont())
|
||||
self.assertEqual(self.session.state, STATE_EXITED)
|
||||
# Run from Exited restarts cleanly with the same target and
|
||||
# the same breakpoints — and hits the breakpoint again.
|
||||
self.assertTrue(self.session.run())
|
||||
self.assertEqual(self.session.state, STATE_STOPPED)
|
||||
self.assertTrue(self.session.cont())
|
||||
self.assertEqual(self.session.last_stop.reason,
|
||||
"breakpoint-hit")
|
||||
self.assertEqual(self.session.last_stop.frame.line, 6)
|
||||
|
||||
def test_stop_kills_running_debuggee(self):
|
||||
sleeper = _write_script(self.tmp.name, "sleep.py", SLEEPER)
|
||||
self.assertTrue(self.session.start(sleeper))
|
||||
# Shorten the stop wait: the debuggee sleeps 60s, so any
|
||||
# Continue waits the whole timeout before giving up.
|
||||
self.session.settings.stop_timeout_ms = 2000
|
||||
# Continue past the entry stop: the debuggee prints "awake"
|
||||
# and sleeps 60s, so Continue times out waiting for a stop
|
||||
# and leaves the session Running (by design — the UI poll
|
||||
# picks up the stop when it lands).
|
||||
self.assertTrue(self.session.cont())
|
||||
self.assertEqual(self.session.state, "running")
|
||||
# It printed "awake" and is now sleeping inside time.sleep.
|
||||
self.assertIn("awake", self.session.target_output())
|
||||
proc = self.session._proc
|
||||
self.assertIsNotNone(proc)
|
||||
self.session.stop()
|
||||
self.assertEqual(self.session.state, STATE_EXITED)
|
||||
self.assertIsNotNone(proc.poll()) # reaped, no lingerer
|
||||
|
||||
def test_breakpoint_enable_disable_toggling(self):
|
||||
self.assertTrue(self.session.start(self.script))
|
||||
bp = self.session.add_breakpoint("%s:6" % self.script)
|
||||
self.assertIsNotNone(bp)
|
||||
# Disabled: Continue runs straight to the end.
|
||||
self.assertTrue(self.session.enable_breakpoint(bp.id, False))
|
||||
self.assertFalse(bp.enabled)
|
||||
self.assertTrue(self.session.cont())
|
||||
self.assertEqual(self.session.state, STATE_EXITED)
|
||||
# Restart, re-enable: the breakpoint hits again.
|
||||
self.assertTrue(self.session.run())
|
||||
self.assertTrue(self.session.enable_breakpoint(bp.id, True))
|
||||
self.assertTrue(bp.enabled)
|
||||
self.assertTrue(self.session.cont())
|
||||
self.assertEqual(self.session.last_stop.reason,
|
||||
"breakpoint-hit")
|
||||
self.assertEqual(self.session.last_stop.frame.line, 6)
|
||||
# Refresh syncs the hit count from pdb.
|
||||
self.assertTrue(self.session.refresh_breakpoints())
|
||||
self.assertGreaterEqual(bp.hits, 1)
|
||||
|
||||
def test_staged_breakpoint_before_start(self):
|
||||
bp = self.session.add_breakpoint("%s:6" % self.script)
|
||||
self.assertIsNotNone(bp)
|
||||
self.assertEqual(bp.id, 0) # staged, no pdb yet
|
||||
self.assertTrue(self.session.start(self.script))
|
||||
self.assertGreater(bp.id, 0) # inserted on start
|
||||
self.assertTrue(self.session.cont())
|
||||
self.assertEqual(self.session.last_stop.reason,
|
||||
"breakpoint-hit")
|
||||
|
||||
def test_toggle_breakpoint(self):
|
||||
self.assertFalse(
|
||||
self.session.has_breakpoint(self.script, 6))
|
||||
self.assertTrue(
|
||||
self.session.toggle_breakpoint(self.script, 6))
|
||||
self.assertTrue(self.session.has_breakpoint(self.script, 6))
|
||||
self.assertEqual(
|
||||
self.session.breakpoint_lines(self.script), [6])
|
||||
self.assertFalse(
|
||||
self.session.toggle_breakpoint(self.script, 6))
|
||||
self.assertFalse(
|
||||
self.session.has_breakpoint(self.script, 6))
|
||||
|
||||
def test_break_on_main_setting(self):
|
||||
main_script = _write_script(
|
||||
self.tmp.name, "m.py",
|
||||
"def helper():\n return 1\n\n\ndef main():\n"
|
||||
" x = helper()\n print(x)\n\n\nif __name__ == \"__main__\":\n"
|
||||
" main()\n")
|
||||
session = PdbSession(DebuggerSettings(break_on_main=True))
|
||||
try:
|
||||
self.assertTrue(session.start(main_script))
|
||||
# break_on_main is a persistent breakpoint on def main
|
||||
# (line 5), not a temp one: it is in the list and stays.
|
||||
self.assertIn(5, session.breakpoint_lines(main_script))
|
||||
self.assertTrue(session.cont())
|
||||
self.assertEqual(session.last_stop.reason,
|
||||
"breakpoint-hit")
|
||||
self.assertEqual(session.last_stop.frame.line, 5)
|
||||
finally:
|
||||
session.shutdown()
|
||||
|
||||
def test_stop_on_entry_false_runs_on(self):
|
||||
session = PdbSession(DebuggerSettings(stop_on_entry=False))
|
||||
try:
|
||||
self.assertTrue(session.start(self.script))
|
||||
self.assertEqual(session.state, STATE_EXITED)
|
||||
self.assertIn("total 13", session.target_output())
|
||||
finally:
|
||||
session.shutdown()
|
||||
|
||||
|
||||
try:
|
||||
import gi
|
||||
gi.require_version("Gtk", "3.0")
|
||||
from gi.repository import Gtk
|
||||
_GTK_OK = Gtk.init_check()[0]
|
||||
except Exception:
|
||||
Gtk = None
|
||||
_GTK_OK = False
|
||||
|
||||
if _GTK_OK:
|
||||
from lightgui.debugger_ui import (BP_LOCATION_MIN_WIDTH,
|
||||
BP_PANE_MIN_WIDTH, DebuggerWindow)
|
||||
|
||||
|
||||
class DebuggerWindowTests(unittest.TestCase):
|
||||
"""Widget-level checks for the anti-bug UI rules (bug 1, 2, 7, 8)."""
|
||||
|
||||
def setUp(self):
|
||||
if not _GTK_OK:
|
||||
self.skipTest("needs a display (run under Xvfb)")
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.script = _write_script(self.tmp.name, "t.py", SCRIPT)
|
||||
self.win = DebuggerWindow(target=self.script)
|
||||
|
||||
def tearDown(self):
|
||||
if _GTK_OK:
|
||||
self.win.destroy()
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_breakpoint_pane_is_wide(self):
|
||||
# Bug 1: the pane must be wide enough to read file:line.
|
||||
width, _height = self.win.bp_tree.get_parent().get_size_request()
|
||||
self.assertGreaterEqual(width, BP_PANE_MIN_WIDTH)
|
||||
widths = [col.get_min_width()
|
||||
for col in self.win.bp_tree.get_columns()]
|
||||
self.assertIn(BP_LOCATION_MIN_WIDTH, widths)
|
||||
|
||||
def test_watch_and_locals_trees_have_no_search(self):
|
||||
# Bug 7: clicking a watch/locals row must not open a search
|
||||
# popup — search is disabled on both trees.
|
||||
self.assertFalse(self.win.watch_tree.get_enable_search())
|
||||
# Locals tree is the first tree in the inspect pane; find it
|
||||
# via the locals store's view is not exposed, so check the
|
||||
# watch tree and the breakpoint tree instead.
|
||||
self.assertFalse(self.win.bp_tree.get_enable_search())
|
||||
|
||||
def test_breakpoint_toggle_updates_store_row(self):
|
||||
# Bug 8: toggling the checkbox updates the session and the
|
||||
# store row (staged breakpoint, no live pdb needed).
|
||||
self.assertTrue(
|
||||
self.win.toggle_breakpoint(self.script, 6))
|
||||
self.assertEqual(len(self.win.bp_store), 1)
|
||||
tree_iter = self.win.bp_store.get_iter_first()
|
||||
bp_id = self.win.bp_store.get_value(tree_iter, 0)
|
||||
self.assertTrue(self.win.bp_store.get_value(tree_iter, 1))
|
||||
# Toggle off via the session path the renderer uses.
|
||||
self.assertTrue(
|
||||
self.win.session.enable_breakpoint(bp_id, False))
|
||||
self.win.bp_store.set_value(tree_iter, 1, False)
|
||||
self.assertFalse(self.win.bp_store.get_value(tree_iter, 1))
|
||||
|
||||
def test_breakpoint_refresh_keeps_selection(self):
|
||||
# Bug 2: refreshing the list must not drop the selection.
|
||||
self.win.toggle_breakpoint(self.script, 6)
|
||||
tree_iter = self.win.bp_store.get_iter_first()
|
||||
self.win.bp_tree.get_selection().select_iter(tree_iter)
|
||||
self.assertEqual(self.win._selected_bp_id,
|
||||
self.win.bp_store.get_value(tree_iter, 0))
|
||||
self.win._refresh_breakpoints()
|
||||
_model, selected = \
|
||||
self.win.bp_tree.get_selection().get_selected()
|
||||
self.assertIsNotNone(selected)
|
||||
self.assertEqual(
|
||||
self.win.bp_store.get_value(selected, 2),
|
||||
"%s:6" % self.script)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Tests for lightgui.install_libs (Phase 5): dry-run only.
|
||||
|
||||
Command construction, file list and target paths are checked here.
|
||||
No test performs a real privileged install (no pkexec/sudo run,
|
||||
nothing is written outside a temp dir).
|
||||
"""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from lightgui import install_libs as install
|
||||
|
||||
|
||||
class InstallLibsTests(unittest.TestCase):
|
||||
def test_site_packages_is_a_real_dir(self):
|
||||
site = install.site_packages()
|
||||
self.assertTrue(os.path.isdir(site))
|
||||
self.assertTrue(site.endswith("dist-packages")
|
||||
or site.endswith("site-packages"))
|
||||
|
||||
def test_package_target(self):
|
||||
self.assertEqual(
|
||||
install.package_target("/usr/lib/python3/dist-packages"),
|
||||
"/usr/lib/python3/dist-packages/lightgui")
|
||||
|
||||
def test_launcher_text(self):
|
||||
text = install.launcher_text()
|
||||
self.assertTrue(text.startswith("#!/bin/sh\n"))
|
||||
self.assertIn("python3 -m lightgui", text)
|
||||
|
||||
def test_desktop_text(self):
|
||||
text = install.desktop_text()
|
||||
self.assertIn("[Desktop Entry]", text)
|
||||
self.assertIn("Name=LightGUI", text)
|
||||
self.assertIn("Exec=lightgui", text)
|
||||
|
||||
def test_install_files(self):
|
||||
files = install.install_files(root="/repo",
|
||||
site="/usr/lib/python3/x")
|
||||
dests = [dest for _src, dest in files]
|
||||
self.assertIn("/usr/lib/python3/x/lightgui", dests)
|
||||
self.assertIn(install.LAUNCHER_PATH, dests)
|
||||
self.assertIn(install.DESKTOP_PATH, dests)
|
||||
self.assertEqual(install.LAUNCHER_PATH,
|
||||
"/usr/local/bin/lightgui")
|
||||
self.assertEqual(install.DESKTOP_PATH,
|
||||
"/usr/local/share/applications/lightgui.desktop")
|
||||
|
||||
def test_build_install_script(self):
|
||||
script = install.build_install_script(
|
||||
root="/repo", site="/usr/lib/python3/x")
|
||||
self.assertIn("set -e", script)
|
||||
self.assertIn("cp -r '/repo/lightgui' "
|
||||
"'/usr/lib/python3/x/lightgui'", script)
|
||||
self.assertIn("rm -rf '/usr/lib/python3/x/lightgui'", script)
|
||||
self.assertIn("__pycache__", script)
|
||||
self.assertIn("chmod 755 '/usr/local/bin/lightgui'", script)
|
||||
self.assertIn("chmod 644 '/usr/local/share/applications/"
|
||||
"lightgui.desktop'", script)
|
||||
# No password, no credential, nothing secret in the script.
|
||||
self.assertNotIn("password", script.lower())
|
||||
self.assertNotIn("sudo", script)
|
||||
|
||||
def test_privileged_runner(self):
|
||||
# pkexec is not installed on the server; sudo is. The test
|
||||
# asserts the shape, not a hardcoded runner, so it holds on
|
||||
# a machine with pkexec too.
|
||||
runner = install.privileged_runner()
|
||||
self.assertIn(runner, ("pkexec", "sudo", None))
|
||||
if runner is not None:
|
||||
self.assertTrue(runner in ("pkexec", "sudo"))
|
||||
|
||||
def test_install_command_construction(self):
|
||||
argv = install.install_command("/tmp/x.sh", runner="pkexec")
|
||||
self.assertEqual(argv, ["pkexec", "sh", "/tmp/x.sh"])
|
||||
argv = install.install_command("/tmp/x.sh", runner="sudo")
|
||||
self.assertEqual(argv, ["sudo", "-S", "sh", "/tmp/x.sh"])
|
||||
# With an explicit runner the command never contains a
|
||||
# password or a user name.
|
||||
self.assertNotIn("password", " ".join(argv))
|
||||
self.assertIsNone(install.install_command("/tmp/x.sh",
|
||||
runner="bogus"))
|
||||
|
||||
def test_install_command_uses_detected_runner(self):
|
||||
runner = install.privileged_runner()
|
||||
argv = install.install_command("/tmp/x.sh")
|
||||
if runner is None:
|
||||
self.assertIsNone(argv)
|
||||
else:
|
||||
self.assertEqual(argv[0], runner)
|
||||
self.assertEqual(argv[-1], "/tmp/x.sh")
|
||||
|
||||
def test_run_install_without_runner_fails_cleanly(self):
|
||||
ok, output = install.run_install(runner=None) \
|
||||
if install.privileged_runner() is None else (None, None)
|
||||
if install.privileged_runner() is None:
|
||||
self.assertFalse(ok)
|
||||
self.assertIn("pkexec", output)
|
||||
|
||||
def test_run_install_sudo_without_password_refuses(self):
|
||||
if install.privileged_runner() != "sudo":
|
||||
self.skipTest("sudo is not the detected runner here")
|
||||
ok, output = install.run_install(password=None,
|
||||
runner="sudo")
|
||||
self.assertFalse(ok)
|
||||
self.assertIn("password", output)
|
||||
|
||||
def test_write_install_script_roundtrip(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = os.path.join(folder, "inst.sh")
|
||||
written = install.write_install_script(
|
||||
path, root="/repo", site="/usr/lib/python3/x")
|
||||
self.assertEqual(written, path)
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
self.assertEqual(
|
||||
handle.read(),
|
||||
install.build_install_script(
|
||||
root="/repo", site="/usr/lib/python3/x"))
|
||||
|
||||
def test_is_installed_false_for_empty_site(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
self.assertFalse(install.is_installed(site=folder))
|
||||
|
||||
|
||||
try:
|
||||
import gi
|
||||
gi.require_version("Gtk", "3.0")
|
||||
from gi.repository import Gtk
|
||||
_GTK_OK = Gtk.init_check()[0]
|
||||
except Exception:
|
||||
Gtk = None
|
||||
_GTK_OK = False
|
||||
|
||||
if _GTK_OK:
|
||||
from lightgui.install_libs import InstallLibrariesDialog
|
||||
|
||||
|
||||
class InstallDialogTests(unittest.TestCase):
|
||||
def test_dialog_shows_dry_run_without_installing(self):
|
||||
if not _GTK_OK:
|
||||
self.skipTest("needs a display (run under Xvfb)")
|
||||
dialog = InstallLibrariesDialog(parent=None)
|
||||
try:
|
||||
text = dialog.buffer.get_text(
|
||||
*dialog.buffer.get_bounds(), True)
|
||||
self.assertIn("lightgui", text)
|
||||
self.assertIn("/usr/local/bin/lightgui", text)
|
||||
self.assertIn("cp -r", text)
|
||||
# Showing the dialog must not have installed anything.
|
||||
self.assertFalse(dialog._installing)
|
||||
finally:
|
||||
dialog.window.destroy()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user