Skip to content

Commit 0259e5f

Browse files
committed
gui: Wait for a wallet choice and list new wallets as the CLI does
A list with one row drew a lone checkbox. Unticking it left nothing chosen, and Continue then raised StopIteration in _selected. Group every row under a hidden leader so even one row is a radio that cannot be unticked, start with nothing chosen, and keep Continue disabled until a choice is made. The wallet page asked Bitcoin Core again only on "Check again". Poll once a second instead, as the CLI waits for a new wallet, keeping the chosen wallet by name across a refresh. work.run now queues jobs behind one lock, so an import waits for a poll rather than failing as busy. Claude-Session: https://claude.ai/code/session_01N8jLK621Vh9wiv9ZntctSG
1 parent ae9d360 commit 0259e5f

5 files changed

Lines changed: 120 additions & 61 deletions

File tree

‎docs/developer/gui.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ about 250 lines, and the rest of the difference is user-facing wording in
6060
page a rewrite has just added keeps what it holds, and a page a rewrite drops
6161
is cleared.
6262
6. **One worker, and no callback touches a page that is gone.** `work.run`
63-
refuses to start a second operation, delivers its result through
63+
queues a second operation behind one gate, so an import waits for the
64+
once-a-second wallet-list poll instead of overlapping it, delivers its result through
6465
`GLib.idle_add`, and drops it unless `work.showing` finds the page still on
6566
the stack — being rooted in the window is not the test, because a page keeps
6667
its root for the length of the navigation animation. It delivers from
@@ -164,7 +165,6 @@ library's.
164165

165166
- A 74- or 127-character card scrolls sideways in the entry field, because it is
166167
one `Gtk.Entry`. A 48-character card fits.
167-
- The list of empty Bitcoin Core wallets refreshes when asked, not on its own.
168168
- Widget construction is not covered by pytest, because it needs a display.
169169
`tools/gui_walkthrough.py` covers it instead, under `xvfb-run`.
170170
- Selecting text inside the entry field hands it to the primary selection for

‎src/codex32_gui/pages.py‎

Lines changed: 57 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,10 @@
4545
(3, 5, "Five cards, any three recover"),
4646
(0, 1, "One card"),
4747
)
48-
CREATE_WALLET = "Create a new wallet"
48+
CREATE_ROW = (
49+
"Create a new wallet",
50+
"codex32 asks Bitcoin Core for a blank wallet, with a passphrase you choose",
51+
)
4952
HANDWRITING = (
5053
"Mark the look-alikes as you write: slash every 0, cross 7 and Z, write S like $, close the loops of 6 "
5154
"and 9, and give G an open, obvious bar. Then 5 and S, 6 and G, and 2 and Z stay apart."
@@ -338,17 +341,17 @@ def _guessed(observed: str, corrected: str) -> frozenset[int]:
338341
return frozenset(changed)
339342

340343

341-
def _radio_group(group: Adw.PreferencesGroup, rows: Sequence[tuple[str, str]]) -> list[Gtk.CheckButton]:
342-
"""Build one radio row per choice. Rows carry Bitcoin Core's text, so none of it is markup."""
343-
first: Gtk.CheckButton | None = None
344+
def _radio_group(
345+
group: Adw.PreferencesGroup, rows: Sequence[tuple[str, str]], action: Gtk.Button
346+
) -> list[Gtk.CheckButton]:
347+
"""Build one radio row per choice, none chosen; `action` waits for one. Core's text is never markup."""
348+
# A hidden leader groups even one row, so it is a radio that cannot be unticked. Handlers keep it alive.
349+
leader = Gtk.CheckButton()
350+
action.set_sensitive(False)
344351
buttons: list[Gtk.CheckButton] = []
345352
for label, detail in rows:
346-
choice = Gtk.CheckButton()
347-
if first is None:
348-
first = choice
349-
choice.set_active(True)
350-
else:
351-
choice.set_group(first)
353+
choice = Gtk.CheckButton(group=leader)
354+
choice.connect("toggled", lambda _choice, _leader=leader: action.set_sensitive(True))
352355
row = Adw.ActionRow(title=label, subtitle=detail, activatable_widget=choice, use_markup=False)
353356
row.add_prefix(choice)
354357
group.add(row)
@@ -422,16 +425,16 @@ def _network_page(
422425
then: Callable[[BitcoinCore], Adw.NavigationPage],
423426
) -> Adw.NavigationPage:
424427
group = Adw.PreferencesGroup(title="Bitcoin Core is running on more than one network")
425-
buttons = _radio_group(group, [(label, "") for label in options])
426-
content = _column(
427-
_title("Which network?", "Practise on signet. Use mainnet only for coins you cannot replace."),
428-
group,
429-
)
430428
action = _button(
431429
"Continue",
432430
lambda: _connect(view, options[_selected(buttons)], then),
433431
style="suggested-action",
434432
)
433+
buttons = _radio_group(group, [(label, "") for label in options], action)
434+
content = _column(
435+
_title("Which network?", "Practise on signet. Use mainnet only for coins you cannot replace."),
436+
group,
437+
)
435438
return _page("Network", content, actions=_actions(action))
436439

437440

@@ -578,7 +581,8 @@ def _layout_page(view: Adw.NavigationView, core: BitcoinCore) -> Adw.NavigationP
578581
"Something else": "Choose the numbers yourself, and the size of the seed.",
579582
}
580583
group = Adw.PreferencesGroup()
581-
buttons = _radio_group(group, [(label, details[label]) for label in details])
584+
action = _button("Continue", lambda: begin(), style="suggested-action")
585+
buttons = _radio_group(group, [(label, details[label]) for label in details], action)
582586
custom = Adw.PreferencesGroup(title="Your own combination", visible=False)
583587
needed = Adw.SpinRow(
584588
title="Cards needed to recover",
@@ -626,9 +630,7 @@ def begin() -> None:
626630
group,
627631
custom,
628632
)
629-
return _page(
630-
"New wallet", content, actions=_actions(_button("Continue", begin, style="suggested-action"))
631-
)
633+
return _page("New wallet", content, actions=_actions(action))
632634

633635

634636
def _ready_page(
@@ -798,10 +800,36 @@ def _wallet_page(
798800
restoring: bool,
799801
) -> Adw.NavigationPage:
800802
"""Name the wallet that will hold the keys. The library confirms that name again."""
801-
group = Adw.PreferencesGroup(title="Empty wallets Bitcoin Core has ready")
802-
rows = [(item.name, "Empty, encrypted" if item.encrypted else "Empty, not encrypted") for item in found]
803-
rows.append((CREATE_WALLET, "codex32 asks Bitcoin Core for a blank wallet, with a passphrase you choose"))
804-
buttons = _radio_group(group, rows)
803+
# Like the CLI, ask Bitcoin Core again every second, so a wallet made there appears here.
804+
holder = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
805+
action = _button("Continue", lambda: go(), style="suggested-action")
806+
buttons: list[Gtk.CheckButton] = []
807+
808+
def show(listed: tuple[wallet_setup.Wallet, ...]) -> None:
809+
nonlocal found, buttons
810+
# A refresh keeps the operator's choice by name; None stands for the create row.
811+
kept = next((n for n, b in zip([w.name for w in found] + [None], buttons) if b.get_active()), False)
812+
found = listed
813+
group = Adw.PreferencesGroup(title="Empty wallets Bitcoin Core has ready")
814+
rows = [(w.name, "Empty, encrypted" if w.encrypted else "Empty, not encrypted") for w in found]
815+
buttons = _radio_group(group, [*rows, CREATE_ROW], action)
816+
for choice, name in zip(buttons, [item.name for item in found] + [None], strict=True):
817+
choice.set_active(name == kept)
818+
if (old := holder.get_first_child()) is not None:
819+
holder.remove(old)
820+
holder.append(group)
821+
822+
def refreshed(listed: tuple[wallet_setup.Wallet, ...] | Exception) -> None:
823+
# A failed poll keeps the list shown; Continue reports Bitcoin Core's error if it persists.
824+
if isinstance(listed, tuple) and listed != found:
825+
show(listed)
826+
827+
def poll() -> bool:
828+
if view.get_visible_page() is page and not work.busy():
829+
work.run(view, page, lambda: wallet_setup.eligible(core), refreshed)
830+
return work.showing(view, page)
831+
832+
show(found)
805833

806834
def go() -> None:
807835
# By position, so that a wallet named like the create row is still reachable.
@@ -820,10 +848,10 @@ def go() -> None:
820848
"Which wallet should hold your keys?",
821849
f"Bitcoin Core {wallet_setup.version_text(core)} is running on {wallet_setup.network(core)}.",
822850
),
823-
group,
851+
holder,
824852
_note(
825-
"Only empty wallets are listed, so no wallet you already use can be overwritten. You may also "
826-
"create one in Bitcoin Core yourself and check again."
853+
"Only empty wallets are listed, so no wallet you already use can be overwritten. A wallet you "
854+
"create in Bitcoin Core yourself appears here."
827855
),
828856
*(
829857
(
@@ -837,16 +865,9 @@ def go() -> None:
837865
else ()
838866
),
839867
)
840-
return _page(
841-
"Wallet",
842-
content,
843-
actions=_actions(
844-
_button(
845-
"Check again", lambda: _wallets(view, core, secret, timestamp, expected, restoring=restoring)
846-
),
847-
_button("Continue", go, style="suggested-action"),
848-
),
849-
)
868+
page = _page("Wallet", content, actions=_actions(action))
869+
GLib.timeout_add_seconds(1, poll)
870+
return page
850871

851872

852873
def _new_wallet_page(

‎src/codex32_gui/work.py‎

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,7 @@
1414
"That operation stopped in a way this program did not expect. If it was writing to Bitcoin "
1515
"Core, check there what state the wallet is in before trying again."
1616
)
17-
_BUSY = "Another operation is still finishing. Try again in a moment."
18-
_running = False
17+
_gate = threading.Lock()
1918

2019

2120
def showing(view: Adw.NavigationView, page: Adw.NavigationPage) -> bool:
@@ -29,6 +28,11 @@ def showing(view: Adw.NavigationView, page: Adw.NavigationPage) -> bool:
2928
return any(stack.get_item(position) is page for position in range(stack.get_n_items()))
3029

3130

31+
def busy() -> bool:
32+
"""Report whether an operation holds the gate, so a background poll can skip a turn."""
33+
return _gate.locked()
34+
35+
3236
def run[Result](
3337
view: Adw.NavigationView,
3438
page: Adw.NavigationPage,
@@ -38,8 +42,8 @@ def run[Result](
3842
"""Run one blocking library call off the main loop and deliver its result back.
3943
4044
`correct` runs for up to ten seconds and every Bitcoin Core call waits on a
41-
subprocess, so neither may run on the main loop. The page that starts an
42-
operation shows a spinner and cannot be left, so only one is ever in flight,
45+
subprocess, so neither may run on the main loop. Operations take one gate in
46+
turn, so an import queues behind a wallet-list poll instead of overlapping it,
4347
and a result for a page that is gone anyway is dropped. The result is
4448
delivered from `finally`, so a failure no screen anticipated still releases
4549
the program instead of leaving it spinning.
@@ -49,36 +53,20 @@ def run[Result](
4953
blocks in daemon threads while the interpreter is shutting down, so closing
5054
the window during an import would otherwise leave that wallet open.
5155
"""
52-
global _running
53-
if _running:
54-
GLib.idle_add(_busy, view, page, done)
55-
return
56-
_running = True
5756

5857
def worker() -> None:
5958
outcome: Result | Exception = RuntimeError(_UNFINISHED)
6059
try:
61-
outcome = work()
60+
with _gate:
61+
outcome = work()
6262
except (CodexError, BitcoinCoreError, OSError, TypeError, ValueError) as error:
6363
outcome = error
6464
finally:
6565
GLib.idle_add(deliver, outcome)
6666

6767
def deliver(outcome: Result | Exception) -> bool:
68-
global _running
69-
_running = False
7068
if showing(view, page):
7169
done(outcome)
7270
return False
7371

7472
threading.Thread(target=worker).start()
75-
76-
77-
def _busy[Result](
78-
view: Adw.NavigationView,
79-
page: Adw.NavigationPage,
80-
done: Callable[[Result | Exception], None],
81-
) -> bool:
82-
if showing(view, page):
83-
done(RuntimeError(_BUSY))
84-
return False

‎tests/test_gui_before_you_start.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ def test_a_layout_choice_leads_to_the_checklist_not_to_a_card(monkeypatch: pytes
4545
view = Adw.NavigationView()
4646
core: Any = object()
4747
view.push(pages._layout_page(view, core))
48+
_widgets(view.get_visible_page(), Gtk.CheckButton).__next__().set_active(True)
4849

4950
_button(view.get_visible_page(), "Continue").emit("clicked")
5051
ready = view.get_visible_page()
@@ -115,3 +116,52 @@ def launch(self, _parent: object, _cancellable: object, _callback: object) -> No
115116

116117
_button(page, "Open the recovery card form").emit("clicked")
117118
assert opened == ["/home/amnesia/Tor Browser/codex32 forms/recovery-card.html"]
119+
120+
121+
def _wallet(name: str) -> Any:
122+
return pages.wallet_setup.Wallet(name=name, encrypted=True, locked=False)
123+
124+
125+
@pytest.fixture(autouse=True)
126+
def _core_text(monkeypatch: pytest.MonkeyPatch) -> None:
127+
monkeypatch.setattr(pages.wallet_setup, "version_text", lambda _core: "32.1.0")
128+
monkeypatch.setattr(pages.wallet_setup, "network", lambda _core: "signet")
129+
130+
131+
def test_continue_waits_for_a_choice_and_a_lone_row_stays_a_radio() -> None:
132+
view = Adw.NavigationView()
133+
page = pages._layout_page(view, object()) # type: ignore[arg-type]
134+
choices = list(_widgets(page, Gtk.CheckButton))
135+
assert not any(choice.get_active() for choice in choices)
136+
assert not _button(page, "Continue").get_sensitive()
137+
138+
page = pages._wallet_page(view, object(), object(), (), "now", None, False) # type: ignore[arg-type]
139+
(choice,) = _widgets(page, Gtk.CheckButton)
140+
assert not _button(page, "Continue").get_sensitive()
141+
choice.activate()
142+
choice.activate()
143+
assert choice.get_active() and _button(page, "Continue").get_sensitive()
144+
assert all(button.get_label() != "Check again" for button in _widgets(page, Gtk.Button))
145+
146+
147+
def test_the_wallet_list_refreshes_like_the_cli_and_keeps_the_choice(monkeypatch: pytest.MonkeyPatch) -> None:
148+
polls: list[Any] = []
149+
listed = [(_wallet("b"),), (_wallet("a"), _wallet("b"))]
150+
monkeypatch.setattr(pages.GLib, "timeout_add_seconds", lambda _seconds, poll: polls.append(poll))
151+
monkeypatch.setattr(pages.wallet_setup, "eligible", lambda _core: listed.pop(0))
152+
monkeypatch.setattr(pages.work, "run", lambda _view, _page, job, done: done(job()))
153+
view = Adw.NavigationView()
154+
view.push(pages.home(view))
155+
view.push(pages._wallet_page(view, object(), object(), (), "now", None, False)) # type: ignore[arg-type]
156+
157+
assert polls[0]() is True
158+
page = view.get_visible_page()
159+
assert "b" in _texts(page)
160+
next(_widgets(page, Gtk.CheckButton)).set_active(True)
161+
assert polls[0]() is True
162+
choices = list(_widgets(page, Gtk.CheckButton))
163+
assert "a" in _texts(page) and [choice.get_active() for choice in choices] == [False, True, False]
164+
assert _button(page, "Continue").get_sensitive()
165+
166+
view.pop()
167+
assert polls[0]() is False

‎tests/test_gui_boundaries.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ def test_the_gui_keeps_its_own_size_budget() -> None:
132132
def test_every_restore_way_to_a_wallet_passes_the_identity_choice() -> None:
133133
tree = ast.parse((_package() / "pages.py").read_text())
134134

135-
assert _callers(tree, "_wallets") == {"_fingerprint_page", "_identity", "_wallet_page"}
135+
assert _callers(tree, "_wallets") == {"_fingerprint_page", "_identity"}
136136
assert _callers(tree, "_fingerprint_page") == {"_identity", "_restore", "_fingerprint_page"}
137137
assert _callers(tree, "_identity") == {"_unshared_page", "_card_confirmed", "_fingerprint_page"}
138138

0 commit comments

Comments
 (0)