tmcode 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- termcode/__init__.py +3 -0
- termcode/app.py +2236 -0
- termcode/buffers.py +168 -0
- termcode/cli.py +69 -0
- termcode/commands.py +234 -0
- termcode/completions.py +205 -0
- termcode/findbar.py +258 -0
- termcode/formatting.py +365 -0
- termcode/highlighting.py +61 -0
- termcode/modals.py +431 -0
- termcode/runner.py +725 -0
- termcode/search.py +105 -0
- termcode/styles.tcss +796 -0
- termcode/theme.py +99 -0
- termcode/workspace.py +271 -0
- tmcode-0.2.0.dist-info/METADATA +128 -0
- tmcode-0.2.0.dist-info/RECORD +21 -0
- tmcode-0.2.0.dist-info/WHEEL +5 -0
- tmcode-0.2.0.dist-info/entry_points.txt +3 -0
- tmcode-0.2.0.dist-info/licenses/LICENSE +21 -0
- tmcode-0.2.0.dist-info/top_level.txt +1 -0
termcode/app.py
ADDED
|
@@ -0,0 +1,2236 @@
|
|
|
1
|
+
"""Main Textual TUI application for TermCode."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Iterable
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
from rich.text import Text
|
|
14
|
+
from textual import events, work
|
|
15
|
+
from textual.app import App, ComposeResult, SuspendNotSupported
|
|
16
|
+
from textual.binding import Binding
|
|
17
|
+
from textual.containers import Horizontal, Vertical
|
|
18
|
+
from textual.css.query import NoMatches
|
|
19
|
+
from textual.widgets import Button, DirectoryTree, Input, OptionList, Static, TextArea
|
|
20
|
+
from textual.widgets.option_list import Option
|
|
21
|
+
|
|
22
|
+
from termcode.buffers import EditorPaneState, OpenBuffer
|
|
23
|
+
from termcode.completions import (
|
|
24
|
+
compute_closing_brace_dedent,
|
|
25
|
+
compute_enter_indent,
|
|
26
|
+
extract_prefix,
|
|
27
|
+
get_completions,
|
|
28
|
+
)
|
|
29
|
+
from termcode import __version__, theme
|
|
30
|
+
from termcode.findbar import FindBar
|
|
31
|
+
from termcode.formatting import format_code
|
|
32
|
+
from termcode.highlighting import register_extra_languages
|
|
33
|
+
from termcode.modals import (
|
|
34
|
+
CommandPaletteModal,
|
|
35
|
+
ConfirmModal,
|
|
36
|
+
FilePickerModal,
|
|
37
|
+
FolderPickerModal,
|
|
38
|
+
TextInputModal,
|
|
39
|
+
UnsavedChangesModal,
|
|
40
|
+
)
|
|
41
|
+
from termcode.search import parse_goto
|
|
42
|
+
from termcode.runner import (
|
|
43
|
+
AsyncRunner,
|
|
44
|
+
RunResult,
|
|
45
|
+
RunnerError,
|
|
46
|
+
build_run_plan,
|
|
47
|
+
editor_language_for_path,
|
|
48
|
+
language_label_for_path,
|
|
49
|
+
run_in_foreground,
|
|
50
|
+
user_shell_command,
|
|
51
|
+
wait_ignoring_ctrl_c,
|
|
52
|
+
)
|
|
53
|
+
from termcode.workspace import (
|
|
54
|
+
IGNORED_DIRS,
|
|
55
|
+
WorkspaceError,
|
|
56
|
+
create_file,
|
|
57
|
+
create_folder,
|
|
58
|
+
delete_path,
|
|
59
|
+
current_git_branch,
|
|
60
|
+
list_workspace_files,
|
|
61
|
+
load_recent_folders,
|
|
62
|
+
read_text_file,
|
|
63
|
+
record_recent_folder,
|
|
64
|
+
rename_path,
|
|
65
|
+
write_text_file,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
MAX_OUTPUT_HISTORY_CHARS = 500_000
|
|
69
|
+
MIN_TERMINAL_HEIGHT = 4
|
|
70
|
+
DEFAULT_TERMINAL_HEIGHT = 10
|
|
71
|
+
OUTPUT_FLUSH_INTERVAL = 1 / 30
|
|
72
|
+
DEFAULT_SIDEBAR_WIDTH = 30
|
|
73
|
+
MIN_SIDEBAR_WIDTH = 16
|
|
74
|
+
MAX_SIDEBAR_WIDTH = 60
|
|
75
|
+
# Dragging a panel smaller than this collapses it (VS Code behaviour).
|
|
76
|
+
COLLAPSE_SIDEBAR_BELOW = 10
|
|
77
|
+
COLLAPSE_TERMINAL_BELOW = 3
|
|
78
|
+
|
|
79
|
+
_GTK_CLIPBOARD_SCRIPT = (
|
|
80
|
+
"import sys, gi\n"
|
|
81
|
+
"gi.require_version('Gtk', '3.0')\n"
|
|
82
|
+
"from gi.repository import Gtk, Gdk\n"
|
|
83
|
+
"text = sys.stdin.read()\n"
|
|
84
|
+
"cb = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)\n"
|
|
85
|
+
"cb.set_text(text, -1)\n"
|
|
86
|
+
"cb.store()\n"
|
|
87
|
+
"while Gtk.events_pending():\n"
|
|
88
|
+
" Gtk.main_iteration()\n"
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _copy_to_os_clipboard(text: str) -> bool:
|
|
93
|
+
"""Copy text to the native OS clipboard across Linux, macOS, and Windows."""
|
|
94
|
+
if os.environ.get("PYTEST_CURRENT_TEST"):
|
|
95
|
+
return False
|
|
96
|
+
|
|
97
|
+
candidates: list[list[str]]
|
|
98
|
+
if sys.platform == "darwin":
|
|
99
|
+
candidates = [["pbcopy"]]
|
|
100
|
+
elif sys.platform == "win32":
|
|
101
|
+
candidates = [["clip"]]
|
|
102
|
+
else:
|
|
103
|
+
candidates = [
|
|
104
|
+
["wl-copy"],
|
|
105
|
+
["xclip", "-selection", "clipboard"],
|
|
106
|
+
["xsel", "--clipboard", "--input"],
|
|
107
|
+
]
|
|
108
|
+
|
|
109
|
+
for cmd in candidates:
|
|
110
|
+
if shutil.which(cmd[0]) is None:
|
|
111
|
+
continue
|
|
112
|
+
try:
|
|
113
|
+
subprocess.run(
|
|
114
|
+
cmd,
|
|
115
|
+
input=text.encode("utf-8"),
|
|
116
|
+
stdout=subprocess.DEVNULL,
|
|
117
|
+
stderr=subprocess.DEVNULL,
|
|
118
|
+
check=True,
|
|
119
|
+
timeout=2,
|
|
120
|
+
)
|
|
121
|
+
return True
|
|
122
|
+
except (OSError, subprocess.SubprocessError):
|
|
123
|
+
continue
|
|
124
|
+
|
|
125
|
+
# Linux X11 fallback using system GTK3 (PyGObject) when xclip/xsel are absent.
|
|
126
|
+
if sys.platform != "win32" and sys.platform != "darwin" and os.environ.get("DISPLAY"):
|
|
127
|
+
sys_py = shutil.which("python3")
|
|
128
|
+
if sys_py:
|
|
129
|
+
try:
|
|
130
|
+
subprocess.run(
|
|
131
|
+
[sys_py, "-c", _GTK_CLIPBOARD_SCRIPT],
|
|
132
|
+
input=text.encode("utf-8"),
|
|
133
|
+
stdout=subprocess.DEVNULL,
|
|
134
|
+
stderr=subprocess.DEVNULL,
|
|
135
|
+
check=True,
|
|
136
|
+
timeout=2,
|
|
137
|
+
)
|
|
138
|
+
return True
|
|
139
|
+
except (OSError, subprocess.SubprocessError):
|
|
140
|
+
pass
|
|
141
|
+
|
|
142
|
+
return False
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _is_within(child: Path, parent: Path) -> bool:
|
|
146
|
+
try:
|
|
147
|
+
child.resolve().relative_to(parent.resolve())
|
|
148
|
+
return True
|
|
149
|
+
except ValueError:
|
|
150
|
+
return False
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class ResizeHover:
|
|
154
|
+
"""Mixin for drag handles: highlighted look (thick line + grip) while hovered or dragged.
|
|
155
|
+
|
|
156
|
+
The resize mouse pointer itself comes from the `pointer:` rule in styles.tcss.
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
_dragging: bool
|
|
160
|
+
|
|
161
|
+
def on_enter(self, event: events.Enter) -> None:
|
|
162
|
+
self.add_class("-hover") # type: ignore[attr-defined]
|
|
163
|
+
self.refresh() # type: ignore[attr-defined]
|
|
164
|
+
|
|
165
|
+
def on_leave(self, event: events.Leave) -> None:
|
|
166
|
+
if not self._dragging:
|
|
167
|
+
self._end_hover()
|
|
168
|
+
|
|
169
|
+
def _end_hover(self) -> None:
|
|
170
|
+
self.remove_class("-hover") # type: ignore[attr-defined]
|
|
171
|
+
self.refresh() # type: ignore[attr-defined]
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class TerminalResizeHandle(ResizeHover, Static):
|
|
175
|
+
"""Draggable Terminal header bar — drag vertically with mouse to resize Terminal."""
|
|
176
|
+
|
|
177
|
+
def __init__(self, content: str, *, id: str | None = None, markup: bool = False) -> None:
|
|
178
|
+
super().__init__(content, id=id, markup=markup)
|
|
179
|
+
self._dragging = False
|
|
180
|
+
self._start_y = 0
|
|
181
|
+
self._start_height = DEFAULT_TERMINAL_HEIGHT
|
|
182
|
+
|
|
183
|
+
def on_mouse_down(self, event: events.MouseDown) -> None:
|
|
184
|
+
if event.button != 1:
|
|
185
|
+
return
|
|
186
|
+
app = self.app
|
|
187
|
+
if isinstance(app, TermCodeApp):
|
|
188
|
+
self.add_class("-dragging")
|
|
189
|
+
self._dragging = True
|
|
190
|
+
self._start_y = event.screen_y
|
|
191
|
+
self._start_height = app.terminal_height
|
|
192
|
+
self.capture_mouse()
|
|
193
|
+
event.stop()
|
|
194
|
+
|
|
195
|
+
def on_mouse_move(self, event: events.MouseMove) -> None:
|
|
196
|
+
if not self._dragging:
|
|
197
|
+
return
|
|
198
|
+
app = self.app
|
|
199
|
+
if isinstance(app, TermCodeApp):
|
|
200
|
+
wanted = self._start_height + (self._start_y - event.screen_y)
|
|
201
|
+
if wanted < COLLAPSE_TERMINAL_BELOW:
|
|
202
|
+
self._dragging = False
|
|
203
|
+
self.remove_class("-dragging")
|
|
204
|
+
self.release_mouse()
|
|
205
|
+
app.set_output_visible(False)
|
|
206
|
+
else:
|
|
207
|
+
app.set_terminal_height(wanted)
|
|
208
|
+
event.stop()
|
|
209
|
+
|
|
210
|
+
def on_mouse_up(self, event: events.MouseUp) -> None:
|
|
211
|
+
if self._dragging:
|
|
212
|
+
self._dragging = False
|
|
213
|
+
self.remove_class("-dragging")
|
|
214
|
+
self.release_mouse()
|
|
215
|
+
if not self.is_mouse_over:
|
|
216
|
+
self._end_hover()
|
|
217
|
+
event.stop()
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class OutputEdge(TerminalResizeHandle):
|
|
221
|
+
"""The line along the top of the Output panel: the obvious thing to grab."""
|
|
222
|
+
|
|
223
|
+
def __init__(self, *, id: str | None = None) -> None:
|
|
224
|
+
super().__init__("", id=id)
|
|
225
|
+
|
|
226
|
+
def render(self) -> Text:
|
|
227
|
+
width = max(self.size.width, 1)
|
|
228
|
+
if self.has_class("-hover") or self.has_class("-dragging"):
|
|
229
|
+
# Thick line with a grip in the middle: reads as "drag me up/down".
|
|
230
|
+
grip = " ⇕ "
|
|
231
|
+
left = (width - len(grip)) // 2
|
|
232
|
+
return Text("━" * left + grip + "━" * (width - left - len(grip)))
|
|
233
|
+
return Text("─" * width)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class SidebarResizeHandle(ResizeHover, Static):
|
|
237
|
+
"""The sidebar's right edge: drag horizontally to resize, drag shut to hide."""
|
|
238
|
+
|
|
239
|
+
def __init__(self, *, id: str | None = None) -> None:
|
|
240
|
+
super().__init__("", id=id)
|
|
241
|
+
self._dragging = False
|
|
242
|
+
self._start_x = 0
|
|
243
|
+
self._start_width = DEFAULT_SIDEBAR_WIDTH
|
|
244
|
+
|
|
245
|
+
def render(self) -> Text:
|
|
246
|
+
height = max(self.size.height, 1)
|
|
247
|
+
if self.has_class("-hover") or self.has_class("-dragging"):
|
|
248
|
+
rows = ["┃"] * height
|
|
249
|
+
rows[height // 2] = "⇔"
|
|
250
|
+
return Text("\n".join(rows))
|
|
251
|
+
return Text("\n".join("│" for _ in range(height)))
|
|
252
|
+
|
|
253
|
+
def on_mouse_down(self, event: events.MouseDown) -> None:
|
|
254
|
+
app = self.app
|
|
255
|
+
if event.button != 1 or not isinstance(app, TermCodeApp):
|
|
256
|
+
return
|
|
257
|
+
self._dragging = True
|
|
258
|
+
self._start_x = event.screen_x
|
|
259
|
+
self._start_width = app.sidebar_width
|
|
260
|
+
self.add_class("-dragging")
|
|
261
|
+
self.capture_mouse()
|
|
262
|
+
event.stop()
|
|
263
|
+
|
|
264
|
+
def on_mouse_move(self, event: events.MouseMove) -> None:
|
|
265
|
+
app = self.app
|
|
266
|
+
if not self._dragging or not isinstance(app, TermCodeApp):
|
|
267
|
+
return
|
|
268
|
+
wanted = self._start_width + (event.screen_x - self._start_x)
|
|
269
|
+
if wanted < COLLAPSE_SIDEBAR_BELOW:
|
|
270
|
+
self._stop()
|
|
271
|
+
app.set_sidebar_visible(False)
|
|
272
|
+
else:
|
|
273
|
+
app.set_sidebar_width(wanted)
|
|
274
|
+
event.stop()
|
|
275
|
+
|
|
276
|
+
def on_mouse_up(self, event: events.MouseUp) -> None:
|
|
277
|
+
if self._dragging:
|
|
278
|
+
self._stop()
|
|
279
|
+
event.stop()
|
|
280
|
+
|
|
281
|
+
def _stop(self) -> None:
|
|
282
|
+
self._dragging = False
|
|
283
|
+
self.remove_class("-dragging")
|
|
284
|
+
self.release_mouse()
|
|
285
|
+
if not self.is_mouse_over:
|
|
286
|
+
self._end_hover()
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
class CodeTextArea(TextArea):
|
|
290
|
+
"""VS Code-style TextArea: Ctrl+A select-all, Ctrl+C selection/line copy, C/C++ colors, auto-indent, autocomplete."""
|
|
291
|
+
|
|
292
|
+
BINDINGS = [
|
|
293
|
+
Binding("ctrl+a", "select_all", "Select All", show=False),
|
|
294
|
+
]
|
|
295
|
+
|
|
296
|
+
def __init__(self, *args: object, **kwargs: object) -> None:
|
|
297
|
+
super().__init__(*args, **kwargs) # type: ignore[arg-type]
|
|
298
|
+
register_extra_languages(self)
|
|
299
|
+
self.register_theme(theme.EDITOR_THEME)
|
|
300
|
+
self.register_theme(theme.OUTPUT_THEME)
|
|
301
|
+
self.theme = theme.OUTPUT_THEME_NAME if self.read_only else theme.EDITOR_THEME_NAME
|
|
302
|
+
|
|
303
|
+
def action_copy(self) -> None:
|
|
304
|
+
"""Copy selected text, or the current line when nothing is selected (VS Code behavior)."""
|
|
305
|
+
selected = self.selected_text
|
|
306
|
+
if selected:
|
|
307
|
+
self.app.copy_to_clipboard(selected)
|
|
308
|
+
self.app.notify(f"Copied selection ({len(selected)} chars)")
|
|
309
|
+
return
|
|
310
|
+
row = self.cursor_location[0]
|
|
311
|
+
line = self.document.get_line(row)
|
|
312
|
+
self.app.copy_to_clipboard(line)
|
|
313
|
+
self.app.notify("Copied current line")
|
|
314
|
+
|
|
315
|
+
async def _on_key(self, event: events.Key) -> None:
|
|
316
|
+
if self.read_only:
|
|
317
|
+
await super()._on_key(event)
|
|
318
|
+
return
|
|
319
|
+
|
|
320
|
+
app = self.app
|
|
321
|
+
if isinstance(app, TermCodeApp) and app.is_completion_open_for(self):
|
|
322
|
+
if event.key == "down":
|
|
323
|
+
app.move_completion(1)
|
|
324
|
+
event.prevent_default()
|
|
325
|
+
event.stop()
|
|
326
|
+
return
|
|
327
|
+
if event.key == "up":
|
|
328
|
+
app.move_completion(-1)
|
|
329
|
+
event.prevent_default()
|
|
330
|
+
event.stop()
|
|
331
|
+
return
|
|
332
|
+
if event.key in ("tab", "enter"):
|
|
333
|
+
app.accept_completion(self)
|
|
334
|
+
event.prevent_default()
|
|
335
|
+
event.stop()
|
|
336
|
+
return
|
|
337
|
+
if event.key == "escape":
|
|
338
|
+
app.hide_completions()
|
|
339
|
+
event.prevent_default()
|
|
340
|
+
event.stop()
|
|
341
|
+
return
|
|
342
|
+
|
|
343
|
+
if event.key == "escape" and isinstance(app, TermCodeApp):
|
|
344
|
+
find_bar = app.query_one("#find-bar", FindBar)
|
|
345
|
+
if find_bar.is_open:
|
|
346
|
+
find_bar.action_close()
|
|
347
|
+
event.prevent_default()
|
|
348
|
+
event.stop()
|
|
349
|
+
return
|
|
350
|
+
|
|
351
|
+
if event.key == "enter":
|
|
352
|
+
row, col = self.cursor_location
|
|
353
|
+
line_before = self.document.get_line(row)[:col]
|
|
354
|
+
indent = compute_enter_indent(line_before, self.language)
|
|
355
|
+
self.insert("\n" + indent)
|
|
356
|
+
event.prevent_default()
|
|
357
|
+
event.stop()
|
|
358
|
+
return
|
|
359
|
+
|
|
360
|
+
if event.character == "}":
|
|
361
|
+
row, col = self.cursor_location
|
|
362
|
+
line_before = self.document.get_line(row)[:col]
|
|
363
|
+
dedent = compute_closing_brace_dedent(line_before)
|
|
364
|
+
if dedent > 0:
|
|
365
|
+
self.replace("}", (row, col - dedent), (row, col))
|
|
366
|
+
event.prevent_default()
|
|
367
|
+
event.stop()
|
|
368
|
+
return
|
|
369
|
+
|
|
370
|
+
await super()._on_key(event)
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
class FilteredDirectoryTree(DirectoryTree):
|
|
374
|
+
"""DirectoryTree that hides dotfiles and noisy build/cache folders by default,
|
|
375
|
+
and draws the file that is open in the editor in the accent color."""
|
|
376
|
+
|
|
377
|
+
ICON_NODE = "▸ "
|
|
378
|
+
ICON_NODE_EXPANDED = "▾ "
|
|
379
|
+
ICON_FILE = " "
|
|
380
|
+
# Class-level default: labels can render during __init__, before it's set.
|
|
381
|
+
active_path: Path | None = None
|
|
382
|
+
|
|
383
|
+
def __init__(self, path: str | Path, *, show_hidden: bool = False, id: str | None = None) -> None:
|
|
384
|
+
super().__init__(path, id=id)
|
|
385
|
+
self.show_hidden = show_hidden
|
|
386
|
+
# The folder name already heads the sidebar; don't repeat it as a tree node.
|
|
387
|
+
self.show_root = False
|
|
388
|
+
self.active_path: Path | None = None
|
|
389
|
+
|
|
390
|
+
def render_label(self, node, base_style, style): # type: ignore[no-untyped-def]
|
|
391
|
+
label = super().render_label(node, base_style, style)
|
|
392
|
+
path = getattr(node.data, "path", None)
|
|
393
|
+
if self.active_path is not None and path == self.active_path:
|
|
394
|
+
label.stylize(f"bold {theme.ACCENT}")
|
|
395
|
+
return label
|
|
396
|
+
|
|
397
|
+
def show_active(self, path: Path | None) -> None:
|
|
398
|
+
"""Highlight path as the open file and, when it's visible, put the cursor on it."""
|
|
399
|
+
if path == self.active_path:
|
|
400
|
+
return
|
|
401
|
+
self.active_path = path
|
|
402
|
+
self._clear_line_cache()
|
|
403
|
+
self.refresh()
|
|
404
|
+
if path is None or self.has_focus:
|
|
405
|
+
return # don't yank the cursor while the user is navigating the tree
|
|
406
|
+
stack = [self.root]
|
|
407
|
+
while stack:
|
|
408
|
+
node = stack.pop()
|
|
409
|
+
if getattr(node.data, "path", None) == path:
|
|
410
|
+
self.move_cursor(node)
|
|
411
|
+
return
|
|
412
|
+
if node.is_expanded:
|
|
413
|
+
stack.extend(node.children)
|
|
414
|
+
|
|
415
|
+
def filter_paths(self, paths: Iterable[Path]) -> Iterable[Path]:
|
|
416
|
+
if self.show_hidden:
|
|
417
|
+
return paths
|
|
418
|
+
return [
|
|
419
|
+
p
|
|
420
|
+
for p in paths
|
|
421
|
+
if not p.name.startswith(".") and p.name not in IGNORED_DIRS
|
|
422
|
+
]
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
class TabItem(Horizontal):
|
|
426
|
+
"""One editor tab: the file name plus a close button (× clean, ● unsaved)."""
|
|
427
|
+
|
|
428
|
+
def __init__(self, title: str, pane_id: str, tab_index: int, *, dirty: bool, active: bool) -> None:
|
|
429
|
+
super().__init__(classes="editor-tab")
|
|
430
|
+
self._title = title
|
|
431
|
+
self._dirty = dirty
|
|
432
|
+
self.pane_id = pane_id
|
|
433
|
+
self.tab_index = tab_index
|
|
434
|
+
self.set_class(active, "-active")
|
|
435
|
+
self.set_class(dirty, "-dirty")
|
|
436
|
+
|
|
437
|
+
def compose(self) -> ComposeResult:
|
|
438
|
+
yield TabButton(self._title, self.pane_id, self.tab_index, classes="editor-tab-btn")
|
|
439
|
+
close = TabCloseButton("●" if self._dirty else "×", self.pane_id, self.tab_index)
|
|
440
|
+
close.tooltip = "Close (Ctrl+W)"
|
|
441
|
+
yield close
|
|
442
|
+
|
|
443
|
+
def update_tab(self, title: str, pane_id: str, tab_index: int, *, dirty: bool, active: bool) -> None:
|
|
444
|
+
self.pane_id, self.tab_index = pane_id, tab_index
|
|
445
|
+
self.set_class(active, "-active")
|
|
446
|
+
self.set_class(dirty, "-dirty")
|
|
447
|
+
for child in self.children:
|
|
448
|
+
if isinstance(child, (TabButton, TabCloseButton)):
|
|
449
|
+
child.pane_id, child.tab_index = pane_id, tab_index
|
|
450
|
+
if isinstance(child, TabCloseButton):
|
|
451
|
+
child.label = "●" if dirty else "×"
|
|
452
|
+
elif isinstance(child, TabButton):
|
|
453
|
+
child.label = title
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
class TabCloseButton(Button):
|
|
457
|
+
"""The × on a tab."""
|
|
458
|
+
|
|
459
|
+
def __init__(self, label: str, pane_id: str, tab_index: int) -> None:
|
|
460
|
+
super().__init__(label, classes="editor-tab-close")
|
|
461
|
+
self.pane_id = pane_id
|
|
462
|
+
self.tab_index = tab_index
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
class TabButton(Button):
|
|
466
|
+
"""Button representing an editor tab strip item."""
|
|
467
|
+
|
|
468
|
+
def __init__(
|
|
469
|
+
self,
|
|
470
|
+
label: str,
|
|
471
|
+
pane_id: str,
|
|
472
|
+
tab_index: int,
|
|
473
|
+
*,
|
|
474
|
+
classes: str | None = None,
|
|
475
|
+
) -> None:
|
|
476
|
+
super().__init__(label, classes=classes)
|
|
477
|
+
self.pane_id = pane_id
|
|
478
|
+
self.tab_index = tab_index
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
class TermCodeApp(App[None]):
|
|
482
|
+
"""Lightweight VS Code-style terminal editor and runner for all major languages."""
|
|
483
|
+
|
|
484
|
+
CSS_PATH = "styles.tcss"
|
|
485
|
+
TITLE = "TermCode"
|
|
486
|
+
ENABLE_COMMAND_PALETTE = False
|
|
487
|
+
|
|
488
|
+
BINDINGS = [
|
|
489
|
+
Binding("ctrl+k", "open_palette", "/Menu", priority=True),
|
|
490
|
+
Binding("ctrl+s", "save_file", "Save", priority=True),
|
|
491
|
+
Binding("f5", "run_file", "Run", priority=True),
|
|
492
|
+
Binding("f7", "stop_run", "Stop", priority=True),
|
|
493
|
+
Binding("ctrl+n", "new_file", "New", priority=True),
|
|
494
|
+
Binding("f3", "new_folder", "NewDir", show=False, priority=True),
|
|
495
|
+
Binding("ctrl+p", "open_file", "Pick", priority=True),
|
|
496
|
+
Binding("ctrl+o", "open_folder", "Folder", priority=True),
|
|
497
|
+
Binding("f2", "rename_item", "Rename", priority=True),
|
|
498
|
+
Binding("f4", "delete_item", "Delete", show=False, priority=True),
|
|
499
|
+
Binding("f8", "save_file_as", "SaveAs", show=False, priority=True),
|
|
500
|
+
Binding("f9", "toggle_hidden", "Hidden", show=False, priority=True),
|
|
501
|
+
Binding("ctrl+up", "terminal_grow", "GrowTerm", show=False, priority=True),
|
|
502
|
+
Binding("ctrl+down", "terminal_shrink", "ShrinkTerm", show=False, priority=True),
|
|
503
|
+
Binding("f10", "copy_output", "CopyOut", show=False, priority=True),
|
|
504
|
+
Binding("f11", "next_tab", "NextTab", show=False, priority=True),
|
|
505
|
+
Binding("ctrl+w", "close_tab", "CloseTab", show=False, priority=True),
|
|
506
|
+
Binding("f12", "toggle_split", "Split", show=False, priority=True),
|
|
507
|
+
Binding("ctrl+b", "toggle_sidebar", "Files", priority=True),
|
|
508
|
+
Binding("ctrl+j", "toggle_terminal", "Terminal", priority=True),
|
|
509
|
+
Binding("ctrl+l", "clear_output", "Clear", show=False, priority=True),
|
|
510
|
+
Binding("ctrl+q", "request_quit", "Quit", priority=True),
|
|
511
|
+
Binding("ctrl+f", "find", "Find", show=False, priority=True),
|
|
512
|
+
Binding("ctrl+r", "replace", "Replace", show=False, priority=True),
|
|
513
|
+
Binding("ctrl+g", "goto_line", "GoTo", show=False, priority=True),
|
|
514
|
+
Binding("shift+f5", "run_in_terminal", "RunTerm", show=False, priority=True),
|
|
515
|
+
Binding("ctrl+t", "open_shell", "Shell", show=False, priority=True),
|
|
516
|
+
Binding("f6", "format_file", "Format", show=False, priority=True),
|
|
517
|
+
]
|
|
518
|
+
|
|
519
|
+
def __init__(
|
|
520
|
+
self,
|
|
521
|
+
workspace_root: Path | None = None,
|
|
522
|
+
initial_file: Path | None = None,
|
|
523
|
+
*,
|
|
524
|
+
recent_store: Path | None = None,
|
|
525
|
+
) -> None:
|
|
526
|
+
super().__init__()
|
|
527
|
+
self.workspace_root: Path | None = workspace_root.resolve() if workspace_root else None
|
|
528
|
+
self._initial_file: Path | None = initial_file.resolve() if initial_file else None
|
|
529
|
+
self.selected_path: Path | None = self._initial_file or self.workspace_root
|
|
530
|
+
self.left_pane: EditorPaneState = EditorPaneState()
|
|
531
|
+
self.right_pane: EditorPaneState = EditorPaneState()
|
|
532
|
+
self.active_pane_id: str = "left"
|
|
533
|
+
self.is_split: bool = False
|
|
534
|
+
self._suppress_dirty: bool = False
|
|
535
|
+
self.runner: AsyncRunner = AsyncRunner()
|
|
536
|
+
self._flushed_output: str = ""
|
|
537
|
+
self._pending_output: list[str] = []
|
|
538
|
+
self._flush_scheduled: bool = False
|
|
539
|
+
self._last_flush: float = 0.0
|
|
540
|
+
self.terminal_height: int = DEFAULT_TERMINAL_HEIGHT
|
|
541
|
+
self.sidebar_width: int = DEFAULT_SIDEBAR_WIDTH
|
|
542
|
+
# What the user chose; the start page hides Output regardless.
|
|
543
|
+
self.output_visible: bool = True
|
|
544
|
+
self.format_on_save: bool = True
|
|
545
|
+
self._recent_store: Path | None = recent_store
|
|
546
|
+
self._recent_folders: list[Path] = []
|
|
547
|
+
self._completion_editor: CodeTextArea | None = None
|
|
548
|
+
self._completion_prefix: str = ""
|
|
549
|
+
self._completion_items: list[str] = []
|
|
550
|
+
self._just_accepted_completion: bool = False
|
|
551
|
+
|
|
552
|
+
@property
|
|
553
|
+
def output_history(self) -> str:
|
|
554
|
+
"""Everything printed to the Output panel, including not-yet-rendered chunks."""
|
|
555
|
+
if self._pending_output:
|
|
556
|
+
return self._flushed_output + "".join(self._pending_output)
|
|
557
|
+
return self._flushed_output
|
|
558
|
+
|
|
559
|
+
@output_history.setter
|
|
560
|
+
def output_history(self, value: str) -> None:
|
|
561
|
+
self._pending_output.clear()
|
|
562
|
+
self._flushed_output = value
|
|
563
|
+
|
|
564
|
+
@property
|
|
565
|
+
def active_file(self) -> Path | None:
|
|
566
|
+
buf = self._active_pane().active_buffer
|
|
567
|
+
return buf.path if buf is not None else None
|
|
568
|
+
|
|
569
|
+
@active_file.setter
|
|
570
|
+
def active_file(self, value: Path | None) -> None:
|
|
571
|
+
buf = self._active_pane().active_buffer
|
|
572
|
+
if buf is not None:
|
|
573
|
+
buf.path = value.resolve() if value is not None else None
|
|
574
|
+
|
|
575
|
+
@property
|
|
576
|
+
def is_dirty(self) -> bool:
|
|
577
|
+
buf = self._active_pane().active_buffer
|
|
578
|
+
return buf.is_dirty if buf is not None else False
|
|
579
|
+
|
|
580
|
+
@is_dirty.setter
|
|
581
|
+
def is_dirty(self, value: bool) -> None:
|
|
582
|
+
buf = self._active_pane().active_buffer
|
|
583
|
+
if buf is not None and not value:
|
|
584
|
+
buf.saved_content = buf.content
|
|
585
|
+
|
|
586
|
+
def _pane_for_id(self, pane_id: str) -> EditorPaneState:
|
|
587
|
+
return self.right_pane if pane_id == "right" else self.left_pane
|
|
588
|
+
|
|
589
|
+
def _active_pane(self) -> EditorPaneState:
|
|
590
|
+
return self._pane_for_id(self.active_pane_id)
|
|
591
|
+
|
|
592
|
+
def _editor_for_pane(self, pane_id: str) -> CodeTextArea:
|
|
593
|
+
widget_id = "#editor-right" if pane_id == "right" else "#editor"
|
|
594
|
+
return self.query_one(widget_id, CodeTextArea)
|
|
595
|
+
|
|
596
|
+
def _active_editor(self) -> CodeTextArea:
|
|
597
|
+
return self._editor_for_pane(self.active_pane_id)
|
|
598
|
+
|
|
599
|
+
def compose(self) -> ComposeResult:
|
|
600
|
+
initial_tree_root = self.workspace_root or Path.home()
|
|
601
|
+
with Horizontal(id="workspace-body"):
|
|
602
|
+
with Vertical(id="sidebar"):
|
|
603
|
+
with Vertical(id="sidebar-folder-bar"):
|
|
604
|
+
yield Static("", id="sidebar-folder", markup=False)
|
|
605
|
+
with Horizontal(id="sidebar-actions"):
|
|
606
|
+
new_file_btn = Button("+ file", id="sidebar-new-file-btn", classes="sidebar-tool-btn")
|
|
607
|
+
new_file_btn.tooltip = "New file (Ctrl+N)"
|
|
608
|
+
yield new_file_btn
|
|
609
|
+
new_dir_btn = Button("+ dir", id="sidebar-new-dir-btn", classes="sidebar-tool-btn")
|
|
610
|
+
new_dir_btn.tooltip = "New folder (F3)"
|
|
611
|
+
yield new_dir_btn
|
|
612
|
+
yield Static("", classes="spacer")
|
|
613
|
+
hide_side_btn = Button("«", id="sidebar-hide-btn", classes="sidebar-tool-btn")
|
|
614
|
+
hide_side_btn.tooltip = "Hide sidebar (Ctrl+B)"
|
|
615
|
+
yield hide_side_btn
|
|
616
|
+
with Vertical(id="no-folder-box"):
|
|
617
|
+
yield Static(
|
|
618
|
+
"No folder open.",
|
|
619
|
+
id="no-folder-text",
|
|
620
|
+
markup=False,
|
|
621
|
+
)
|
|
622
|
+
yield Button("Open folder", id="sidebar-open-folder-btn")
|
|
623
|
+
yield Static("or press Ctrl+O", id="no-folder-hint", markup=False)
|
|
624
|
+
yield FilteredDirectoryTree(str(initial_tree_root), id="file-tree")
|
|
625
|
+
yield SidebarResizeHandle(id="sidebar-handle")
|
|
626
|
+
|
|
627
|
+
with Vertical(id="main-pane"):
|
|
628
|
+
with Horizontal(id="editors-row"):
|
|
629
|
+
with Vertical(id="left-editor-col"):
|
|
630
|
+
with Horizontal(id="tab-bar"):
|
|
631
|
+
with Horizontal(id="left-tabs"):
|
|
632
|
+
yield Static("Home", id="active-tab", markup=False)
|
|
633
|
+
yield Static("", id="tab-meta", markup=False)
|
|
634
|
+
split_btn = Button("Split", id="split-toggle-btn", classes="term-tool-btn")
|
|
635
|
+
split_btn.tooltip = "Split editor (F12)"
|
|
636
|
+
yield split_btn
|
|
637
|
+
|
|
638
|
+
with Vertical(id="welcome-view"):
|
|
639
|
+
with Vertical(id="welcome-card"):
|
|
640
|
+
yield Static(
|
|
641
|
+
Text.assemble(
|
|
642
|
+
("termcode", f"bold {theme.TEXT}"),
|
|
643
|
+
(f" {__version__}", theme.FAINT),
|
|
644
|
+
),
|
|
645
|
+
id="welcome-title",
|
|
646
|
+
)
|
|
647
|
+
yield Static(
|
|
648
|
+
"Open a folder to start writing and running code.",
|
|
649
|
+
id="welcome-subtitle",
|
|
650
|
+
markup=False,
|
|
651
|
+
)
|
|
652
|
+
yield Button(
|
|
653
|
+
"Open folder Ctrl+O",
|
|
654
|
+
id="home-open-folder-btn",
|
|
655
|
+
)
|
|
656
|
+
with Vertical(id="home-recent-section"):
|
|
657
|
+
yield Static(
|
|
658
|
+
"Recent",
|
|
659
|
+
classes="welcome-section-title",
|
|
660
|
+
markup=False,
|
|
661
|
+
)
|
|
662
|
+
yield OptionList(id="recent-list")
|
|
663
|
+
yield Static(
|
|
664
|
+
"Folders you open will show up here.",
|
|
665
|
+
id="recent-empty",
|
|
666
|
+
markup=False,
|
|
667
|
+
)
|
|
668
|
+
yield Static(
|
|
669
|
+
"Run termcode inside a project folder to skip this screen.",
|
|
670
|
+
id="welcome-tip",
|
|
671
|
+
markup=False,
|
|
672
|
+
)
|
|
673
|
+
|
|
674
|
+
yield CodeTextArea.code_editor(
|
|
675
|
+
"",
|
|
676
|
+
language=None,
|
|
677
|
+
theme="vscode_dark",
|
|
678
|
+
show_line_numbers=True,
|
|
679
|
+
id="editor",
|
|
680
|
+
)
|
|
681
|
+
|
|
682
|
+
with Vertical(id="right-editor-col"):
|
|
683
|
+
with Horizontal(id="right-tab-bar"):
|
|
684
|
+
with Horizontal(id="right-tabs"):
|
|
685
|
+
pass
|
|
686
|
+
yield Button("×", id="close-split-btn", classes="term-tool-btn")
|
|
687
|
+
yield CodeTextArea.code_editor(
|
|
688
|
+
"",
|
|
689
|
+
language=None,
|
|
690
|
+
theme="vscode_dark",
|
|
691
|
+
show_line_numbers=True,
|
|
692
|
+
id="editor-right",
|
|
693
|
+
)
|
|
694
|
+
|
|
695
|
+
yield FindBar(self._active_editor, id="find-bar")
|
|
696
|
+
|
|
697
|
+
with Vertical(id="output-pane"):
|
|
698
|
+
edge = OutputEdge(id="output-edge")
|
|
699
|
+
edge.tooltip = "Drag to resize"
|
|
700
|
+
yield edge
|
|
701
|
+
with Horizontal(id="output-header-bar"):
|
|
702
|
+
handle = TerminalResizeHandle("", id="output-header")
|
|
703
|
+
handle.tooltip = "Drag to resize (or Ctrl+Up / Ctrl+Down)"
|
|
704
|
+
yield handle
|
|
705
|
+
yield Button("▴", id="term-grow-btn", classes="term-tool-btn")
|
|
706
|
+
yield Button("▾", id="term-shrink-btn", classes="term-tool-btn")
|
|
707
|
+
yield Button("Copy", id="term-copy-btn", classes="term-tool-btn")
|
|
708
|
+
yield Button("Clear", id="term-clear-btn", classes="term-tool-btn")
|
|
709
|
+
hide_out_btn = Button("×", id="term-hide-btn", classes="term-tool-btn")
|
|
710
|
+
hide_out_btn.tooltip = "Hide Output (Ctrl+J)"
|
|
711
|
+
yield hide_out_btn
|
|
712
|
+
yield CodeTextArea(
|
|
713
|
+
"",
|
|
714
|
+
read_only=True,
|
|
715
|
+
show_line_numbers=False,
|
|
716
|
+
soft_wrap=True,
|
|
717
|
+
theme="vscode_dark",
|
|
718
|
+
id="output-log",
|
|
719
|
+
)
|
|
720
|
+
yield Input(
|
|
721
|
+
placeholder="Type input for the program, then Enter",
|
|
722
|
+
disabled=True,
|
|
723
|
+
id="stdin-input",
|
|
724
|
+
)
|
|
725
|
+
|
|
726
|
+
yield OptionList(id="completion-popup")
|
|
727
|
+
with Horizontal(id="status-bar"):
|
|
728
|
+
files_btn = Button("Files", id="status-files-btn", classes="status-toggle -on")
|
|
729
|
+
files_btn.tooltip = "Show or hide the sidebar (Ctrl+B)"
|
|
730
|
+
yield files_btn
|
|
731
|
+
out_btn = Button("Output", id="status-output-btn", classes="status-toggle -on")
|
|
732
|
+
out_btn.tooltip = "Show or hide Output (Ctrl+J)"
|
|
733
|
+
yield out_btn
|
|
734
|
+
yield Static("", id="status-left", markup=False)
|
|
735
|
+
yield Static("", id="status-right", markup=False)
|
|
736
|
+
|
|
737
|
+
def on_mount(self) -> None:
|
|
738
|
+
self.query_one("#stdin-input", Input).display = False
|
|
739
|
+
self.query_one("#right-editor-col").display = False
|
|
740
|
+
self.query_one("#completion-popup").display = False
|
|
741
|
+
self.query_one("#find-bar").display = False
|
|
742
|
+
self._set_run_state("idle")
|
|
743
|
+
self._refresh_recent_list()
|
|
744
|
+
|
|
745
|
+
if self.workspace_root is not None:
|
|
746
|
+
record_recent_folder(self.workspace_root, store_path=self._recent_store)
|
|
747
|
+
self._sync_workspace_ui(show_welcome=False)
|
|
748
|
+
if self._initial_file is not None:
|
|
749
|
+
if not self.load_file(self._initial_file):
|
|
750
|
+
self.left_pane.ensure_untitled()
|
|
751
|
+
self.selected_path = self.workspace_root
|
|
752
|
+
self._render_pane("left")
|
|
753
|
+
self._update_chrome()
|
|
754
|
+
else:
|
|
755
|
+
self.left_pane.ensure_untitled()
|
|
756
|
+
self._render_pane("left")
|
|
757
|
+
self._update_chrome()
|
|
758
|
+
self.query_one("#editor", CodeTextArea).focus()
|
|
759
|
+
else:
|
|
760
|
+
self._sync_workspace_ui(show_welcome=True)
|
|
761
|
+
self._update_chrome()
|
|
762
|
+
self.query_one("#home-open-folder-btn", Button).focus()
|
|
763
|
+
|
|
764
|
+
def _on_main_screen(self) -> bool:
|
|
765
|
+
return len(self.screen_stack) == 1
|
|
766
|
+
|
|
767
|
+
def _sync_workspace_ui(self, *, show_welcome: bool) -> None:
|
|
768
|
+
has_folder = self.workspace_root is not None
|
|
769
|
+
self.query_one("#no-folder-box").display = not has_folder
|
|
770
|
+
self.query_one("#file-tree").display = has_folder
|
|
771
|
+
folder_bar = self.query_one("#sidebar-folder-bar")
|
|
772
|
+
folder_bar.display = has_folder
|
|
773
|
+
if self.workspace_root is not None:
|
|
774
|
+
self.query_one("#sidebar-folder", Static).update(self.workspace_root.name)
|
|
775
|
+
|
|
776
|
+
self.query_one("#welcome-view").display = show_welcome
|
|
777
|
+
self.query_one("#editor").display = not show_welcome
|
|
778
|
+
self.query_one("#output-pane").display = not show_welcome and self.output_visible
|
|
779
|
+
self._sync_layout_toggles()
|
|
780
|
+
self.query_one("#split-toggle-btn").display = not show_welcome
|
|
781
|
+
if show_welcome and self.is_split:
|
|
782
|
+
self.is_split = False
|
|
783
|
+
self.query_one("#right-editor-col").display = False
|
|
784
|
+
|
|
785
|
+
def _refresh_recent_list(self) -> None:
|
|
786
|
+
self._recent_folders = load_recent_folders(store_path=self._recent_store)
|
|
787
|
+
recent_list = self.query_one("#recent-list", OptionList)
|
|
788
|
+
empty_label = self.query_one("#recent-empty", Static)
|
|
789
|
+
recent_list.clear_options()
|
|
790
|
+
if not self._recent_folders:
|
|
791
|
+
recent_list.display = False
|
|
792
|
+
empty_label.display = True
|
|
793
|
+
return
|
|
794
|
+
recent_list.display = True
|
|
795
|
+
empty_label.display = False
|
|
796
|
+
home = Path.home()
|
|
797
|
+
for idx, folder in enumerate(self._recent_folders):
|
|
798
|
+
try:
|
|
799
|
+
display_path = "~/" + folder.relative_to(home).as_posix()
|
|
800
|
+
except ValueError:
|
|
801
|
+
display_path = str(folder)
|
|
802
|
+
row = Text(no_wrap=True, overflow="ellipsis")
|
|
803
|
+
row.append(folder.name, theme.TEXT)
|
|
804
|
+
row.append(f" {display_path}", theme.FAINT)
|
|
805
|
+
recent_list.add_option(Option(row, id=str(idx)))
|
|
806
|
+
|
|
807
|
+
def _apply_editor_language(self, editor: CodeTextArea, path: Path | None) -> None:
|
|
808
|
+
wanted = editor_language_for_path(path)
|
|
809
|
+
if wanted and wanted in editor.available_languages:
|
|
810
|
+
editor.language = wanted
|
|
811
|
+
else:
|
|
812
|
+
editor.language = None
|
|
813
|
+
|
|
814
|
+
def _sync_buffer_from_editor(self, pane_id: str) -> None:
|
|
815
|
+
pane = self._pane_for_id(pane_id)
|
|
816
|
+
buf = pane.active_buffer
|
|
817
|
+
if buf is None:
|
|
818
|
+
return
|
|
819
|
+
editor = self._editor_for_pane(pane_id)
|
|
820
|
+
buf.content = editor.text
|
|
821
|
+
buf.cursor = editor.cursor_location
|
|
822
|
+
|
|
823
|
+
def _rebuild_tab_strip(self, pane_id: str) -> None:
|
|
824
|
+
container_id = "#right-tabs" if pane_id == "right" else "#left-tabs"
|
|
825
|
+
try:
|
|
826
|
+
container = self.query_one(container_id, Horizontal)
|
|
827
|
+
except Exception:
|
|
828
|
+
return
|
|
829
|
+
|
|
830
|
+
pane = self._pane_for_id(pane_id)
|
|
831
|
+
on_welcome = pane_id == "left" and self.query_one("#welcome-view").display
|
|
832
|
+
|
|
833
|
+
if pane_id == "left":
|
|
834
|
+
try:
|
|
835
|
+
home_tab = self.query_one("#active-tab", Static)
|
|
836
|
+
home_tab.display = on_welcome
|
|
837
|
+
if on_welcome:
|
|
838
|
+
home_tab.update("Home")
|
|
839
|
+
except Exception:
|
|
840
|
+
pass
|
|
841
|
+
|
|
842
|
+
if on_welcome:
|
|
843
|
+
for child in list(container.children):
|
|
844
|
+
if child.id != "active-tab":
|
|
845
|
+
child.remove()
|
|
846
|
+
return
|
|
847
|
+
|
|
848
|
+
if pane_id == "right":
|
|
849
|
+
try:
|
|
850
|
+
self.query_one("#right-active-tab", Static).display = False
|
|
851
|
+
except Exception:
|
|
852
|
+
pass
|
|
853
|
+
|
|
854
|
+
existing = [c for c in container.children if isinstance(c, TabItem)]
|
|
855
|
+
for idx, buf in enumerate(pane.tabs):
|
|
856
|
+
active = idx == pane.active_index
|
|
857
|
+
if idx < len(existing):
|
|
858
|
+
existing[idx].update_tab(buf.title, pane_id, idx, dirty=buf.is_dirty, active=active)
|
|
859
|
+
else:
|
|
860
|
+
container.mount(TabItem(buf.title, pane_id, idx, dirty=buf.is_dirty, active=active))
|
|
861
|
+
for extra in existing[len(pane.tabs):]:
|
|
862
|
+
extra.remove()
|
|
863
|
+
|
|
864
|
+
def _render_pane(self, pane_id: str) -> None:
|
|
865
|
+
pane = self._pane_for_id(pane_id)
|
|
866
|
+
editor = self._editor_for_pane(pane_id)
|
|
867
|
+
buf = pane.active_buffer
|
|
868
|
+
|
|
869
|
+
self._suppress_dirty = True
|
|
870
|
+
try:
|
|
871
|
+
if buf is None:
|
|
872
|
+
editor.text = ""
|
|
873
|
+
editor.language = None
|
|
874
|
+
else:
|
|
875
|
+
editor.text = buf.content
|
|
876
|
+
self._apply_editor_language(editor, buf.path)
|
|
877
|
+
try:
|
|
878
|
+
editor.cursor_location = buf.cursor
|
|
879
|
+
except Exception:
|
|
880
|
+
pass
|
|
881
|
+
finally:
|
|
882
|
+
self._suppress_dirty = False
|
|
883
|
+
|
|
884
|
+
self._rebuild_tab_strip(pane_id)
|
|
885
|
+
|
|
886
|
+
def _update_chrome(self) -> None:
|
|
887
|
+
meta = self.query_one("#tab-meta", Static)
|
|
888
|
+
status_left = self.query_one("#status-left", Static)
|
|
889
|
+
status_right = self.query_one("#status-right", Static)
|
|
890
|
+
on_welcome = self.query_one("#welcome-view").display
|
|
891
|
+
|
|
892
|
+
if on_welcome:
|
|
893
|
+
self._rebuild_tab_strip("left")
|
|
894
|
+
meta.update("No Folder Opened" if self.workspace_root is None else str(self.workspace_root))
|
|
895
|
+
else:
|
|
896
|
+
self._rebuild_tab_strip("left")
|
|
897
|
+
if self.is_split:
|
|
898
|
+
self._rebuild_tab_strip("right")
|
|
899
|
+
# Show the folder path only when the file lives below the root;
|
|
900
|
+
# otherwise it would just repeat the tab title.
|
|
901
|
+
active_path = self.active_file
|
|
902
|
+
hint = ""
|
|
903
|
+
if active_path is not None:
|
|
904
|
+
if self.workspace_root is not None:
|
|
905
|
+
try:
|
|
906
|
+
parent = active_path.parent.relative_to(self.workspace_root).as_posix()
|
|
907
|
+
hint = "" if parent == "." else f"{parent}/"
|
|
908
|
+
except ValueError:
|
|
909
|
+
hint = str(active_path.parent)
|
|
910
|
+
else:
|
|
911
|
+
hint = str(active_path.parent)
|
|
912
|
+
meta.update(hint)
|
|
913
|
+
tree = self.query_one("#file-tree", FilteredDirectoryTree)
|
|
914
|
+
tree.show_active(active_path.resolve() if active_path is not None else None)
|
|
915
|
+
|
|
916
|
+
sep = " "
|
|
917
|
+
left = Text(no_wrap=True, overflow="ellipsis")
|
|
918
|
+
if self.workspace_root is not None:
|
|
919
|
+
left.append(self.workspace_root.name, theme.TEXT)
|
|
920
|
+
branch = current_git_branch(self.workspace_root)
|
|
921
|
+
if branch:
|
|
922
|
+
left.append(f"{sep}⎇ {branch}", theme.MUTED)
|
|
923
|
+
else:
|
|
924
|
+
left.append("No folder", theme.MUTED)
|
|
925
|
+
status_left.update(left)
|
|
926
|
+
|
|
927
|
+
right = Text(no_wrap=True)
|
|
928
|
+
if not on_welcome:
|
|
929
|
+
editor = self._active_editor()
|
|
930
|
+
row, col = editor.cursor_location
|
|
931
|
+
lang_label = language_label_for_path(self.active_file)
|
|
932
|
+
right.append(f"Ln {row + 1}, Col {col + 1}{sep}{lang_label}{sep}", theme.MUTED)
|
|
933
|
+
right.append("Ctrl+K", theme.TEXT)
|
|
934
|
+
right.append(" commands", theme.MUTED)
|
|
935
|
+
status_right.update(right)
|
|
936
|
+
|
|
937
|
+
def _set_run_state(self, state: str, detail: str = "") -> None:
|
|
938
|
+
"""Paint the Output header and its left stripe for idle/running/ok/fail."""
|
|
939
|
+
glyphs = {
|
|
940
|
+
"idle": ("", theme.MUTED),
|
|
941
|
+
"running": ("● running", theme.BUSY),
|
|
942
|
+
"ok": ("✓", theme.OK),
|
|
943
|
+
"fail": ("✗", theme.FAIL),
|
|
944
|
+
"stopped": ("■ stopped", theme.MUTED),
|
|
945
|
+
}
|
|
946
|
+
label, color = glyphs.get(state, glyphs["idle"])
|
|
947
|
+
header = Text(no_wrap=True, overflow="ellipsis")
|
|
948
|
+
header.append("Output", f"bold {theme.TEXT}")
|
|
949
|
+
if label:
|
|
950
|
+
header.append(" ")
|
|
951
|
+
header.append(label, f"bold {color}")
|
|
952
|
+
if detail:
|
|
953
|
+
header.append(f" {detail}", theme.MUTED)
|
|
954
|
+
self.query_one("#output-header", Static).update(header)
|
|
955
|
+
pane = self.query_one("#output-pane")
|
|
956
|
+
for s in glyphs:
|
|
957
|
+
pane.set_class(s == state, f"-{s}")
|
|
958
|
+
|
|
959
|
+
def _refresh_tree(self) -> None:
|
|
960
|
+
if self.workspace_root is None:
|
|
961
|
+
return
|
|
962
|
+
tree = self.query_one("#file-tree", FilteredDirectoryTree)
|
|
963
|
+
tree.path = self.workspace_root
|
|
964
|
+
tree.reload()
|
|
965
|
+
|
|
966
|
+
def _target_dir_for_create(self) -> Path:
|
|
967
|
+
if self.selected_path is not None and self.selected_path.exists():
|
|
968
|
+
if self.selected_path.is_dir():
|
|
969
|
+
return self.selected_path
|
|
970
|
+
return self.selected_path.parent
|
|
971
|
+
if self.active_file is not None and self.active_file.parent.exists():
|
|
972
|
+
return self.active_file.parent
|
|
973
|
+
if self.workspace_root is not None:
|
|
974
|
+
return self.workspace_root
|
|
975
|
+
return Path.cwd()
|
|
976
|
+
|
|
977
|
+
def _target_path_for_edit(self) -> Path | None:
|
|
978
|
+
if (
|
|
979
|
+
self.selected_path is not None
|
|
980
|
+
and self.selected_path.exists()
|
|
981
|
+
and (
|
|
982
|
+
self.workspace_root is None
|
|
983
|
+
or self.selected_path.resolve() != self.workspace_root.resolve()
|
|
984
|
+
)
|
|
985
|
+
):
|
|
986
|
+
return self.selected_path
|
|
987
|
+
if self.active_file is not None and self.active_file.exists():
|
|
988
|
+
return self.active_file
|
|
989
|
+
return None
|
|
990
|
+
|
|
991
|
+
# ---- Clipboard & Terminal ----
|
|
992
|
+
|
|
993
|
+
def copy_to_clipboard(self, text: str) -> None:
|
|
994
|
+
super().copy_to_clipboard(text)
|
|
995
|
+
_copy_to_os_clipboard(text)
|
|
996
|
+
|
|
997
|
+
def set_terminal_height(self, height: int) -> None:
|
|
998
|
+
"""Resize the bottom Terminal panel within safe screen bounds."""
|
|
999
|
+
max_h = max(MIN_TERMINAL_HEIGHT + 2, self.size.height - 9) if self.size.height else 30
|
|
1000
|
+
clamped = max(MIN_TERMINAL_HEIGHT, min(height, max_h))
|
|
1001
|
+
self.terminal_height = clamped
|
|
1002
|
+
self.query_one("#output-pane").styles.height = clamped
|
|
1003
|
+
|
|
1004
|
+
def append_output(self, text: str) -> None:
|
|
1005
|
+
"""Queue a chunk for the Output panel; chunks are flushed in batches.
|
|
1006
|
+
|
|
1007
|
+
Programs that print in a tight loop deliver thousands of tiny chunks.
|
|
1008
|
+
Re-rendering the whole log per chunk is quadratic and froze the UI, so
|
|
1009
|
+
chunks are buffered and appended at most ~30 times per second.
|
|
1010
|
+
"""
|
|
1011
|
+
if not text:
|
|
1012
|
+
return
|
|
1013
|
+
clean = Text.from_ansi(text).plain
|
|
1014
|
+
if not clean:
|
|
1015
|
+
return
|
|
1016
|
+
self._pending_output.append(clean)
|
|
1017
|
+
if self._flush_scheduled:
|
|
1018
|
+
return
|
|
1019
|
+
wait = self._last_flush + OUTPUT_FLUSH_INTERVAL - time.monotonic()
|
|
1020
|
+
if wait <= 0:
|
|
1021
|
+
self._flush_output() # quiet stream: show it immediately
|
|
1022
|
+
else:
|
|
1023
|
+
self._flush_scheduled = True
|
|
1024
|
+
self.set_timer(wait, self._scheduled_flush)
|
|
1025
|
+
|
|
1026
|
+
def _scheduled_flush(self) -> None:
|
|
1027
|
+
self._flush_scheduled = False
|
|
1028
|
+
self._flush_output()
|
|
1029
|
+
|
|
1030
|
+
def _flush_output(self) -> None:
|
|
1031
|
+
if not self._pending_output:
|
|
1032
|
+
return
|
|
1033
|
+
self._last_flush = time.monotonic()
|
|
1034
|
+
# Query the base screen so output keeps flowing while a modal is open.
|
|
1035
|
+
try:
|
|
1036
|
+
log = self.screen_stack[0].query_one("#output-log", CodeTextArea)
|
|
1037
|
+
except (NoMatches, IndexError): # app is shutting down
|
|
1038
|
+
return
|
|
1039
|
+
chunk = "".join(self._pending_output)
|
|
1040
|
+
self._pending_output.clear()
|
|
1041
|
+
follow = log.scroll_y >= log.max_scroll_y - 1
|
|
1042
|
+
self._flushed_output += chunk
|
|
1043
|
+
if len(self._flushed_output) > MAX_OUTPUT_HISTORY_CHARS:
|
|
1044
|
+
# Trim well below the cap so the full reload happens rarely.
|
|
1045
|
+
keep = int(MAX_OUTPUT_HISTORY_CHARS * 0.8)
|
|
1046
|
+
self._flushed_output = self._flushed_output[-keep:]
|
|
1047
|
+
log.load_text(self._flushed_output)
|
|
1048
|
+
else:
|
|
1049
|
+
log.insert(chunk, log.document.end, maintain_selection_offset=False)
|
|
1050
|
+
log.history.clear()
|
|
1051
|
+
if follow:
|
|
1052
|
+
log.scroll_end(animate=False)
|
|
1053
|
+
|
|
1054
|
+
# ---- Inline Autocomplete Popup ----
|
|
1055
|
+
|
|
1056
|
+
def is_completion_open_for(self, editor: CodeTextArea) -> bool:
|
|
1057
|
+
popup = self.query_one("#completion-popup", OptionList)
|
|
1058
|
+
return bool(popup.display and self._completion_editor is editor and self._completion_items)
|
|
1059
|
+
|
|
1060
|
+
def hide_completions(self) -> None:
|
|
1061
|
+
popup = self.query_one("#completion-popup", OptionList)
|
|
1062
|
+
popup.display = False
|
|
1063
|
+
self._completion_editor = None
|
|
1064
|
+
self._completion_prefix = ""
|
|
1065
|
+
self._completion_items = []
|
|
1066
|
+
|
|
1067
|
+
def _update_completions(self, editor: CodeTextArea) -> None:
|
|
1068
|
+
if editor.read_only or not self._on_main_screen():
|
|
1069
|
+
self.hide_completions()
|
|
1070
|
+
return
|
|
1071
|
+
row, col = editor.cursor_location
|
|
1072
|
+
line = editor.document.get_line(row)
|
|
1073
|
+
prefix = extract_prefix(line, col)
|
|
1074
|
+
items = get_completions(prefix, editor.language, editor.text, limit=7)
|
|
1075
|
+
if not items:
|
|
1076
|
+
self.hide_completions()
|
|
1077
|
+
return
|
|
1078
|
+
|
|
1079
|
+
popup = self.query_one("#completion-popup", OptionList)
|
|
1080
|
+
popup.clear_options()
|
|
1081
|
+
for word in items:
|
|
1082
|
+
popup.add_option(Option(word, id=word))
|
|
1083
|
+
popup.highlighted = 0
|
|
1084
|
+
|
|
1085
|
+
cx, cy = editor.cursor_screen_offset
|
|
1086
|
+
popup_h = min(len(items) + 2, 9)
|
|
1087
|
+
max_x = max(0, self.size.width - 34)
|
|
1088
|
+
max_y = max(0, self.size.height - popup_h - 2)
|
|
1089
|
+
pos_x = max(0, min(cx, max_x))
|
|
1090
|
+
pos_y = cy + 1 if (cy + 1) <= max_y else max(0, cy - popup_h)
|
|
1091
|
+
popup.styles.offset = (pos_x, pos_y)
|
|
1092
|
+
popup.display = True
|
|
1093
|
+
|
|
1094
|
+
self._completion_editor = editor
|
|
1095
|
+
self._completion_prefix = prefix
|
|
1096
|
+
self._completion_items = items
|
|
1097
|
+
|
|
1098
|
+
def move_completion(self, delta: int) -> None:
|
|
1099
|
+
popup = self.query_one("#completion-popup", OptionList)
|
|
1100
|
+
if not self._completion_items:
|
|
1101
|
+
return
|
|
1102
|
+
cur = popup.highlighted if popup.highlighted is not None else 0
|
|
1103
|
+
popup.highlighted = (cur + delta) % len(self._completion_items)
|
|
1104
|
+
|
|
1105
|
+
def accept_completion(self, editor: CodeTextArea | None = None) -> None:
|
|
1106
|
+
target = editor or self._completion_editor
|
|
1107
|
+
if target is None or not self._completion_items:
|
|
1108
|
+
self.hide_completions()
|
|
1109
|
+
return
|
|
1110
|
+
popup = self.query_one("#completion-popup", OptionList)
|
|
1111
|
+
idx = popup.highlighted if popup.highlighted is not None else 0
|
|
1112
|
+
if not (0 <= idx < len(self._completion_items)):
|
|
1113
|
+
self.hide_completions()
|
|
1114
|
+
return
|
|
1115
|
+
word = self._completion_items[idx]
|
|
1116
|
+
prefix = self._completion_prefix
|
|
1117
|
+
row, col = target.cursor_location
|
|
1118
|
+
start_col = max(0, col - len(prefix))
|
|
1119
|
+
self.hide_completions()
|
|
1120
|
+
self._just_accepted_completion = True
|
|
1121
|
+
target.replace(word, (row, start_col), (row, col))
|
|
1122
|
+
target.focus()
|
|
1123
|
+
|
|
1124
|
+
# ---- File & Buffer Operations ----
|
|
1125
|
+
|
|
1126
|
+
def load_file(self, path: Path, *, pane_id: str | None = None) -> bool:
|
|
1127
|
+
"""Open a text file as a tab in the target (or active) pane."""
|
|
1128
|
+
resolved = path.resolve()
|
|
1129
|
+
target_pane_id = pane_id or self.active_pane_id
|
|
1130
|
+
pane = self._pane_for_id(target_pane_id)
|
|
1131
|
+
|
|
1132
|
+
# Save edits of current tab in this pane before switching
|
|
1133
|
+
self._sync_buffer_from_editor(target_pane_id)
|
|
1134
|
+
|
|
1135
|
+
# If already open in this pane, just focus its existing tab (preserving edits)
|
|
1136
|
+
existing_idx = pane.index_of_path(resolved)
|
|
1137
|
+
if existing_idx is not None:
|
|
1138
|
+
self._sync_workspace_ui(show_welcome=False)
|
|
1139
|
+
pane.select_tab(existing_idx)
|
|
1140
|
+
self.active_pane_id = target_pane_id
|
|
1141
|
+
self.selected_path = resolved
|
|
1142
|
+
self._render_pane(target_pane_id)
|
|
1143
|
+
self._update_chrome()
|
|
1144
|
+
self._editor_for_pane(target_pane_id).focus()
|
|
1145
|
+
return True
|
|
1146
|
+
|
|
1147
|
+
try:
|
|
1148
|
+
content = read_text_file(resolved)
|
|
1149
|
+
except WorkspaceError as exc:
|
|
1150
|
+
self.notify(str(exc), severity="error")
|
|
1151
|
+
return False
|
|
1152
|
+
|
|
1153
|
+
self._sync_workspace_ui(show_welcome=False)
|
|
1154
|
+
pane.open_file(resolved, content)
|
|
1155
|
+
self.active_pane_id = target_pane_id
|
|
1156
|
+
self.selected_path = resolved
|
|
1157
|
+
self._render_pane(target_pane_id)
|
|
1158
|
+
self._update_chrome()
|
|
1159
|
+
self._editor_for_pane(target_pane_id).focus()
|
|
1160
|
+
return True
|
|
1161
|
+
|
|
1162
|
+
def _open_workspace_folder(self, candidate: Path) -> None:
|
|
1163
|
+
resolved = candidate.resolve()
|
|
1164
|
+
if not resolved.is_dir():
|
|
1165
|
+
self.notify(f"Folder not found: {resolved}", severity="error")
|
|
1166
|
+
return
|
|
1167
|
+
|
|
1168
|
+
def _do_switch() -> None:
|
|
1169
|
+
self.workspace_root = resolved
|
|
1170
|
+
self.selected_path = resolved
|
|
1171
|
+
self.left_pane.clear()
|
|
1172
|
+
self.right_pane.clear()
|
|
1173
|
+
self.is_split = False
|
|
1174
|
+
self.active_pane_id = "left"
|
|
1175
|
+
self.query_one("#right-editor-col").display = False
|
|
1176
|
+
self.left_pane.ensure_untitled()
|
|
1177
|
+
record_recent_folder(resolved, store_path=self._recent_store)
|
|
1178
|
+
self._refresh_recent_list()
|
|
1179
|
+
self._sync_workspace_ui(show_welcome=False)
|
|
1180
|
+
self._render_pane("left")
|
|
1181
|
+
self._refresh_tree()
|
|
1182
|
+
self._update_chrome()
|
|
1183
|
+
self.query_one("#editor", CodeTextArea).focus()
|
|
1184
|
+
self.notify(f"Opened {resolved.name}/")
|
|
1185
|
+
|
|
1186
|
+
self._guard_all_unsaved(_do_switch)
|
|
1187
|
+
|
|
1188
|
+
def _guard_unsaved(self, on_continue: Callable[[], None], *, buf: OpenBuffer | None = None) -> None:
|
|
1189
|
+
"""Prompt to save/discard before leaving a dirty buffer, then run on_continue."""
|
|
1190
|
+
self._sync_buffer_from_editor(self.active_pane_id)
|
|
1191
|
+
target_buf = buf if buf is not None else self._active_pane().active_buffer
|
|
1192
|
+
if target_buf is None or not target_buf.is_dirty:
|
|
1193
|
+
on_continue()
|
|
1194
|
+
return
|
|
1195
|
+
|
|
1196
|
+
def _after_choice(choice: str | None) -> None:
|
|
1197
|
+
if choice == "discard":
|
|
1198
|
+
target_buf.saved_content = target_buf.content
|
|
1199
|
+
on_continue()
|
|
1200
|
+
elif choice == "save":
|
|
1201
|
+
self._save_current(after_save=on_continue)
|
|
1202
|
+
|
|
1203
|
+
self.push_screen(UnsavedChangesModal(target_buf.title), _after_choice)
|
|
1204
|
+
|
|
1205
|
+
def _guard_all_unsaved(self, on_continue: Callable[[], None]) -> None:
|
|
1206
|
+
"""Prompt if any open tab across left or right pane has unsaved edits."""
|
|
1207
|
+
self._sync_buffer_from_editor("left")
|
|
1208
|
+
if self.is_split:
|
|
1209
|
+
self._sync_buffer_from_editor("right")
|
|
1210
|
+
dirty_bufs = [
|
|
1211
|
+
b for b in (*self.left_pane.tabs, *self.right_pane.tabs) if b.is_dirty
|
|
1212
|
+
]
|
|
1213
|
+
if not dirty_bufs:
|
|
1214
|
+
on_continue()
|
|
1215
|
+
return
|
|
1216
|
+
|
|
1217
|
+
label = dirty_bufs[0].title if len(dirty_bufs) == 1 else f"{len(dirty_bufs)} unsaved files"
|
|
1218
|
+
|
|
1219
|
+
def _after_choice(choice: str | None) -> None:
|
|
1220
|
+
if choice == "discard":
|
|
1221
|
+
for b in dirty_bufs:
|
|
1222
|
+
b.saved_content = b.content
|
|
1223
|
+
on_continue()
|
|
1224
|
+
elif choice == "save":
|
|
1225
|
+
# Save all named dirty buffers; prompt if active buffer is untitled
|
|
1226
|
+
for b in dirty_bufs:
|
|
1227
|
+
if b.path is not None:
|
|
1228
|
+
self._format_before_save(b, b.path)
|
|
1229
|
+
try:
|
|
1230
|
+
write_text_file(b.path, b.content)
|
|
1231
|
+
b.mark_saved()
|
|
1232
|
+
except WorkspaceError as exc:
|
|
1233
|
+
self.notify(str(exc), severity="error")
|
|
1234
|
+
return
|
|
1235
|
+
remaining_untitled = [b for b in dirty_bufs if b.is_dirty]
|
|
1236
|
+
if remaining_untitled:
|
|
1237
|
+
self._prompt_save_as(title="Save file", after_save=on_continue)
|
|
1238
|
+
else:
|
|
1239
|
+
self._update_chrome()
|
|
1240
|
+
on_continue()
|
|
1241
|
+
|
|
1242
|
+
self.push_screen(UnsavedChangesModal(label), _after_choice)
|
|
1243
|
+
|
|
1244
|
+
def _save_current(self, *, after_save: Callable[[], None] | None = None) -> None:
|
|
1245
|
+
self._sync_buffer_from_editor(self.active_pane_id)
|
|
1246
|
+
pane = self._active_pane()
|
|
1247
|
+
buf = pane.ensure_untitled()
|
|
1248
|
+
if buf.path is None:
|
|
1249
|
+
self._prompt_save_as(title="Save file", after_save=after_save)
|
|
1250
|
+
return
|
|
1251
|
+
|
|
1252
|
+
formatted = self._format_before_save(buf, buf.path)
|
|
1253
|
+
try:
|
|
1254
|
+
write_text_file(buf.path, buf.content)
|
|
1255
|
+
except WorkspaceError as exc:
|
|
1256
|
+
self.notify(str(exc), severity="error")
|
|
1257
|
+
return
|
|
1258
|
+
|
|
1259
|
+
buf.mark_saved()
|
|
1260
|
+
self._update_chrome()
|
|
1261
|
+
self.notify(f"Saved and formatted {buf.path.name}" if formatted else f"Saved {buf.path.name}")
|
|
1262
|
+
if after_save is not None:
|
|
1263
|
+
after_save()
|
|
1264
|
+
|
|
1265
|
+
# ---- Format on save ----
|
|
1266
|
+
|
|
1267
|
+
def _editor_showing(self, buf: OpenBuffer) -> CodeTextArea | None:
|
|
1268
|
+
for pane_id in ("left", "right"):
|
|
1269
|
+
if pane_id == "right" and not self.is_split:
|
|
1270
|
+
continue
|
|
1271
|
+
if self._pane_for_id(pane_id).active_buffer is buf:
|
|
1272
|
+
return self._editor_for_pane(pane_id)
|
|
1273
|
+
return None
|
|
1274
|
+
|
|
1275
|
+
def _replace_editor_text(self, editor: CodeTextArea, new_text: str) -> None:
|
|
1276
|
+
"""Swap in formatted text as one undoable edit, keeping the cursor on its code."""
|
|
1277
|
+
row, col = editor.cursor_location
|
|
1278
|
+
old_line = editor.document.get_line(row)
|
|
1279
|
+
old_indent = len(old_line) - len(old_line.lstrip())
|
|
1280
|
+
with editor.prevent(TextArea.Changed):
|
|
1281
|
+
editor.replace(new_text, (0, 0), editor.document.end)
|
|
1282
|
+
row = min(row, editor.document.line_count - 1)
|
|
1283
|
+
new_line = editor.document.get_line(row)
|
|
1284
|
+
new_indent = len(new_line) - len(new_line.lstrip())
|
|
1285
|
+
col = max(0, min(col + new_indent - old_indent, len(new_line)))
|
|
1286
|
+
editor.cursor_location = (row, col)
|
|
1287
|
+
|
|
1288
|
+
def _format_buffer(self, buf: OpenBuffer, path: Path) -> tuple[bool, str | None]:
|
|
1289
|
+
"""Format buf in place (and its editor). Returns (changed, error)."""
|
|
1290
|
+
result = format_code(buf.content, editor_language_for_path(path), filename=path.name)
|
|
1291
|
+
if result.error or not result.changed:
|
|
1292
|
+
return False, result.error
|
|
1293
|
+
editor = self._editor_showing(buf)
|
|
1294
|
+
if editor is not None:
|
|
1295
|
+
self._replace_editor_text(editor, result.text)
|
|
1296
|
+
buf.content = editor.text
|
|
1297
|
+
buf.cursor = editor.cursor_location
|
|
1298
|
+
else:
|
|
1299
|
+
buf.content = result.text
|
|
1300
|
+
return True, None
|
|
1301
|
+
|
|
1302
|
+
def _format_before_save(self, buf: OpenBuffer, path: Path) -> bool:
|
|
1303
|
+
"""Run before every save (Ctrl+S, F5/Shift+F5, save-as, save-all). Never blocks saving."""
|
|
1304
|
+
if not self.format_on_save:
|
|
1305
|
+
return False
|
|
1306
|
+
changed, error = self._format_buffer(buf, path)
|
|
1307
|
+
if error:
|
|
1308
|
+
self.notify(f"Saved without formatting. {error}", severity="warning", timeout=6)
|
|
1309
|
+
return changed
|
|
1310
|
+
|
|
1311
|
+
def _format_clean_before_run(self) -> None:
|
|
1312
|
+
"""Run keys format even an already-saved file; a change makes it dirty, so it gets saved."""
|
|
1313
|
+
buf = self._active_pane().active_buffer
|
|
1314
|
+
if not self.format_on_save or buf is None or buf.path is None or buf.is_dirty:
|
|
1315
|
+
return # dirty or untitled files are formatted by the save that follows
|
|
1316
|
+
_, error = self._format_buffer(buf, buf.path)
|
|
1317
|
+
if error:
|
|
1318
|
+
self.notify(f"Running without formatting. {error}", severity="warning", timeout=6)
|
|
1319
|
+
|
|
1320
|
+
def action_format_file(self) -> None:
|
|
1321
|
+
if not self._editor_ready():
|
|
1322
|
+
return
|
|
1323
|
+
self._sync_buffer_from_editor(self.active_pane_id)
|
|
1324
|
+
buf = self._active_pane().active_buffer
|
|
1325
|
+
if buf is None:
|
|
1326
|
+
return
|
|
1327
|
+
path = buf.path or Path("untitled.txt")
|
|
1328
|
+
changed, error = self._format_buffer(buf, path)
|
|
1329
|
+
if error:
|
|
1330
|
+
self.notify(f"Can't format: {error}", severity="warning", timeout=6)
|
|
1331
|
+
else:
|
|
1332
|
+
self.notify("Formatted" if changed else "Already tidy")
|
|
1333
|
+
self._update_chrome()
|
|
1334
|
+
|
|
1335
|
+
def action_toggle_format_on_save(self) -> None:
|
|
1336
|
+
self.format_on_save = not self.format_on_save
|
|
1337
|
+
self.notify(f"Format on save is {'on' if self.format_on_save else 'off'}")
|
|
1338
|
+
|
|
1339
|
+
def _prompt_save_as(
|
|
1340
|
+
self,
|
|
1341
|
+
*,
|
|
1342
|
+
title: str = "Save as",
|
|
1343
|
+
after_save: Callable[[], None] | None = None,
|
|
1344
|
+
) -> None:
|
|
1345
|
+
target_dir = self._target_dir_for_create()
|
|
1346
|
+
pane_id = self.active_pane_id
|
|
1347
|
+
pane = self._pane_for_id(pane_id)
|
|
1348
|
+
buf = pane.ensure_untitled()
|
|
1349
|
+
initial = buf.path.name if buf.path else ""
|
|
1350
|
+
|
|
1351
|
+
def _handle_name(raw_name: str | None) -> None:
|
|
1352
|
+
if raw_name is None:
|
|
1353
|
+
return
|
|
1354
|
+
cleaned = raw_name.strip()
|
|
1355
|
+
if not cleaned:
|
|
1356
|
+
self.notify("Filename cannot be empty.", severity="error")
|
|
1357
|
+
return
|
|
1358
|
+
dest = Path(cleaned)
|
|
1359
|
+
if not dest.is_absolute():
|
|
1360
|
+
dest = target_dir / dest
|
|
1361
|
+
dest = dest.resolve()
|
|
1362
|
+
|
|
1363
|
+
def _commit_save() -> None:
|
|
1364
|
+
self._sync_buffer_from_editor(pane_id)
|
|
1365
|
+
self._format_before_save(buf, dest)
|
|
1366
|
+
try:
|
|
1367
|
+
write_text_file(dest, buf.content)
|
|
1368
|
+
except WorkspaceError as exc:
|
|
1369
|
+
self.notify(str(exc), severity="error")
|
|
1370
|
+
return
|
|
1371
|
+
|
|
1372
|
+
buf.mark_saved(dest)
|
|
1373
|
+
self.selected_path = dest
|
|
1374
|
+
self._apply_editor_language(self._editor_for_pane(pane_id), dest)
|
|
1375
|
+
self._update_chrome()
|
|
1376
|
+
self._refresh_tree()
|
|
1377
|
+
self.notify(f"Saved {dest.name}")
|
|
1378
|
+
if after_save is not None:
|
|
1379
|
+
after_save()
|
|
1380
|
+
|
|
1381
|
+
if dest.exists() and (buf.path is None or dest != buf.path.resolve()):
|
|
1382
|
+
def _on_overwrite(confirmed: bool | None) -> None:
|
|
1383
|
+
if confirmed:
|
|
1384
|
+
_commit_save()
|
|
1385
|
+
|
|
1386
|
+
self.push_screen(
|
|
1387
|
+
ConfirmModal(
|
|
1388
|
+
title="Overwrite existing file?",
|
|
1389
|
+
message=f"'{dest.name}' already exists. Overwrite it?",
|
|
1390
|
+
confirm_label="Overwrite",
|
|
1391
|
+
),
|
|
1392
|
+
_on_overwrite,
|
|
1393
|
+
)
|
|
1394
|
+
else:
|
|
1395
|
+
_commit_save()
|
|
1396
|
+
|
|
1397
|
+
self.push_screen(
|
|
1398
|
+
TextInputModal(
|
|
1399
|
+
title=title,
|
|
1400
|
+
prompt=f"Filename inside {target_dir}:",
|
|
1401
|
+
initial=initial,
|
|
1402
|
+
placeholder="main.py",
|
|
1403
|
+
confirm_label="Save",
|
|
1404
|
+
),
|
|
1405
|
+
_handle_name,
|
|
1406
|
+
)
|
|
1407
|
+
|
|
1408
|
+
# ---- Events ----
|
|
1409
|
+
|
|
1410
|
+
def on_descendant_focus(self, event: events.DescendantFocus) -> None:
|
|
1411
|
+
wid = event.widget.id
|
|
1412
|
+
if wid == "editor":
|
|
1413
|
+
self.active_pane_id = "left"
|
|
1414
|
+
self._update_chrome()
|
|
1415
|
+
elif wid == "editor-right":
|
|
1416
|
+
self.active_pane_id = "right"
|
|
1417
|
+
self._update_chrome()
|
|
1418
|
+
elif wid != "completion-popup":
|
|
1419
|
+
self.hide_completions()
|
|
1420
|
+
|
|
1421
|
+
def on_key(self, event: events.Key) -> None:
|
|
1422
|
+
if not self._on_main_screen():
|
|
1423
|
+
return
|
|
1424
|
+
if event.character == "/" or event.key == "slash":
|
|
1425
|
+
focused = self.focused
|
|
1426
|
+
if (isinstance(focused, TextArea) and not focused.read_only) or isinstance(
|
|
1427
|
+
focused, Input
|
|
1428
|
+
):
|
|
1429
|
+
return
|
|
1430
|
+
event.prevent_default()
|
|
1431
|
+
event.stop()
|
|
1432
|
+
self.action_open_palette()
|
|
1433
|
+
|
|
1434
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
1435
|
+
if isinstance(event.button, TabCloseButton):
|
|
1436
|
+
self._close_tab_at(event.button.pane_id, event.button.tab_index)
|
|
1437
|
+
return
|
|
1438
|
+
if isinstance(event.button, TabButton):
|
|
1439
|
+
self._switch_to_tab(event.button.pane_id, event.button.tab_index)
|
|
1440
|
+
return
|
|
1441
|
+
|
|
1442
|
+
btn_id = event.button.id or ""
|
|
1443
|
+
if btn_id in ("sidebar-open-folder-btn", "home-open-folder-btn"):
|
|
1444
|
+
self.action_open_folder()
|
|
1445
|
+
elif btn_id == "sidebar-new-file-btn":
|
|
1446
|
+
self.action_new_file()
|
|
1447
|
+
elif btn_id == "sidebar-new-dir-btn":
|
|
1448
|
+
self.action_new_folder()
|
|
1449
|
+
elif btn_id in ("split-toggle-btn", "close-split-btn"):
|
|
1450
|
+
self.action_toggle_split()
|
|
1451
|
+
elif btn_id == "term-grow-btn":
|
|
1452
|
+
self.action_terminal_grow()
|
|
1453
|
+
elif btn_id == "term-shrink-btn":
|
|
1454
|
+
self.action_terminal_shrink()
|
|
1455
|
+
elif btn_id == "term-copy-btn":
|
|
1456
|
+
self.action_copy_output()
|
|
1457
|
+
elif btn_id in ("sidebar-hide-btn", "status-files-btn"):
|
|
1458
|
+
self.action_toggle_sidebar()
|
|
1459
|
+
elif btn_id in ("term-hide-btn", "status-output-btn"):
|
|
1460
|
+
self.action_toggle_terminal()
|
|
1461
|
+
elif btn_id == "term-clear-btn":
|
|
1462
|
+
self.action_clear_output()
|
|
1463
|
+
elif btn_id.startswith("tab-left-"):
|
|
1464
|
+
idx = int(btn_id.removeprefix("tab-left-"))
|
|
1465
|
+
self._switch_to_tab("left", idx)
|
|
1466
|
+
elif btn_id.startswith("tab-right-"):
|
|
1467
|
+
idx = int(btn_id.removeprefix("tab-right-"))
|
|
1468
|
+
self._switch_to_tab("right", idx)
|
|
1469
|
+
|
|
1470
|
+
def _switch_to_tab(self, pane_id: str, index: int) -> None:
|
|
1471
|
+
self.hide_completions()
|
|
1472
|
+
self._sync_buffer_from_editor(pane_id)
|
|
1473
|
+
pane = self._pane_for_id(pane_id)
|
|
1474
|
+
if pane.select_tab(index) is not None:
|
|
1475
|
+
self.active_pane_id = pane_id
|
|
1476
|
+
self._render_pane(pane_id)
|
|
1477
|
+
self._update_chrome()
|
|
1478
|
+
self._editor_for_pane(pane_id).focus()
|
|
1479
|
+
|
|
1480
|
+
def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
|
|
1481
|
+
if event.option_list.id == "recent-list" and event.option_id is not None:
|
|
1482
|
+
idx = int(event.option_id)
|
|
1483
|
+
if 0 <= idx < len(self._recent_folders):
|
|
1484
|
+
self._open_workspace_folder(self._recent_folders[idx])
|
|
1485
|
+
elif event.option_list.id == "completion-popup":
|
|
1486
|
+
self.accept_completion()
|
|
1487
|
+
|
|
1488
|
+
def on_text_area_changed(self, event: TextArea.Changed) -> None:
|
|
1489
|
+
if event.text_area.id not in ("editor", "editor-right") or self._suppress_dirty:
|
|
1490
|
+
return
|
|
1491
|
+
pane_id = "right" if event.text_area.id == "editor-right" else "left"
|
|
1492
|
+
pane = self._pane_for_id(pane_id)
|
|
1493
|
+
buf = pane.ensure_untitled()
|
|
1494
|
+
buf.content = event.text_area.text
|
|
1495
|
+
buf.cursor = event.text_area.cursor_location
|
|
1496
|
+
self._update_chrome()
|
|
1497
|
+
if isinstance(event.text_area, CodeTextArea):
|
|
1498
|
+
if self.focused is not event.text_area:
|
|
1499
|
+
self.hide_completions()
|
|
1500
|
+
elif self._just_accepted_completion:
|
|
1501
|
+
self._just_accepted_completion = False
|
|
1502
|
+
else:
|
|
1503
|
+
self._update_completions(event.text_area)
|
|
1504
|
+
|
|
1505
|
+
def on_text_area_selection_changed(self, event: TextArea.SelectionChanged) -> None:
|
|
1506
|
+
if event.text_area.id in ("editor", "editor-right"):
|
|
1507
|
+
self._update_chrome()
|
|
1508
|
+
|
|
1509
|
+
def on_tree_node_highlighted(self, event: DirectoryTree.NodeHighlighted) -> None:
|
|
1510
|
+
data = getattr(event.node, "data", None)
|
|
1511
|
+
path = getattr(data, "path", None)
|
|
1512
|
+
if isinstance(path, Path):
|
|
1513
|
+
self.selected_path = path
|
|
1514
|
+
|
|
1515
|
+
def on_directory_tree_directory_selected(
|
|
1516
|
+
self, event: DirectoryTree.DirectorySelected
|
|
1517
|
+
) -> None:
|
|
1518
|
+
self.selected_path = event.path
|
|
1519
|
+
|
|
1520
|
+
def on_directory_tree_file_selected(self, event: DirectoryTree.FileSelected) -> None:
|
|
1521
|
+
self.selected_path = event.path
|
|
1522
|
+
self.load_file(event.path)
|
|
1523
|
+
|
|
1524
|
+
async def on_input_submitted(self, event: Input.Submitted) -> None:
|
|
1525
|
+
if event.input.id != "stdin-input":
|
|
1526
|
+
return
|
|
1527
|
+
if not self.runner.is_running:
|
|
1528
|
+
return
|
|
1529
|
+
line = event.value
|
|
1530
|
+
event.input.value = ""
|
|
1531
|
+
self.append_output(f"> {line}\n")
|
|
1532
|
+
await self.runner.send_input(line)
|
|
1533
|
+
|
|
1534
|
+
# ---- Actions ----
|
|
1535
|
+
|
|
1536
|
+
def action_open_palette(self) -> None:
|
|
1537
|
+
if not self._on_main_screen():
|
|
1538
|
+
return
|
|
1539
|
+
self.hide_completions()
|
|
1540
|
+
|
|
1541
|
+
def _dispatch(action_name: str | None) -> None:
|
|
1542
|
+
if not action_name:
|
|
1543
|
+
return
|
|
1544
|
+
method = getattr(self, f"action_{action_name}", None)
|
|
1545
|
+
if callable(method):
|
|
1546
|
+
method()
|
|
1547
|
+
|
|
1548
|
+
self.push_screen(CommandPaletteModal("/"), _dispatch)
|
|
1549
|
+
|
|
1550
|
+
def action_save_file(self) -> None:
|
|
1551
|
+
if not self._on_main_screen():
|
|
1552
|
+
return
|
|
1553
|
+
if self.query_one("#welcome-view").display:
|
|
1554
|
+
self.notify("Open a folder or create a file first.")
|
|
1555
|
+
return
|
|
1556
|
+
self._save_current()
|
|
1557
|
+
|
|
1558
|
+
def action_save_file_as(self) -> None:
|
|
1559
|
+
if not self._on_main_screen():
|
|
1560
|
+
return
|
|
1561
|
+
if self.query_one("#welcome-view").display:
|
|
1562
|
+
self.notify("Open a folder or create a file first.")
|
|
1563
|
+
return
|
|
1564
|
+
self._prompt_save_as()
|
|
1565
|
+
|
|
1566
|
+
def action_run_file(self) -> None:
|
|
1567
|
+
if not self._on_main_screen():
|
|
1568
|
+
return
|
|
1569
|
+
if self.query_one("#welcome-view").display:
|
|
1570
|
+
self.notify("Open a file or create one (Ctrl+N) before running.")
|
|
1571
|
+
return
|
|
1572
|
+
if self.runner.is_running:
|
|
1573
|
+
self.notify("A program is already running. Press F7 (/stop) to stop it.", severity="warning")
|
|
1574
|
+
return
|
|
1575
|
+
self._sync_buffer_from_editor(self.active_pane_id)
|
|
1576
|
+
self._format_clean_before_run()
|
|
1577
|
+
if self.active_file is None or self.is_dirty:
|
|
1578
|
+
self._save_current(after_save=self._start_run_worker)
|
|
1579
|
+
else:
|
|
1580
|
+
self._start_run_worker()
|
|
1581
|
+
|
|
1582
|
+
@work(exclusive=True)
|
|
1583
|
+
async def _start_run_worker(self) -> None:
|
|
1584
|
+
if self.active_file is None:
|
|
1585
|
+
return
|
|
1586
|
+
source = self.active_file
|
|
1587
|
+
ws_root = self.workspace_root or source.parent
|
|
1588
|
+
self.set_output_visible(True) # a run always brings Output back
|
|
1589
|
+
stdin_input = self.query_one("#stdin-input", Input)
|
|
1590
|
+
|
|
1591
|
+
try:
|
|
1592
|
+
plan_preview = build_run_plan(source, ws_root, source.parent)
|
|
1593
|
+
except RunnerError as exc:
|
|
1594
|
+
self.append_output(f"[Error] {exc}\n")
|
|
1595
|
+
self._set_run_state("fail", "could not start")
|
|
1596
|
+
self.notify(str(exc), severity="error")
|
|
1597
|
+
return
|
|
1598
|
+
|
|
1599
|
+
self.append_output(f"$ {plan_preview.display_cmd}\n")
|
|
1600
|
+
self._set_run_state("running", f"{source.name} F7 to stop")
|
|
1601
|
+
stdin_input.disabled = False
|
|
1602
|
+
stdin_input.display = True
|
|
1603
|
+
|
|
1604
|
+
try:
|
|
1605
|
+
result = await self.runner.run(source, ws_root, self.append_output)
|
|
1606
|
+
except RunnerError as exc:
|
|
1607
|
+
self.append_output(f"[Error] {exc}\n")
|
|
1608
|
+
self._set_run_state("fail", "could not start")
|
|
1609
|
+
self.notify(str(exc), severity="error")
|
|
1610
|
+
else:
|
|
1611
|
+
secs = f"{result.duration_seconds:.2f}s"
|
|
1612
|
+
if result.cancelled:
|
|
1613
|
+
self.append_output(f"[Stopped after {secs}]\n")
|
|
1614
|
+
self._set_run_state("stopped", f"{source.name} after {secs}")
|
|
1615
|
+
elif result.compile_failed:
|
|
1616
|
+
self.append_output(f"[Compile failed (exit {result.exit_code}) in {secs}]\n")
|
|
1617
|
+
self._set_run_state("fail", f"compile failed {source.name}")
|
|
1618
|
+
else:
|
|
1619
|
+
self.append_output(f"[Exited {result.exit_code} in {secs}]\n")
|
|
1620
|
+
state = "ok" if result.exit_code == 0 else "fail"
|
|
1621
|
+
self._set_run_state(state, f"exit {result.exit_code} {source.name} in {secs}")
|
|
1622
|
+
finally:
|
|
1623
|
+
stdin_input.value = ""
|
|
1624
|
+
stdin_input.disabled = True
|
|
1625
|
+
stdin_input.display = False
|
|
1626
|
+
if self._on_main_screen() and self.query_one("#editor").display:
|
|
1627
|
+
self._active_editor().focus()
|
|
1628
|
+
|
|
1629
|
+
# ---- Real terminal: hand the whole screen to a program or the shell ----
|
|
1630
|
+
|
|
1631
|
+
@staticmethod
|
|
1632
|
+
def _tty_write(text: str) -> None:
|
|
1633
|
+
"""Write straight to the real terminal (Textual captures sys.stdout)."""
|
|
1634
|
+
out = sys.__stdout__
|
|
1635
|
+
if out is not None:
|
|
1636
|
+
out.write(text)
|
|
1637
|
+
out.flush()
|
|
1638
|
+
|
|
1639
|
+
@staticmethod
|
|
1640
|
+
def _tty_wait_for_enter() -> None:
|
|
1641
|
+
stdin = sys.__stdin__
|
|
1642
|
+
if stdin is None:
|
|
1643
|
+
return
|
|
1644
|
+
try:
|
|
1645
|
+
stdin.readline()
|
|
1646
|
+
except (KeyboardInterrupt, EOFError, OSError):
|
|
1647
|
+
pass
|
|
1648
|
+
|
|
1649
|
+
def _suspended(self, body: Callable[[], None]) -> bool:
|
|
1650
|
+
"""Run body with the real terminal; False if this terminal can't do that."""
|
|
1651
|
+
try:
|
|
1652
|
+
with self.suspend():
|
|
1653
|
+
body()
|
|
1654
|
+
except SuspendNotSupported:
|
|
1655
|
+
self.notify("This terminal can't hand over the screen.", severity="warning")
|
|
1656
|
+
return False
|
|
1657
|
+
return True
|
|
1658
|
+
|
|
1659
|
+
def action_open_shell(self) -> None:
|
|
1660
|
+
"""Ctrl+T: open the user's own shell; `exit` comes back to TermCode."""
|
|
1661
|
+
if not self._on_main_screen():
|
|
1662
|
+
return
|
|
1663
|
+
if self.runner.is_running:
|
|
1664
|
+
self.notify("Stop the running program first (F7).", severity="warning")
|
|
1665
|
+
return
|
|
1666
|
+
self.hide_completions()
|
|
1667
|
+
cwd = self.workspace_root or Path.home()
|
|
1668
|
+
cmd = user_shell_command()
|
|
1669
|
+
|
|
1670
|
+
def _shell() -> None:
|
|
1671
|
+
self._tty_write(
|
|
1672
|
+
f"\x1b[2J\x1b[H\x1b[2mTermCode is paused. You're in {cwd}. "
|
|
1673
|
+
"Type exit to come back.\x1b[0m\n"
|
|
1674
|
+
)
|
|
1675
|
+
try:
|
|
1676
|
+
wait_ignoring_ctrl_c(subprocess.Popen(cmd, cwd=cwd))
|
|
1677
|
+
except OSError as exc:
|
|
1678
|
+
self._tty_write(f"Could not start {cmd[0]}: {exc}\nPress Enter to return. ")
|
|
1679
|
+
self._tty_wait_for_enter()
|
|
1680
|
+
|
|
1681
|
+
if self._suspended(_shell):
|
|
1682
|
+
self._refresh_tree() # the shell may have created or deleted files
|
|
1683
|
+
self._reload_clean_buffers()
|
|
1684
|
+
|
|
1685
|
+
def action_run_in_terminal(self) -> None:
|
|
1686
|
+
"""Shift+F5: save, then run the file with the full terminal (Code::Blocks style)."""
|
|
1687
|
+
if not self._editor_ready():
|
|
1688
|
+
return
|
|
1689
|
+
if self.runner.is_running:
|
|
1690
|
+
self.notify("A program is already running. Press F7 to stop it.", severity="warning")
|
|
1691
|
+
return
|
|
1692
|
+
self._sync_buffer_from_editor(self.active_pane_id)
|
|
1693
|
+
self._format_clean_before_run()
|
|
1694
|
+
if self.active_file is None or self.is_dirty:
|
|
1695
|
+
self._save_current(after_save=self._run_in_terminal_now)
|
|
1696
|
+
else:
|
|
1697
|
+
self._run_in_terminal_now()
|
|
1698
|
+
|
|
1699
|
+
def _run_in_terminal_now(self) -> None:
|
|
1700
|
+
source = self.active_file
|
|
1701
|
+
if source is None:
|
|
1702
|
+
return
|
|
1703
|
+
ws_root = self.workspace_root or source.parent
|
|
1704
|
+
outcome: dict[str, object] = {}
|
|
1705
|
+
|
|
1706
|
+
def _run() -> None:
|
|
1707
|
+
self._tty_write(f"\x1b[2J\x1b[H\x1b[2m$ running {source.name}\x1b[0m\n\n")
|
|
1708
|
+
try:
|
|
1709
|
+
outcome["result"] = run_in_foreground(source, ws_root)
|
|
1710
|
+
except RunnerError as exc:
|
|
1711
|
+
outcome["error"] = str(exc)
|
|
1712
|
+
self._tty_write(f"\x1b[31m{exc}\x1b[0m\n")
|
|
1713
|
+
result = outcome.get("result")
|
|
1714
|
+
if isinstance(result, RunResult):
|
|
1715
|
+
color = "32" if result.exit_code == 0 and not result.cancelled else "31"
|
|
1716
|
+
status = (
|
|
1717
|
+
"stopped" if result.cancelled
|
|
1718
|
+
else "failed to compile" if result.compile_failed
|
|
1719
|
+
else f"exited {result.exit_code}"
|
|
1720
|
+
)
|
|
1721
|
+
summary = f"{source.name} {status} in {result.duration_seconds:.2f}s"
|
|
1722
|
+
else:
|
|
1723
|
+
color, summary = "31", f"{source.name} could not start"
|
|
1724
|
+
self._tty_write(
|
|
1725
|
+
f"\n\x1b[{color}m── {summary} ──\x1b[0m\x1b[2m press Enter to return \x1b[0m"
|
|
1726
|
+
)
|
|
1727
|
+
self._tty_wait_for_enter()
|
|
1728
|
+
|
|
1729
|
+
if not self._suspended(_run):
|
|
1730
|
+
return
|
|
1731
|
+
result = outcome.get("result")
|
|
1732
|
+
if isinstance(result, RunResult):
|
|
1733
|
+
secs = f"{result.duration_seconds:.2f}s"
|
|
1734
|
+
if result.cancelled:
|
|
1735
|
+
self._set_run_state("stopped", f"{source.name} after {secs} ran in terminal")
|
|
1736
|
+
elif result.compile_failed:
|
|
1737
|
+
self._set_run_state("fail", f"compile failed {source.name} ran in terminal")
|
|
1738
|
+
else:
|
|
1739
|
+
state = "ok" if result.exit_code == 0 else "fail"
|
|
1740
|
+
self._set_run_state(
|
|
1741
|
+
state, f"exit {result.exit_code} {source.name} in {secs} ran in terminal"
|
|
1742
|
+
)
|
|
1743
|
+
self.append_output(f"[Ran {source.name} in terminal: exit {result.exit_code} in {secs}]\n")
|
|
1744
|
+
elif "error" in outcome:
|
|
1745
|
+
self._set_run_state("fail", "could not start")
|
|
1746
|
+
self.notify(str(outcome["error"]), severity="error")
|
|
1747
|
+
self._active_editor().focus()
|
|
1748
|
+
|
|
1749
|
+
def _reload_clean_buffers(self) -> None:
|
|
1750
|
+
"""After the shell, pick up on-disk edits to files that have no unsaved changes."""
|
|
1751
|
+
for pane_id in ("left", "right"):
|
|
1752
|
+
if pane_id == "right" and not self.is_split:
|
|
1753
|
+
continue
|
|
1754
|
+
pane = self._pane_for_id(pane_id)
|
|
1755
|
+
self._sync_buffer_from_editor(pane_id)
|
|
1756
|
+
changed = False
|
|
1757
|
+
for buf in pane.tabs:
|
|
1758
|
+
if buf.path is None or buf.is_dirty or not buf.path.is_file():
|
|
1759
|
+
continue
|
|
1760
|
+
try:
|
|
1761
|
+
disk = read_text_file(buf.path)
|
|
1762
|
+
except WorkspaceError:
|
|
1763
|
+
continue
|
|
1764
|
+
if disk != buf.content:
|
|
1765
|
+
buf.content = disk
|
|
1766
|
+
buf.saved_content = disk
|
|
1767
|
+
changed = True
|
|
1768
|
+
if changed:
|
|
1769
|
+
self._render_pane(pane_id)
|
|
1770
|
+
self._update_chrome()
|
|
1771
|
+
|
|
1772
|
+
def action_stop_run(self) -> None:
|
|
1773
|
+
if not self._on_main_screen():
|
|
1774
|
+
return
|
|
1775
|
+
if not self.runner.is_running:
|
|
1776
|
+
self.notify("No program is currently running.")
|
|
1777
|
+
return
|
|
1778
|
+
self._stop_run_worker()
|
|
1779
|
+
|
|
1780
|
+
@work
|
|
1781
|
+
async def _stop_run_worker(self) -> None:
|
|
1782
|
+
await self.runner.stop()
|
|
1783
|
+
|
|
1784
|
+
def action_new_file(self) -> None:
|
|
1785
|
+
if not self._on_main_screen():
|
|
1786
|
+
return
|
|
1787
|
+
self.hide_completions()
|
|
1788
|
+
if self.workspace_root is None:
|
|
1789
|
+
self._sync_workspace_ui(show_welcome=False)
|
|
1790
|
+
self.left_pane.ensure_untitled()
|
|
1791
|
+
self._render_pane("left")
|
|
1792
|
+
self._update_chrome()
|
|
1793
|
+
self.query_one("#editor", CodeTextArea).focus()
|
|
1794
|
+
return
|
|
1795
|
+
|
|
1796
|
+
base_dir = self._target_dir_for_create()
|
|
1797
|
+
|
|
1798
|
+
def _create(raw_name: str | None) -> None:
|
|
1799
|
+
if raw_name is None:
|
|
1800
|
+
return
|
|
1801
|
+
try:
|
|
1802
|
+
created = create_file(base_dir, raw_name)
|
|
1803
|
+
except WorkspaceError as exc:
|
|
1804
|
+
self.notify(str(exc), severity="error")
|
|
1805
|
+
return
|
|
1806
|
+
self._refresh_tree()
|
|
1807
|
+
self.load_file(created)
|
|
1808
|
+
|
|
1809
|
+
self.push_screen(
|
|
1810
|
+
TextInputModal(
|
|
1811
|
+
title="New File",
|
|
1812
|
+
prompt=f"Create file inside {base_dir}:",
|
|
1813
|
+
placeholder="e.g. main.py or utils/helper.cpp",
|
|
1814
|
+
confirm_label="Create",
|
|
1815
|
+
),
|
|
1816
|
+
_create,
|
|
1817
|
+
)
|
|
1818
|
+
|
|
1819
|
+
def action_new_folder(self) -> None:
|
|
1820
|
+
if not self._on_main_screen():
|
|
1821
|
+
return
|
|
1822
|
+
if self.workspace_root is None:
|
|
1823
|
+
self.notify("Open a folder first (Ctrl+O) before creating a subfolder.", severity="warning")
|
|
1824
|
+
return
|
|
1825
|
+
base_dir = self._target_dir_for_create()
|
|
1826
|
+
|
|
1827
|
+
def _create(raw_name: str | None) -> None:
|
|
1828
|
+
if raw_name is None:
|
|
1829
|
+
return
|
|
1830
|
+
try:
|
|
1831
|
+
created = create_folder(base_dir, raw_name)
|
|
1832
|
+
except WorkspaceError as exc:
|
|
1833
|
+
self.notify(str(exc), severity="error")
|
|
1834
|
+
return
|
|
1835
|
+
self.selected_path = created
|
|
1836
|
+
self._refresh_tree()
|
|
1837
|
+
self.notify(f"Created folder {created.name}/")
|
|
1838
|
+
|
|
1839
|
+
self.push_screen(
|
|
1840
|
+
TextInputModal(
|
|
1841
|
+
title="New Folder",
|
|
1842
|
+
prompt=f"Create folder inside {base_dir}:",
|
|
1843
|
+
placeholder="e.g. src or algorithms/dp",
|
|
1844
|
+
confirm_label="Create",
|
|
1845
|
+
),
|
|
1846
|
+
_create,
|
|
1847
|
+
)
|
|
1848
|
+
|
|
1849
|
+
def action_open_file(self) -> None:
|
|
1850
|
+
if not self._on_main_screen():
|
|
1851
|
+
return
|
|
1852
|
+
if self.workspace_root is None:
|
|
1853
|
+
self.notify("Open a folder first (Ctrl+O) to pick files.", severity="warning")
|
|
1854
|
+
return
|
|
1855
|
+
files = list_workspace_files(self.workspace_root)
|
|
1856
|
+
if not files:
|
|
1857
|
+
self.notify("No files in this folder yet. Press Ctrl+N to create one.")
|
|
1858
|
+
return
|
|
1859
|
+
|
|
1860
|
+
def _picked(path: Path | None) -> None:
|
|
1861
|
+
if path is not None:
|
|
1862
|
+
self.load_file(path)
|
|
1863
|
+
|
|
1864
|
+
self.push_screen(FilePickerModal(self.workspace_root, files), _picked)
|
|
1865
|
+
|
|
1866
|
+
def action_open_folder(self) -> None:
|
|
1867
|
+
if not self._on_main_screen():
|
|
1868
|
+
return
|
|
1869
|
+
start = self.workspace_root or Path.home()
|
|
1870
|
+
|
|
1871
|
+
def _picked(folder: Path | None) -> None:
|
|
1872
|
+
if folder is not None:
|
|
1873
|
+
self._open_workspace_folder(folder)
|
|
1874
|
+
|
|
1875
|
+
self.push_screen(FolderPickerModal(start_dir=start), _picked)
|
|
1876
|
+
|
|
1877
|
+
def action_rename_item(self) -> None:
|
|
1878
|
+
if not self._on_main_screen():
|
|
1879
|
+
return
|
|
1880
|
+
target = self._target_path_for_edit()
|
|
1881
|
+
if target is None:
|
|
1882
|
+
self.notify("Select a file or folder to rename first.", severity="warning")
|
|
1883
|
+
return
|
|
1884
|
+
|
|
1885
|
+
def _do_rename(new_name: str | None) -> None:
|
|
1886
|
+
if new_name is None:
|
|
1887
|
+
return
|
|
1888
|
+
old_path = target.resolve()
|
|
1889
|
+
try:
|
|
1890
|
+
renamed = rename_path(old_path, new_name).resolve()
|
|
1891
|
+
except WorkspaceError as exc:
|
|
1892
|
+
self.notify(str(exc), severity="error")
|
|
1893
|
+
return
|
|
1894
|
+
|
|
1895
|
+
self._sync_buffer_from_editor("left")
|
|
1896
|
+
if self.is_split:
|
|
1897
|
+
self._sync_buffer_from_editor("right")
|
|
1898
|
+
self.left_pane.handle_rename(old_path, renamed)
|
|
1899
|
+
self.right_pane.handle_rename(old_path, renamed)
|
|
1900
|
+
|
|
1901
|
+
if self.left_pane.active_buffer is not None:
|
|
1902
|
+
self._apply_editor_language(
|
|
1903
|
+
self._editor_for_pane("left"), self.left_pane.active_buffer.path
|
|
1904
|
+
)
|
|
1905
|
+
if self.is_split and self.right_pane.active_buffer is not None:
|
|
1906
|
+
self._apply_editor_language(
|
|
1907
|
+
self._editor_for_pane("right"), self.right_pane.active_buffer.path
|
|
1908
|
+
)
|
|
1909
|
+
|
|
1910
|
+
self.selected_path = renamed
|
|
1911
|
+
self._refresh_tree()
|
|
1912
|
+
self._update_chrome()
|
|
1913
|
+
self.notify(f"Renamed to {renamed.name}")
|
|
1914
|
+
|
|
1915
|
+
self.push_screen(
|
|
1916
|
+
TextInputModal(
|
|
1917
|
+
title=f"Rename '{target.name}'",
|
|
1918
|
+
prompt="New name:",
|
|
1919
|
+
initial=target.name,
|
|
1920
|
+
confirm_label="Rename",
|
|
1921
|
+
),
|
|
1922
|
+
_do_rename,
|
|
1923
|
+
)
|
|
1924
|
+
|
|
1925
|
+
def action_delete_item(self) -> None:
|
|
1926
|
+
if not self._on_main_screen():
|
|
1927
|
+
return
|
|
1928
|
+
target = self._target_path_for_edit()
|
|
1929
|
+
if target is None:
|
|
1930
|
+
self.notify("Select a file or folder to delete first.", severity="warning")
|
|
1931
|
+
return
|
|
1932
|
+
|
|
1933
|
+
kind = "folder and all its contents" if target.is_dir() else "file"
|
|
1934
|
+
|
|
1935
|
+
def _do_delete(confirmed: bool | None) -> None:
|
|
1936
|
+
if not confirmed:
|
|
1937
|
+
return
|
|
1938
|
+
old_path = target.resolve()
|
|
1939
|
+
try:
|
|
1940
|
+
delete_path(old_path)
|
|
1941
|
+
except WorkspaceError as exc:
|
|
1942
|
+
self.notify(str(exc), severity="error")
|
|
1943
|
+
return
|
|
1944
|
+
|
|
1945
|
+
self._sync_buffer_from_editor("left")
|
|
1946
|
+
if self.is_split:
|
|
1947
|
+
self._sync_buffer_from_editor("right")
|
|
1948
|
+
self.left_pane.handle_delete(old_path)
|
|
1949
|
+
self.right_pane.handle_delete(old_path)
|
|
1950
|
+
|
|
1951
|
+
if self.left_pane.active_buffer is not None:
|
|
1952
|
+
self._apply_editor_language(
|
|
1953
|
+
self._editor_for_pane("left"), self.left_pane.active_buffer.path
|
|
1954
|
+
)
|
|
1955
|
+
if self.is_split and self.right_pane.active_buffer is not None:
|
|
1956
|
+
self._apply_editor_language(
|
|
1957
|
+
self._editor_for_pane("right"), self.right_pane.active_buffer.path
|
|
1958
|
+
)
|
|
1959
|
+
|
|
1960
|
+
if self.selected_path is not None and (
|
|
1961
|
+
self.selected_path.resolve() == old_path
|
|
1962
|
+
or _is_within(self.selected_path, old_path)
|
|
1963
|
+
):
|
|
1964
|
+
self.selected_path = self.workspace_root
|
|
1965
|
+
|
|
1966
|
+
self._refresh_tree()
|
|
1967
|
+
self._update_chrome()
|
|
1968
|
+
self.notify(f"Deleted {old_path.name}")
|
|
1969
|
+
|
|
1970
|
+
self.push_screen(
|
|
1971
|
+
ConfirmModal(
|
|
1972
|
+
title="Delete permanently?",
|
|
1973
|
+
message=f"Permanently delete {kind} '{target.name}'?",
|
|
1974
|
+
confirm_label="Delete",
|
|
1975
|
+
),
|
|
1976
|
+
_do_delete,
|
|
1977
|
+
)
|
|
1978
|
+
|
|
1979
|
+
def action_next_tab(self) -> None:
|
|
1980
|
+
if not self._on_main_screen() or self.query_one("#welcome-view").display:
|
|
1981
|
+
return
|
|
1982
|
+
pane_id = self.active_pane_id
|
|
1983
|
+
pane = self._pane_for_id(pane_id)
|
|
1984
|
+
if len(pane.tabs) < 2:
|
|
1985
|
+
return
|
|
1986
|
+
self.hide_completions()
|
|
1987
|
+
self._sync_buffer_from_editor(pane_id)
|
|
1988
|
+
pane.next_tab()
|
|
1989
|
+
self._render_pane(pane_id)
|
|
1990
|
+
self._update_chrome()
|
|
1991
|
+
self._editor_for_pane(pane_id).focus()
|
|
1992
|
+
|
|
1993
|
+
def _close_tab_at(self, pane_id: str, index: int) -> None:
|
|
1994
|
+
"""Close any tab from its ×; unsaved tabs are shown first, then asked about."""
|
|
1995
|
+
if not self._on_main_screen():
|
|
1996
|
+
return
|
|
1997
|
+
self.hide_completions()
|
|
1998
|
+
pane = self._pane_for_id(pane_id)
|
|
1999
|
+
self._sync_buffer_from_editor(pane_id)
|
|
2000
|
+
if not (0 <= index < len(pane.tabs)):
|
|
2001
|
+
return
|
|
2002
|
+
if index != pane.active_index and not pane.tabs[index].is_dirty:
|
|
2003
|
+
pane.close_tab(index) # background tab, nothing to lose
|
|
2004
|
+
self._rebuild_tab_strip(pane_id)
|
|
2005
|
+
self._update_chrome()
|
|
2006
|
+
return
|
|
2007
|
+
if index != pane.active_index:
|
|
2008
|
+
self._switch_to_tab(pane_id, index)
|
|
2009
|
+
self.active_pane_id = pane_id
|
|
2010
|
+
self.action_close_tab()
|
|
2011
|
+
|
|
2012
|
+
def action_close_tab(self) -> None:
|
|
2013
|
+
if not self._on_main_screen() or self.query_one("#welcome-view").display:
|
|
2014
|
+
return
|
|
2015
|
+
pane_id = self.active_pane_id
|
|
2016
|
+
pane = self._pane_for_id(pane_id)
|
|
2017
|
+
buf = pane.active_buffer
|
|
2018
|
+
if buf is None:
|
|
2019
|
+
return
|
|
2020
|
+
|
|
2021
|
+
def _do_close() -> None:
|
|
2022
|
+
pane.close_tab(pane.active_index)
|
|
2023
|
+
if pane_id == "right" and not pane.tabs:
|
|
2024
|
+
self.is_split = False
|
|
2025
|
+
self.query_one("#right-editor-col").display = False
|
|
2026
|
+
self.active_pane_id = "left"
|
|
2027
|
+
self._update_chrome()
|
|
2028
|
+
self._editor_for_pane("left").focus()
|
|
2029
|
+
return
|
|
2030
|
+
if not pane.tabs:
|
|
2031
|
+
pane.ensure_untitled()
|
|
2032
|
+
self._render_pane(pane_id)
|
|
2033
|
+
self._update_chrome()
|
|
2034
|
+
self._editor_for_pane(pane_id).focus()
|
|
2035
|
+
|
|
2036
|
+
self._guard_unsaved(_do_close, buf=buf)
|
|
2037
|
+
|
|
2038
|
+
def action_toggle_split(self) -> None:
|
|
2039
|
+
if not self._on_main_screen() or self.query_one("#welcome-view").display:
|
|
2040
|
+
return
|
|
2041
|
+
self.hide_completions()
|
|
2042
|
+
right_col = self.query_one("#right-editor-col")
|
|
2043
|
+
if not self.is_split:
|
|
2044
|
+
self._sync_buffer_from_editor("left")
|
|
2045
|
+
self.is_split = True
|
|
2046
|
+
right_col.display = True
|
|
2047
|
+
if not self.right_pane.tabs:
|
|
2048
|
+
# Open a fresh untitled tab (or copy active file reference if 1 tab)
|
|
2049
|
+
if len(self.left_pane.tabs) >= 2:
|
|
2050
|
+
# Move the inactive neighbor tab to the right pane for instant side-by-side
|
|
2051
|
+
other_idx = (self.left_pane.active_index + 1) % len(self.left_pane.tabs)
|
|
2052
|
+
moved = self.left_pane.close_tab(other_idx)
|
|
2053
|
+
if moved is not None:
|
|
2054
|
+
self.right_pane.tabs.append(moved)
|
|
2055
|
+
self.right_pane.active_index = 0
|
|
2056
|
+
else:
|
|
2057
|
+
self.right_pane.ensure_untitled()
|
|
2058
|
+
self._render_pane("left")
|
|
2059
|
+
self._render_pane("right")
|
|
2060
|
+
self.active_pane_id = "right"
|
|
2061
|
+
self._update_chrome()
|
|
2062
|
+
self._editor_for_pane("right").focus()
|
|
2063
|
+
else:
|
|
2064
|
+
self._sync_buffer_from_editor("left")
|
|
2065
|
+
self._sync_buffer_from_editor("right")
|
|
2066
|
+
self.left_pane.merge_from(self.right_pane)
|
|
2067
|
+
self.is_split = False
|
|
2068
|
+
right_col.display = False
|
|
2069
|
+
self.active_pane_id = "left"
|
|
2070
|
+
self._render_pane("left")
|
|
2071
|
+
self._update_chrome()
|
|
2072
|
+
self._editor_for_pane("left").focus()
|
|
2073
|
+
|
|
2074
|
+
def _editor_ready(self) -> bool:
|
|
2075
|
+
return self._on_main_screen() and not self.query_one("#welcome-view").display
|
|
2076
|
+
|
|
2077
|
+
def action_find(self) -> None:
|
|
2078
|
+
if not self._editor_ready():
|
|
2079
|
+
return
|
|
2080
|
+
self.hide_completions()
|
|
2081
|
+
self.query_one("#find-bar", FindBar).open(replace=False)
|
|
2082
|
+
|
|
2083
|
+
def action_replace(self) -> None:
|
|
2084
|
+
if not self._editor_ready():
|
|
2085
|
+
return
|
|
2086
|
+
self.hide_completions()
|
|
2087
|
+
self.query_one("#find-bar", FindBar).open(replace=True)
|
|
2088
|
+
|
|
2089
|
+
def action_goto_line(self) -> None:
|
|
2090
|
+
if not self._editor_ready():
|
|
2091
|
+
return
|
|
2092
|
+
self.hide_completions()
|
|
2093
|
+
editor = self._active_editor()
|
|
2094
|
+
line_count = editor.document.line_count
|
|
2095
|
+
|
|
2096
|
+
def _go(raw: str | None) -> None:
|
|
2097
|
+
if raw is None:
|
|
2098
|
+
return
|
|
2099
|
+
target = parse_goto(raw)
|
|
2100
|
+
if target is None:
|
|
2101
|
+
self.notify("Type a line number, like 42 or 42:7.", severity="warning")
|
|
2102
|
+
return
|
|
2103
|
+
row = min(target[0], line_count - 1)
|
|
2104
|
+
col = min(target[1], len(editor.document.get_line(row)))
|
|
2105
|
+
editor.cursor_location = (row, col)
|
|
2106
|
+
editor.scroll_cursor_visible(center=True)
|
|
2107
|
+
editor.focus()
|
|
2108
|
+
|
|
2109
|
+
row = editor.cursor_location[0] + 1
|
|
2110
|
+
self.push_screen(
|
|
2111
|
+
TextInputModal(
|
|
2112
|
+
title="Go to line",
|
|
2113
|
+
prompt=f"Line 1–{line_count}, optionally with a column (42:7). You're on line {row}.",
|
|
2114
|
+
placeholder="42",
|
|
2115
|
+
confirm_label="Go",
|
|
2116
|
+
),
|
|
2117
|
+
_go,
|
|
2118
|
+
)
|
|
2119
|
+
|
|
2120
|
+
def action_toggle_sidebar(self) -> None:
|
|
2121
|
+
if not self._on_main_screen():
|
|
2122
|
+
return
|
|
2123
|
+
self.set_sidebar_visible(not self.query_one("#sidebar").display)
|
|
2124
|
+
|
|
2125
|
+
def action_toggle_terminal(self) -> None:
|
|
2126
|
+
if not self._on_main_screen():
|
|
2127
|
+
return
|
|
2128
|
+
if self.query_one("#welcome-view").display:
|
|
2129
|
+
self.notify("Open a folder or file to use Output.")
|
|
2130
|
+
return
|
|
2131
|
+
self.set_output_visible(not self.query_one("#output-pane").display)
|
|
2132
|
+
|
|
2133
|
+
# ---- Layout ----
|
|
2134
|
+
|
|
2135
|
+
def set_sidebar_visible(self, visible: bool) -> None:
|
|
2136
|
+
self.query_one("#sidebar").display = visible
|
|
2137
|
+
self.query_one("#sidebar-handle").display = visible
|
|
2138
|
+
if visible:
|
|
2139
|
+
self.set_sidebar_width(max(self.sidebar_width, MIN_SIDEBAR_WIDTH))
|
|
2140
|
+
elif self.focused is not None and self.query_one("#sidebar") in self.focused.ancestors:
|
|
2141
|
+
self._focus_main()
|
|
2142
|
+
self._sync_layout_toggles()
|
|
2143
|
+
|
|
2144
|
+
def set_sidebar_width(self, width: int) -> None:
|
|
2145
|
+
max_w = MAX_SIDEBAR_WIDTH
|
|
2146
|
+
if self.size.width:
|
|
2147
|
+
max_w = max(MIN_SIDEBAR_WIDTH, min(MAX_SIDEBAR_WIDTH, self.size.width - 30))
|
|
2148
|
+
self.sidebar_width = max(MIN_SIDEBAR_WIDTH, min(width, max_w))
|
|
2149
|
+
sidebar = self.query_one("#sidebar")
|
|
2150
|
+
sidebar.styles.width = self.sidebar_width
|
|
2151
|
+
sidebar.styles.min_width = None
|
|
2152
|
+
sidebar.styles.max_width = None
|
|
2153
|
+
|
|
2154
|
+
def set_output_visible(self, visible: bool) -> None:
|
|
2155
|
+
self.output_visible = visible
|
|
2156
|
+
on_welcome = self.query_one("#welcome-view").display
|
|
2157
|
+
out_pane = self.query_one("#output-pane")
|
|
2158
|
+
out_pane.display = visible and not on_welcome
|
|
2159
|
+
if visible and self.terminal_height < MIN_TERMINAL_HEIGHT + 2:
|
|
2160
|
+
self.set_terminal_height(DEFAULT_TERMINAL_HEIGHT)
|
|
2161
|
+
if not visible and self.focused is not None and out_pane in self.focused.ancestors:
|
|
2162
|
+
self._focus_main()
|
|
2163
|
+
self._sync_layout_toggles()
|
|
2164
|
+
|
|
2165
|
+
def _focus_main(self) -> None:
|
|
2166
|
+
if self.query_one("#editor").display:
|
|
2167
|
+
self._active_editor().focus()
|
|
2168
|
+
else:
|
|
2169
|
+
self.query_one("#home-open-folder-btn").focus()
|
|
2170
|
+
|
|
2171
|
+
def _sync_layout_toggles(self) -> None:
|
|
2172
|
+
self.query_one("#status-files-btn").set_class(self.query_one("#sidebar").display, "-on")
|
|
2173
|
+
self.query_one("#status-output-btn").set_class(
|
|
2174
|
+
bool(self.query_one("#output-pane").display), "-on"
|
|
2175
|
+
)
|
|
2176
|
+
|
|
2177
|
+
def action_toggle_hidden(self) -> None:
|
|
2178
|
+
if not self._on_main_screen():
|
|
2179
|
+
return
|
|
2180
|
+
tree = self.query_one("#file-tree", FilteredDirectoryTree)
|
|
2181
|
+
tree.show_hidden = not tree.show_hidden
|
|
2182
|
+
if self.workspace_root is not None:
|
|
2183
|
+
tree.reload()
|
|
2184
|
+
state = "shown" if tree.show_hidden else "hidden"
|
|
2185
|
+
self.notify(f"Hidden files {state}")
|
|
2186
|
+
|
|
2187
|
+
def action_terminal_grow(self) -> None:
|
|
2188
|
+
if not self._on_main_screen():
|
|
2189
|
+
return
|
|
2190
|
+
if not self.query_one("#output-pane").display:
|
|
2191
|
+
self.set_output_visible(True)
|
|
2192
|
+
self.set_terminal_height(self.terminal_height + 3)
|
|
2193
|
+
|
|
2194
|
+
def action_terminal_shrink(self) -> None:
|
|
2195
|
+
if not self._on_main_screen():
|
|
2196
|
+
return
|
|
2197
|
+
out_pane = self.query_one("#output-pane")
|
|
2198
|
+
if not out_pane.display:
|
|
2199
|
+
return
|
|
2200
|
+
self.set_terminal_height(self.terminal_height - 3)
|
|
2201
|
+
|
|
2202
|
+
def action_copy_output(self) -> None:
|
|
2203
|
+
if not self._on_main_screen():
|
|
2204
|
+
return
|
|
2205
|
+
self._flush_output()
|
|
2206
|
+
log = self.query_one("#output-log", CodeTextArea)
|
|
2207
|
+
if log.selected_text:
|
|
2208
|
+
self.copy_to_clipboard(log.selected_text)
|
|
2209
|
+
self.notify(f"Copied selection ({len(log.selected_text)} chars)")
|
|
2210
|
+
return
|
|
2211
|
+
if not self.output_history:
|
|
2212
|
+
self.notify("Terminal output is empty.")
|
|
2213
|
+
return
|
|
2214
|
+
self.copy_to_clipboard(self.output_history)
|
|
2215
|
+
self.notify("Copied all terminal output")
|
|
2216
|
+
|
|
2217
|
+
def action_clear_output(self) -> None:
|
|
2218
|
+
if not self._on_main_screen():
|
|
2219
|
+
return
|
|
2220
|
+
self.output_history = ""
|
|
2221
|
+
self.query_one("#output-log", CodeTextArea).load_text("")
|
|
2222
|
+
|
|
2223
|
+
def action_request_quit(self) -> None:
|
|
2224
|
+
if not self._on_main_screen():
|
|
2225
|
+
return
|
|
2226
|
+
|
|
2227
|
+
def _finish_quit() -> None:
|
|
2228
|
+
self._shutdown_and_exit()
|
|
2229
|
+
|
|
2230
|
+
self._guard_all_unsaved(_finish_quit)
|
|
2231
|
+
|
|
2232
|
+
@work
|
|
2233
|
+
async def _shutdown_and_exit(self) -> None:
|
|
2234
|
+
if self.runner.is_running:
|
|
2235
|
+
await self.runner.stop()
|
|
2236
|
+
self.exit()
|