60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288 | class QCViewer(App):
BINDINGS = [
("q", "quit", "Quit"),
("/", "focus_search", "Search"),
("n", "next_match", "Next Match"),
("p", "prev_match", "Prev Match"),
Binding("f2", "toggle_mouse", "Toggle Text Selection", priority=True),
]
def __init__(self, data):
super().__init__()
self.data = data
self.mouse_enabled = True
self.matches = []
self.match_index = -1
self.qc_tree = None # will be created in compose()
self.last_highlighted_node = None
def compose(self) -> ComposeResult:
yield Header()
self.qc_tree = Tree("QC Results", id="qc-tree")
yield self.qc_tree
yield Input(placeholder="Search...", id="search")
yield Static("", id="status")
yield Static(self.mouse_guidance, id="mouse-guidance")
yield Footer()
@property
def mouse_guidance(self):
"""Return instructions for the active mouse mode."""
if self.mouse_enabled:
return (
"Mouse mode | Left-click: toggle node | Right-click: expand/collapse "
"subtree | F2: enable text selection"
)
return (
"Text-selection mode | Drag: select text | Copy: Ctrl+Shift+C (not Ctrl+C), "
"Cmd+C on macOS, or right-click the selection | F2: disable text selection"
)
def on_tree_node_selected(self, event: Tree.NodeSelected):
# Right-click simulation: expand all children
# Unfortunately, Tree.NodeSelected does not carry button info
# We rely on a right-click flag set in on_mouse_down
if getattr(self, "_right_click_pending", False):
self.toggle_expand_node(event.node)
self._right_click_pending = False
def on_mouse_up(self, event: MouseUp):
# Set a flag if right-click
if event.button == 3: # right click
self._right_click_pending = True
# node = self.qc_tree.cursor_node
# if node:
# self.toggle_expand_node(node)
def toggle_expand_node(self, node):
"""Right-click: expand if collapsed, collapse if expanded, recursively."""
if hasattr(node, "_expanded_state"):
# toggle previous state
expanding = not node._expanded_state
else:
# first time, check actual state
expanding = not node.is_expanded
if not expanding:
# Collapse node and all children
self._collapse_tree(node)
else:
# Expand node and all children, potentially only up to certain level
depth = self.get_node_depth(node)
if depth <= 1:
self._expand_tree_up_to_depth(node, current_lvl=depth, target_lvl=2)
else:
self._expand_tree(node)
def get_node_depth(self, node):
"""Return depth of node (root=0)."""
depth = 0
parent = node.parent
while parent:
depth += 1
parent = parent.parent
return depth
def _expand_tree_up_to_depth(self, node, current_lvl, target_lvl):
"""Recursively expand node up to certain depth level."""
node.expand()
node._expanded_state = True
if current_lvl >= target_lvl:
return
for child in node.children:
self._expand_tree_up_to_depth(child, current_lvl + 1, target_lvl)
def _expand_tree(self, node):
"""Recursively expand node and all children."""
node.expand()
node._expanded_state = True
for child in node.children:
self._expand_tree(child)
def _collapse_tree(self, node):
"""Recursively collapses node and all children."""
for child in node.children:
self._collapse_tree(child)
node.collapse()
node._expanded_state = False
def on_mount(self):
self.populate_tree(self.qc_tree.root, self.data)
self.qc_tree.root.expand()
def populate_tree(self, node, data):
if isinstance(data, dict):
for k, v in data.items():
child = node.add(k, expand=False)
self.populate_tree(child, v)
elif isinstance(data, list):
for i, v in enumerate(data):
if isinstance(v, (dict, list)):
child = node.add(f"[{i}]", expand=False)
self.populate_tree(child, v)
else:
node.add(repr(v))
else:
node.add(repr(data))
def action_focus_search(self):
self.query_one("#search").focus()
def action_toggle_mouse(self):
"""Toggle between TUI mouse controls and terminal text selection."""
driver = self._driver
self.mouse_enabled = not self.mouse_enabled
if self.mouse_enabled:
# Textual has no public runtime API for toggling mouse reporting.
# Set the driver's startup flag first so its enable method takes effect.
driver._mouse = True
enable_mouse = getattr(driver, "_enable_mouse_support", None)
if enable_mouse is not None:
enable_mouse()
else:
disable_mouse = getattr(driver, "_disable_mouse_support", None)
if disable_mouse is not None:
disable_mouse()
# Keep Textual from re-enabling reporting after a terminal resume.
driver._mouse = False
self.query_one("#mouse-guidance", Static).update(self.mouse_guidance)
mode = "Mouse controls" if self.mouse_enabled else "Text selection"
self.query_one("#status", Static).update(f"{mode} enabled (F2 to toggle)")
def on_input_submitted(self, event: Input.Submitted):
"""Called when the user submits a search in the input."""
query = event.value.strip()
self.matches = []
self.match_index = -1
if query:
# Collect all matching nodes
for node in iter_nodes(self.qc_tree.root):
if query.lower() in str(node.label).lower():
self.matches.append(node)
if self.matches:
# Start at first match
self.match_index = 0
# Jump to it (expand path, collapse old if needed)
self.jump_to_match()
# Return focus to tree so n/p work
self.set_focus(self.qc_tree)
else:
self.query_one("#status", Static).update(f"No matches for '{query}'")
def focus_match(self):
node = self.matches[self.match_index]
node.expand_all()
self.qc_tree.select_node(node)
self.qc_tree.scroll_to_node(node)
self.query_one("#status", Static).update(
f"Match {self.match_index+1}/{len(self.matches)}: {node.label}"
)
def action_next_match(self):
if self.matches:
self.match_index = (self.match_index + 1) % len(self.matches)
self.jump_to_match()
def action_prev_match(self):
if self.matches:
self.match_index = (self.match_index - 1) % len(self.matches)
self.jump_to_match()
def jump_to_match(self) -> None:
"""Jump to the current match, expanding its parents and collapsing previous."""
if not self.matches or self.match_index < 0:
return
# Collapse the previously focused node if any
if hasattr(self, "current_match_node") and self.current_match_node is not None:
try:
self.current_match_node.collapse()
except Exception:
pass
# Get the current match node
node = self.matches[self.match_index]
self.current_match_node = node
# Expand all parents so the node is visible
parent = node.parent
while parent:
parent.expand()
parent = parent.parent
# Expand this node itself too
node.expand()
# Scroll to and select it
self.qc_tree.select_node(node)
self.qc_tree.scroll_to_node(node)
self.qc_tree.select_node(node)
# Status line
self.query_one("#status", Static).update(
f"Match {self.match_index+1}/{len(self.matches)}: {node.label}"
)
|