projectcats-cli 1.0.2__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.
- pcat/__init__.py +2 -0
- pcat/box.py +554 -0
- pcat/cli.py +583 -0
- pcat/config.py +118 -0
- pcat/modules.py +440 -0
- pcat/packer.py +364 -0
- pcat/plugins.py +195 -0
- pcat/templates.py +223 -0
- pcat/terminal.py +1321 -0
- projectcats_cli-1.0.2.dist-info/METADATA +11 -0
- projectcats_cli-1.0.2.dist-info/RECORD +15 -0
- projectcats_cli-1.0.2.dist-info/WHEEL +5 -0
- projectcats_cli-1.0.2.dist-info/entry_points.txt +2 -0
- projectcats_cli-1.0.2.dist-info/licenses/LICENSE +21 -0
- projectcats_cli-1.0.2.dist-info/top_level.txt +1 -0
pcat/terminal.py
ADDED
|
@@ -0,0 +1,1321 @@
|
|
|
1
|
+
# pcat/terminal.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import ctypes
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import platform
|
|
9
|
+
import socket
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import tempfile
|
|
13
|
+
import threading
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from prompt_toolkit.application import Application
|
|
18
|
+
from prompt_toolkit.buffer import Buffer
|
|
19
|
+
from prompt_toolkit.filters import Condition
|
|
20
|
+
from prompt_toolkit.formatted_text import FormattedText
|
|
21
|
+
from prompt_toolkit.key_binding import KeyBindings
|
|
22
|
+
from prompt_toolkit.layout import (
|
|
23
|
+
ConditionalContainer,
|
|
24
|
+
Dimension,
|
|
25
|
+
Float,
|
|
26
|
+
FloatContainer,
|
|
27
|
+
HSplit,
|
|
28
|
+
Layout,
|
|
29
|
+
VSplit,
|
|
30
|
+
Window,
|
|
31
|
+
)
|
|
32
|
+
from prompt_toolkit.layout.controls import FormattedTextControl
|
|
33
|
+
from prompt_toolkit.styles import Style
|
|
34
|
+
from prompt_toolkit.widgets import TextArea
|
|
35
|
+
|
|
36
|
+
from pcat.config import load_config, save_config
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _decode_windows_output(data: bytes) -> str:
|
|
40
|
+
if not data:
|
|
41
|
+
return ""
|
|
42
|
+
for enc in ("cp866", "utf-8", "cp1251"):
|
|
43
|
+
try:
|
|
44
|
+
text = data.decode(enc)
|
|
45
|
+
if text.count("\ufffd") == 0:
|
|
46
|
+
return text
|
|
47
|
+
except UnicodeDecodeError:
|
|
48
|
+
continue
|
|
49
|
+
return data.decode("cp866", errors="replace")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _decode_bytes_utf8_first(data: bytes) -> str:
|
|
53
|
+
if not data:
|
|
54
|
+
return ""
|
|
55
|
+
for enc in ("utf-8", "cp866", "cp1251"):
|
|
56
|
+
try:
|
|
57
|
+
text = data.decode(enc)
|
|
58
|
+
if text.count("\ufffd") == 0:
|
|
59
|
+
return text
|
|
60
|
+
except UnicodeDecodeError:
|
|
61
|
+
continue
|
|
62
|
+
return data.decode("cp866", errors="replace")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _close_parent_console_windows() -> None:
|
|
66
|
+
try:
|
|
67
|
+
kernel32 = ctypes.windll.kernel32
|
|
68
|
+
user32 = ctypes.windll.user32
|
|
69
|
+
hwnd = kernel32.GetConsoleWindow()
|
|
70
|
+
if hwnd:
|
|
71
|
+
WM_CLOSE = 0x0010
|
|
72
|
+
user32.PostMessageW(hwnd, WM_CLOSE, 0, 0)
|
|
73
|
+
except Exception:
|
|
74
|
+
pass
|
|
75
|
+
try:
|
|
76
|
+
ppid = os.getppid()
|
|
77
|
+
if ppid and ppid > 4:
|
|
78
|
+
subprocess.Popen(
|
|
79
|
+
["taskkill", "/F", "/T", "/PID", str(ppid)],
|
|
80
|
+
stdout=subprocess.DEVNULL,
|
|
81
|
+
stderr=subprocess.DEVNULL,
|
|
82
|
+
)
|
|
83
|
+
except Exception:
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _get_clipboard_text() -> str:
|
|
88
|
+
if platform.system().lower().startswith("win"):
|
|
89
|
+
try:
|
|
90
|
+
user32 = ctypes.windll.user32
|
|
91
|
+
kernel32 = ctypes.windll.kernel32
|
|
92
|
+
CF_UNICODETEXT = 13
|
|
93
|
+
CF_TEXT = 1
|
|
94
|
+
if user32.OpenClipboard(None):
|
|
95
|
+
try:
|
|
96
|
+
if user32.IsClipboardFormatAvailable(CF_UNICODETEXT):
|
|
97
|
+
handle = user32.GetClipboardData(CF_UNICODETEXT)
|
|
98
|
+
if handle:
|
|
99
|
+
kernel32.GlobalLock.restype = ctypes.c_void_p
|
|
100
|
+
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
|
|
101
|
+
ptr = kernel32.GlobalLock(handle)
|
|
102
|
+
if ptr:
|
|
103
|
+
try:
|
|
104
|
+
return ctypes.wstring_at(ptr)
|
|
105
|
+
finally:
|
|
106
|
+
kernel32.GlobalUnlock(handle)
|
|
107
|
+
elif user32.IsClipboardFormatAvailable(CF_TEXT):
|
|
108
|
+
handle = user32.GetClipboardData(CF_TEXT)
|
|
109
|
+
if handle:
|
|
110
|
+
kernel32.GlobalLock.restype = ctypes.c_void_p
|
|
111
|
+
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
|
|
112
|
+
ptr = kernel32.GlobalLock(handle)
|
|
113
|
+
if ptr:
|
|
114
|
+
try:
|
|
115
|
+
raw = ctypes.string_at(ptr)
|
|
116
|
+
return _decode_windows_output(raw)
|
|
117
|
+
finally:
|
|
118
|
+
kernel32.GlobalUnlock(handle)
|
|
119
|
+
finally:
|
|
120
|
+
user32.CloseClipboard()
|
|
121
|
+
except Exception:
|
|
122
|
+
pass
|
|
123
|
+
try:
|
|
124
|
+
proc = subprocess.run(
|
|
125
|
+
["powershell", "-NoProfile", "-Command", "Get-Clipboard -Raw"],
|
|
126
|
+
capture_output=True,
|
|
127
|
+
timeout=3,
|
|
128
|
+
)
|
|
129
|
+
if proc.returncode == 0 and proc.stdout:
|
|
130
|
+
return _decode_windows_output(proc.stdout).rstrip("\r\n")
|
|
131
|
+
except Exception:
|
|
132
|
+
pass
|
|
133
|
+
return ""
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _toggle_console_fullscreen_state(is_fullscreen: bool) -> bool:
|
|
137
|
+
if not platform.system().lower().startswith("win"):
|
|
138
|
+
return is_fullscreen
|
|
139
|
+
try:
|
|
140
|
+
kernel32 = ctypes.windll.kernel32
|
|
141
|
+
user32 = ctypes.windll.user32
|
|
142
|
+
hwnd = kernel32.GetConsoleWindow()
|
|
143
|
+
if not hwnd:
|
|
144
|
+
return is_fullscreen
|
|
145
|
+
SW_RESTORE = 9
|
|
146
|
+
SW_MAXIMIZE = 3
|
|
147
|
+
target_is_fs = not is_fullscreen
|
|
148
|
+
cmd = SW_MAXIMIZE if target_is_fs else SW_RESTORE
|
|
149
|
+
user32.ShowWindow(hwnd, cmd)
|
|
150
|
+
return target_is_fs
|
|
151
|
+
except Exception:
|
|
152
|
+
return is_fullscreen
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@dataclass
|
|
156
|
+
class SimpleEditorState:
|
|
157
|
+
active: bool = False
|
|
158
|
+
file_path: str = ""
|
|
159
|
+
lines: list[str] = field(default_factory=lambda: [""])
|
|
160
|
+
row: int = 0
|
|
161
|
+
col: int = 0
|
|
162
|
+
mode: str = "EDIT" # "EDIT" or "CMD"
|
|
163
|
+
status_msg: str = ""
|
|
164
|
+
dirty: bool = False
|
|
165
|
+
|
|
166
|
+
def open_file(self, path: str) -> None:
|
|
167
|
+
abs_path = os.path.abspath(path)
|
|
168
|
+
self.file_path = abs_path
|
|
169
|
+
if os.path.isfile(abs_path):
|
|
170
|
+
with open(abs_path, "r", encoding="utf-8", errors="replace") as f:
|
|
171
|
+
content = f.read().splitlines()
|
|
172
|
+
self.lines = content if content else [""]
|
|
173
|
+
self.status_msg = f'Opened "{os.path.basename(abs_path)}" ({len(self.lines)} lines)'
|
|
174
|
+
else:
|
|
175
|
+
self.lines = [""]
|
|
176
|
+
self.status_msg = f'New file "{os.path.basename(abs_path)}"'
|
|
177
|
+
self.row = 0
|
|
178
|
+
self.col = 0
|
|
179
|
+
self.mode = "EDIT"
|
|
180
|
+
self.dirty = False
|
|
181
|
+
self.active = True
|
|
182
|
+
|
|
183
|
+
def close(self) -> None:
|
|
184
|
+
self.active = False
|
|
185
|
+
self.mode = "EDIT"
|
|
186
|
+
self.status_msg = ""
|
|
187
|
+
|
|
188
|
+
def toggle_mode(self) -> str:
|
|
189
|
+
self.mode = "CMD" if self.mode == "EDIT" else "EDIT"
|
|
190
|
+
if self.mode == "CMD":
|
|
191
|
+
self.status_msg = "CMD mode: s, sq, q, py/python/runbypython/rbp"
|
|
192
|
+
else:
|
|
193
|
+
self.status_msg = "EDIT mode: type text directly into editor"
|
|
194
|
+
return self.mode
|
|
195
|
+
|
|
196
|
+
def save_file(self) -> bool:
|
|
197
|
+
if not self.file_path:
|
|
198
|
+
self.status_msg = "No file path specified"
|
|
199
|
+
return False
|
|
200
|
+
try:
|
|
201
|
+
parent = os.path.dirname(self.file_path)
|
|
202
|
+
if parent:
|
|
203
|
+
os.makedirs(parent, exist_ok=True)
|
|
204
|
+
with open(self.file_path, "w", encoding="utf-8", newline="\n") as f:
|
|
205
|
+
f.write("\n".join(self.lines) + ("\n" if self.lines else ""))
|
|
206
|
+
self.dirty = False
|
|
207
|
+
self.status_msg = f'Saved "{os.path.basename(self.file_path)}"'
|
|
208
|
+
return True
|
|
209
|
+
except Exception as exc:
|
|
210
|
+
self.status_msg = f"Save error: {exc}"
|
|
211
|
+
return False
|
|
212
|
+
|
|
213
|
+
def _clamp_cursor(self) -> None:
|
|
214
|
+
self.row = max(0, min(self.row, len(self.lines) - 1))
|
|
215
|
+
self.col = max(0, min(self.col, len(self.lines[self.row])))
|
|
216
|
+
|
|
217
|
+
def move_left(self) -> None:
|
|
218
|
+
if self.col > 0:
|
|
219
|
+
self.col -= 1
|
|
220
|
+
elif self.row > 0:
|
|
221
|
+
self.row -= 1
|
|
222
|
+
self.col = len(self.lines[self.row])
|
|
223
|
+
|
|
224
|
+
def move_right(self) -> None:
|
|
225
|
+
if self.col < len(self.lines[self.row]):
|
|
226
|
+
self.col += 1
|
|
227
|
+
elif self.row + 1 < len(self.lines):
|
|
228
|
+
self.row += 1
|
|
229
|
+
self.col = 0
|
|
230
|
+
|
|
231
|
+
def move_up(self) -> None:
|
|
232
|
+
if self.row > 0:
|
|
233
|
+
self.row -= 1
|
|
234
|
+
self._clamp_cursor()
|
|
235
|
+
|
|
236
|
+
def move_down(self) -> None:
|
|
237
|
+
if self.row + 1 < len(self.lines):
|
|
238
|
+
self.row += 1
|
|
239
|
+
self._clamp_cursor()
|
|
240
|
+
|
|
241
|
+
def insert_char(self, ch: str) -> None:
|
|
242
|
+
line = self.lines[self.row]
|
|
243
|
+
self.lines[self.row] = line[: self.col] + ch + line[self.col :]
|
|
244
|
+
self.col += len(ch)
|
|
245
|
+
self.dirty = True
|
|
246
|
+
|
|
247
|
+
def insert_text(self, text: str) -> None:
|
|
248
|
+
if not text:
|
|
249
|
+
return
|
|
250
|
+
normalized = text.replace("\r\n", "\n").replace("\r", "\n")
|
|
251
|
+
parts = normalized.split("\n")
|
|
252
|
+
line = self.lines[self.row]
|
|
253
|
+
before = line[: self.col]
|
|
254
|
+
after = line[self.col :]
|
|
255
|
+
if len(parts) == 1:
|
|
256
|
+
self.lines[self.row] = before + parts[0] + after
|
|
257
|
+
self.col += len(parts[0])
|
|
258
|
+
else:
|
|
259
|
+
self.lines[self.row] = before + parts[0]
|
|
260
|
+
middle = parts[1:-1]
|
|
261
|
+
last = parts[-1] + after
|
|
262
|
+
for offset, mid_line in enumerate(middle, start=1):
|
|
263
|
+
self.lines.insert(self.row + offset, mid_line)
|
|
264
|
+
self.lines.insert(self.row + 1 + len(middle), last)
|
|
265
|
+
self.row = self.row + 1 + len(middle)
|
|
266
|
+
self.col = len(parts[-1])
|
|
267
|
+
self.dirty = True
|
|
268
|
+
|
|
269
|
+
def insert_newline(self) -> None:
|
|
270
|
+
line = self.lines[self.row]
|
|
271
|
+
left = line[: self.col]
|
|
272
|
+
right = line[self.col :]
|
|
273
|
+
self.lines[self.row] = left
|
|
274
|
+
self.lines.insert(self.row + 1, right)
|
|
275
|
+
self.row += 1
|
|
276
|
+
self.col = 0
|
|
277
|
+
self.dirty = True
|
|
278
|
+
|
|
279
|
+
def backspace(self) -> None:
|
|
280
|
+
if self.col > 0:
|
|
281
|
+
line = self.lines[self.row]
|
|
282
|
+
self.lines[self.row] = line[: self.col - 1] + line[self.col :]
|
|
283
|
+
self.col -= 1
|
|
284
|
+
self.dirty = True
|
|
285
|
+
elif self.row > 0:
|
|
286
|
+
prev_len = len(self.lines[self.row - 1])
|
|
287
|
+
self.lines[self.row - 1] += self.lines.pop(self.row)
|
|
288
|
+
self.row -= 1
|
|
289
|
+
self.col = prev_len
|
|
290
|
+
self.dirty = True
|
|
291
|
+
|
|
292
|
+
def delete_forward(self) -> None:
|
|
293
|
+
line = self.lines[self.row]
|
|
294
|
+
if self.col < len(line):
|
|
295
|
+
self.lines[self.row] = line[: self.col] + line[self.col + 1 :]
|
|
296
|
+
self.dirty = True
|
|
297
|
+
elif self.row + 1 < len(self.lines):
|
|
298
|
+
self.lines[self.row] = line + self.lines.pop(self.row + 1)
|
|
299
|
+
self.dirty = True
|
|
300
|
+
|
|
301
|
+
def render(self) -> FormattedText:
|
|
302
|
+
tokens: list[tuple[str, str]] = []
|
|
303
|
+
fname = os.path.basename(self.file_path) if self.file_path else "[No Name]"
|
|
304
|
+
dirty_mark = " *" if self.dirty else ""
|
|
305
|
+
top_bar = (
|
|
306
|
+
f" EDITOR | {fname}{dirty_mark} | Mode: {self.mode} (Ctrl+I) | "
|
|
307
|
+
f"Ln {self.row + 1}/{len(self.lines)}, Col {self.col + 1}\n"
|
|
308
|
+
)
|
|
309
|
+
tokens.append(("class:vim-header", top_bar))
|
|
310
|
+
view_height = 22
|
|
311
|
+
start_row = max(0, min(self.row - view_height // 2, max(0, len(self.lines) - view_height)))
|
|
312
|
+
end_row = min(len(self.lines), start_row + view_height)
|
|
313
|
+
for r in range(start_row, end_row):
|
|
314
|
+
line = self.lines[r]
|
|
315
|
+
lineno = f"{r + 1:4d} "
|
|
316
|
+
tokens.append(("class:vim-lineno", lineno))
|
|
317
|
+
if r == self.row:
|
|
318
|
+
c_idx = min(self.col, len(line))
|
|
319
|
+
before = line[:c_idx]
|
|
320
|
+
cursor_ch = line[c_idx : c_idx + 1] if c_idx < len(line) else " "
|
|
321
|
+
after = line[c_idx + 1 :] if c_idx < len(line) else ""
|
|
322
|
+
tokens.append(("class:vim-text", before))
|
|
323
|
+
tokens.append(("class:vim-cursor", cursor_ch))
|
|
324
|
+
tokens.append(("class:vim-text", after + "\n"))
|
|
325
|
+
else:
|
|
326
|
+
tokens.append(("class:vim-text", line + "\n"))
|
|
327
|
+
hint = (
|
|
328
|
+
self.status_msg
|
|
329
|
+
or "Ctrl+I: EDIT <-> CMD | CMD: s, sq, q, py/python/runbypython/rbp"
|
|
330
|
+
)
|
|
331
|
+
tokens.append(("class:vim-status", hint))
|
|
332
|
+
return FormattedText(tokens)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
@dataclass
|
|
336
|
+
class TerminalPane:
|
|
337
|
+
pane_id: int
|
|
338
|
+
title: str = ""
|
|
339
|
+
cwd: str = field(default_factory=os.getcwd)
|
|
340
|
+
history: list[str] = field(default_factory=list)
|
|
341
|
+
cmd_history: list[str] = field(default_factory=list)
|
|
342
|
+
cmd_history_idx: int | None = None
|
|
343
|
+
draft_input: str = ""
|
|
344
|
+
scroll_offset: int = 0
|
|
345
|
+
editor: SimpleEditorState = field(default_factory=SimpleEditorState)
|
|
346
|
+
running_proc: subprocess.Popen | None = None
|
|
347
|
+
box_client: socket.socket | None = None
|
|
348
|
+
box_label: str = ""
|
|
349
|
+
input_area: TextArea = field(init=False)
|
|
350
|
+
output_control: FormattedTextControl = field(init=False)
|
|
351
|
+
output_window: Window = field(init=False)
|
|
352
|
+
container: HSplit = field(init=False)
|
|
353
|
+
_refresh_cb: object = field(default=None, repr=False)
|
|
354
|
+
_io_lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
|
|
355
|
+
|
|
356
|
+
def __post_init__(self) -> None:
|
|
357
|
+
if not self.title:
|
|
358
|
+
self.title = f"Tab #{self.pane_id}"
|
|
359
|
+
self.history.append(f"[Pane #{self.pane_id}] cwd: {self.cwd}")
|
|
360
|
+
self.history.append(
|
|
361
|
+
"Commands: edit <file>, cd <path>, attach <box>, detach, ps <cmd>, cmd <cmd>, clear"
|
|
362
|
+
)
|
|
363
|
+
self.output_control = FormattedTextControl(
|
|
364
|
+
text=self._render_output,
|
|
365
|
+
focusable=False,
|
|
366
|
+
)
|
|
367
|
+
self.output_window = Window(
|
|
368
|
+
content=self.output_control,
|
|
369
|
+
wrap_lines=True,
|
|
370
|
+
height=Dimension(min=3, weight=1),
|
|
371
|
+
)
|
|
372
|
+
self.input_area = TextArea(
|
|
373
|
+
height=1,
|
|
374
|
+
prompt=self._render_prompt,
|
|
375
|
+
multiline=False,
|
|
376
|
+
wrap_lines=False,
|
|
377
|
+
)
|
|
378
|
+
self.container = HSplit(
|
|
379
|
+
[
|
|
380
|
+
self.output_window,
|
|
381
|
+
Window(height=1, char="─", style="class:pane-divider"),
|
|
382
|
+
self.input_area,
|
|
383
|
+
],
|
|
384
|
+
height=Dimension(min=6, weight=1),
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
def _render_prompt(self) -> FormattedText:
|
|
388
|
+
if self.box_client is not None:
|
|
389
|
+
return FormattedText([("class:cmd", f"#{self.pane_id} [BOX:{self.box_label}]> ")])
|
|
390
|
+
if self.editor.active:
|
|
391
|
+
return FormattedText([("class:meta", f"#{self.pane_id} [{self.editor.mode}]> ")])
|
|
392
|
+
return FormattedText([("class:out", f"#{self.pane_id}> ")])
|
|
393
|
+
|
|
394
|
+
def _notify_ui(self) -> None:
|
|
395
|
+
if callable(self._refresh_cb):
|
|
396
|
+
try:
|
|
397
|
+
self._refresh_cb()
|
|
398
|
+
except Exception:
|
|
399
|
+
pass
|
|
400
|
+
|
|
401
|
+
def detach_box(self) -> None:
|
|
402
|
+
if self.box_client is not None:
|
|
403
|
+
try:
|
|
404
|
+
self.box_client.close()
|
|
405
|
+
except Exception:
|
|
406
|
+
pass
|
|
407
|
+
self.box_client = None
|
|
408
|
+
if self.box_label:
|
|
409
|
+
self.append_line(f"[DETACHED] {self.box_label}")
|
|
410
|
+
self.box_label = ""
|
|
411
|
+
self._notify_ui()
|
|
412
|
+
|
|
413
|
+
def terminate_running_proc(self) -> None:
|
|
414
|
+
proc = self.running_proc
|
|
415
|
+
if proc is not None and proc.poll() is None:
|
|
416
|
+
try:
|
|
417
|
+
proc.terminate()
|
|
418
|
+
except Exception:
|
|
419
|
+
pass
|
|
420
|
+
self.running_proc = None
|
|
421
|
+
self.detach_box()
|
|
422
|
+
|
|
423
|
+
def send_box_input(self, line: str) -> None:
|
|
424
|
+
if self.box_client is None:
|
|
425
|
+
return
|
|
426
|
+
if line.strip().lower() == "detach":
|
|
427
|
+
self.detach_box()
|
|
428
|
+
return
|
|
429
|
+
try:
|
|
430
|
+
self.append_line(f"[BOX IN] {line}")
|
|
431
|
+
self.box_client.sendall((line + "\n").encode("utf-8"))
|
|
432
|
+
self._notify_ui()
|
|
433
|
+
except Exception as exc:
|
|
434
|
+
self.append_line(f"[ERR] Failed sending input to box: {exc}")
|
|
435
|
+
self.detach_box()
|
|
436
|
+
|
|
437
|
+
def _stream_process_async(
|
|
438
|
+
self,
|
|
439
|
+
exec_args: list[str],
|
|
440
|
+
cwd: str,
|
|
441
|
+
env: dict[str, str],
|
|
442
|
+
start_msg: str,
|
|
443
|
+
done_prefix: str,
|
|
444
|
+
tmp_path: str = "",
|
|
445
|
+
from_editor: bool = False,
|
|
446
|
+
) -> None:
|
|
447
|
+
if self.running_proc is not None and self.running_proc.poll() is None:
|
|
448
|
+
self.append_line("[ERR] Another process is already running in this pane.")
|
|
449
|
+
self._notify_ui()
|
|
450
|
+
return
|
|
451
|
+
self.append_line(start_msg)
|
|
452
|
+
if from_editor:
|
|
453
|
+
self.editor.status_msg = "Running in background..."
|
|
454
|
+
self._notify_ui()
|
|
455
|
+
|
|
456
|
+
def _worker() -> None:
|
|
457
|
+
is_windows = platform.system().lower().startswith("win")
|
|
458
|
+
try:
|
|
459
|
+
proc = subprocess.Popen(
|
|
460
|
+
exec_args,
|
|
461
|
+
cwd=cwd,
|
|
462
|
+
env=env,
|
|
463
|
+
stdin=subprocess.DEVNULL,
|
|
464
|
+
stdout=subprocess.PIPE,
|
|
465
|
+
stderr=subprocess.STDOUT,
|
|
466
|
+
bufsize=0,
|
|
467
|
+
)
|
|
468
|
+
self.running_proc = proc
|
|
469
|
+
line_buf = bytearray()
|
|
470
|
+
assert proc.stdout is not None
|
|
471
|
+
while True:
|
|
472
|
+
b = proc.stdout.read(1)
|
|
473
|
+
if not b:
|
|
474
|
+
break
|
|
475
|
+
if b == b"\n":
|
|
476
|
+
decoded = (
|
|
477
|
+
_decode_bytes_utf8_first(bytes(line_buf))
|
|
478
|
+
if from_editor or not is_windows
|
|
479
|
+
else _decode_windows_output(bytes(line_buf))
|
|
480
|
+
).rstrip("\r")
|
|
481
|
+
line_buf.clear()
|
|
482
|
+
self.append_line(decoded)
|
|
483
|
+
self._notify_ui()
|
|
484
|
+
else:
|
|
485
|
+
line_buf.extend(b)
|
|
486
|
+
if line_buf:
|
|
487
|
+
tail_txt = (
|
|
488
|
+
_decode_bytes_utf8_first(bytes(line_buf))
|
|
489
|
+
if from_editor or not is_windows
|
|
490
|
+
else _decode_windows_output(bytes(line_buf))
|
|
491
|
+
).rstrip("\r")
|
|
492
|
+
self.append_line(tail_txt)
|
|
493
|
+
code = proc.wait()
|
|
494
|
+
self.running_proc = None
|
|
495
|
+
self.append_line(f"[{done_prefix} DONE] exit={code}")
|
|
496
|
+
if from_editor:
|
|
497
|
+
self.editor.status_msg = f"Python finished (exit={code})"
|
|
498
|
+
self._notify_ui()
|
|
499
|
+
except Exception as exc:
|
|
500
|
+
self.running_proc = None
|
|
501
|
+
self.append_line(f"[ERR] {done_prefix} failed: {exc}")
|
|
502
|
+
if from_editor:
|
|
503
|
+
self.editor.status_msg = f"Run error: {exc}"
|
|
504
|
+
self._notify_ui()
|
|
505
|
+
finally:
|
|
506
|
+
if tmp_path and os.path.exists(tmp_path):
|
|
507
|
+
try:
|
|
508
|
+
os.remove(tmp_path)
|
|
509
|
+
except Exception:
|
|
510
|
+
pass
|
|
511
|
+
|
|
512
|
+
threading.Thread(target=_worker, daemon=True).start()
|
|
513
|
+
|
|
514
|
+
def start_python_live(self, file_label: str, code_text: str) -> None:
|
|
515
|
+
tmp_path = ""
|
|
516
|
+
try:
|
|
517
|
+
with tempfile.NamedTemporaryFile(
|
|
518
|
+
mode="w",
|
|
519
|
+
suffix=".py",
|
|
520
|
+
prefix="pcat_run_",
|
|
521
|
+
encoding="utf-8",
|
|
522
|
+
delete=False,
|
|
523
|
+
) as tmp:
|
|
524
|
+
tmp.write(code_text)
|
|
525
|
+
tmp_path = tmp.name
|
|
526
|
+
except Exception as exc:
|
|
527
|
+
self.append_line(f"[ERR] Temp file error: {exc}")
|
|
528
|
+
self._notify_ui()
|
|
529
|
+
return
|
|
530
|
+
python_exe = sys.executable or "python"
|
|
531
|
+
env = os.environ.copy()
|
|
532
|
+
env["PYTHONUTF8"] = "1"
|
|
533
|
+
env["PYTHONIOENCODING"] = "utf-8"
|
|
534
|
+
env["PYTHONUNBUFFERED"] = "1"
|
|
535
|
+
self._stream_process_async(
|
|
536
|
+
exec_args=[python_exe, "-u", tmp_path],
|
|
537
|
+
cwd=self.cwd,
|
|
538
|
+
env=env,
|
|
539
|
+
start_msg=f"[PYTHON RUN] {file_label}",
|
|
540
|
+
done_prefix="PYTHON",
|
|
541
|
+
tmp_path=tmp_path,
|
|
542
|
+
from_editor=True,
|
|
543
|
+
)
|
|
544
|
+
|
|
545
|
+
def execute_editor_cmd(self, raw_cmd: str) -> bool:
|
|
546
|
+
cmd = raw_cmd.strip().lower()
|
|
547
|
+
if not cmd:
|
|
548
|
+
return False
|
|
549
|
+
if cmd == "s":
|
|
550
|
+
ok = self.editor.save_file()
|
|
551
|
+
self.append_line(f"[EDITOR] {self.editor.status_msg}" if ok else f"[ERR] {self.editor.status_msg}")
|
|
552
|
+
return False
|
|
553
|
+
if cmd == "sq":
|
|
554
|
+
ok = self.editor.save_file()
|
|
555
|
+
if ok:
|
|
556
|
+
path = self.editor.file_path
|
|
557
|
+
self.editor.close()
|
|
558
|
+
self.append_line(f"[EDITOR] Saved & closed: {path}")
|
|
559
|
+
return True
|
|
560
|
+
self.append_line(f"[ERR] {self.editor.status_msg}")
|
|
561
|
+
return False
|
|
562
|
+
if cmd == "q":
|
|
563
|
+
self.terminate_running_proc()
|
|
564
|
+
path = self.editor.file_path
|
|
565
|
+
self.editor.close()
|
|
566
|
+
self.append_line(f"[EDITOR] Closed without saving: {path}")
|
|
567
|
+
return True
|
|
568
|
+
if cmd in ("py", "python", "runbypython", "rbp"):
|
|
569
|
+
code_text = "\n".join(self.editor.lines) + ("\n" if self.editor.lines else "")
|
|
570
|
+
self.start_python_live(self.editor.file_path or "<buffer>", code_text)
|
|
571
|
+
return False
|
|
572
|
+
msg = f"Unknown editor CMD '{raw_cmd.strip()}'. Use: s, sq, q, py, python, runbypython, rbp"
|
|
573
|
+
self.editor.status_msg = msg
|
|
574
|
+
self.append_line(f"[ERR] {msg}")
|
|
575
|
+
return False
|
|
576
|
+
|
|
577
|
+
def record_command(self, cmd: str) -> None:
|
|
578
|
+
if not self.cmd_history or self.cmd_history[-1] != cmd:
|
|
579
|
+
self.cmd_history.append(cmd)
|
|
580
|
+
self.cmd_history_idx = None
|
|
581
|
+
self.draft_input = ""
|
|
582
|
+
|
|
583
|
+
def history_prev(self) -> None:
|
|
584
|
+
if not self.cmd_history:
|
|
585
|
+
return
|
|
586
|
+
if self.cmd_history_idx is None:
|
|
587
|
+
self.draft_input = self.input_area.text
|
|
588
|
+
self.cmd_history_idx = len(self.cmd_history) - 1
|
|
589
|
+
elif self.cmd_history_idx > 0:
|
|
590
|
+
self.cmd_history_idx -= 1
|
|
591
|
+
self.input_area.text = self.cmd_history[self.cmd_history_idx]
|
|
592
|
+
self.input_area.buffer.cursor_position = len(self.input_area.text)
|
|
593
|
+
|
|
594
|
+
def history_next(self) -> None:
|
|
595
|
+
if self.cmd_history_idx is None:
|
|
596
|
+
return
|
|
597
|
+
if self.cmd_history_idx + 1 < len(self.cmd_history):
|
|
598
|
+
self.cmd_history_idx += 1
|
|
599
|
+
self.input_area.text = self.cmd_history[self.cmd_history_idx]
|
|
600
|
+
else:
|
|
601
|
+
self.cmd_history_idx = None
|
|
602
|
+
self.input_area.text = self.draft_input
|
|
603
|
+
self.input_area.buffer.cursor_position = len(self.input_area.text)
|
|
604
|
+
|
|
605
|
+
def scroll_up(self, step: int = 5) -> None:
|
|
606
|
+
with self._io_lock:
|
|
607
|
+
max_offset = max(0, len(self.history) - 1)
|
|
608
|
+
self.scroll_offset = min(max_offset, self.scroll_offset + step)
|
|
609
|
+
|
|
610
|
+
def scroll_down(self, step: int = 5) -> None:
|
|
611
|
+
with self._io_lock:
|
|
612
|
+
self.scroll_offset = max(0, self.scroll_offset - step)
|
|
613
|
+
|
|
614
|
+
def scroll_to_bottom(self) -> None:
|
|
615
|
+
with self._io_lock:
|
|
616
|
+
self.scroll_offset = 0
|
|
617
|
+
|
|
618
|
+
def _render_output(self) -> FormattedText:
|
|
619
|
+
if self.editor.active:
|
|
620
|
+
return self.editor.render()
|
|
621
|
+
with self._io_lock:
|
|
622
|
+
total = len(self.history)
|
|
623
|
+
window_size = 60
|
|
624
|
+
end_idx = max(0, total - self.scroll_offset)
|
|
625
|
+
start_idx = max(0, end_idx - window_size)
|
|
626
|
+
visible = self.history[start_idx:end_idx]
|
|
627
|
+
offset = self.scroll_offset
|
|
628
|
+
tokens: list[tuple[str, str]] = []
|
|
629
|
+
if offset > 0:
|
|
630
|
+
tokens.append(
|
|
631
|
+
(
|
|
632
|
+
"class:meta",
|
|
633
|
+
f"--- scrolled up: -{offset} lines (Ctrl+K — bottom) ---\n",
|
|
634
|
+
)
|
|
635
|
+
)
|
|
636
|
+
for line in visible:
|
|
637
|
+
if line.startswith("[ERR]"):
|
|
638
|
+
tokens.append(("class:err", line + "\n"))
|
|
639
|
+
elif (
|
|
640
|
+
line.startswith("[Pane #")
|
|
641
|
+
or line.startswith("[PYTHON")
|
|
642
|
+
or line.startswith("[CMD")
|
|
643
|
+
or line.startswith("[ATTACH")
|
|
644
|
+
or line.startswith("[BOX")
|
|
645
|
+
or line.startswith("[DETACH")
|
|
646
|
+
):
|
|
647
|
+
tokens.append(("class:meta", line + "\n"))
|
|
648
|
+
elif line.startswith("$ ") or line.startswith("[BOX IN] "):
|
|
649
|
+
tokens.append(("class:cmd", line + "\n"))
|
|
650
|
+
else:
|
|
651
|
+
tokens.append(("class:out", line + "\n"))
|
|
652
|
+
return FormattedText(tokens)
|
|
653
|
+
|
|
654
|
+
def append_line(self, text: str) -> None:
|
|
655
|
+
with self._io_lock:
|
|
656
|
+
for part in text.splitlines() or [""]:
|
|
657
|
+
self.history.append(part)
|
|
658
|
+
self.scroll_offset = 0
|
|
659
|
+
|
|
660
|
+
def attach_to_box(self, identifier: str) -> None:
|
|
661
|
+
from pcat.box import box_ps
|
|
662
|
+
|
|
663
|
+
records = box_ps()
|
|
664
|
+
rec = None
|
|
665
|
+
for r in records:
|
|
666
|
+
if r.box_id == identifier or r.box_id.startswith(identifier) or r.name == identifier:
|
|
667
|
+
rec = r
|
|
668
|
+
break
|
|
669
|
+
|
|
670
|
+
if rec is None:
|
|
671
|
+
self.append_line(f"[ERR] Box not found: '{identifier}'")
|
|
672
|
+
self._notify_ui()
|
|
673
|
+
return
|
|
674
|
+
|
|
675
|
+
if rec.status != "running" or not rec.console_port:
|
|
676
|
+
self.append_line(f"[ERR] Box '{rec.box_id}' ({rec.name}) is not running or has no console port.")
|
|
677
|
+
self._notify_ui()
|
|
678
|
+
return
|
|
679
|
+
|
|
680
|
+
self.detach_box()
|
|
681
|
+
|
|
682
|
+
for label, log_str in (("stdout", rec.stdout_log), ("stderr", rec.stderr_log)):
|
|
683
|
+
if log_str and Path(log_str).is_file():
|
|
684
|
+
try:
|
|
685
|
+
tail_lines = Path(log_str).read_text(encoding="utf-8", errors="replace").splitlines()[-25:]
|
|
686
|
+
if tail_lines:
|
|
687
|
+
self.append_line(f"[BOX {label} tail]")
|
|
688
|
+
for ln in tail_lines:
|
|
689
|
+
self.append_line(ln)
|
|
690
|
+
except Exception:
|
|
691
|
+
pass
|
|
692
|
+
|
|
693
|
+
self.append_line(f"[ATTACH] Connecting to box {rec.box_id} ({rec.name}) @ 127.0.0.1:{rec.console_port}...")
|
|
694
|
+
self._notify_ui()
|
|
695
|
+
|
|
696
|
+
def _reader() -> None:
|
|
697
|
+
try:
|
|
698
|
+
client = socket.create_connection(("127.0.0.1", rec.console_port), timeout=2)
|
|
699
|
+
client.settimeout(0.2)
|
|
700
|
+
self.box_client = client
|
|
701
|
+
self.box_label = f"{rec.name}:{rec.box_id[:6]}"
|
|
702
|
+
self.append_line(f"[ATTACHED] Box {rec.box_id} ({rec.name}). Type 'detach' to disconnect.")
|
|
703
|
+
self._notify_ui()
|
|
704
|
+
|
|
705
|
+
buf = bytearray()
|
|
706
|
+
while self.box_client is client:
|
|
707
|
+
try:
|
|
708
|
+
data = client.recv(4096)
|
|
709
|
+
if not data:
|
|
710
|
+
break
|
|
711
|
+
buf.extend(data)
|
|
712
|
+
while b"\n" in buf:
|
|
713
|
+
line, buf = buf.split(b"\n", 1)
|
|
714
|
+
decoded = line.decode("utf-8", errors="replace").rstrip("\r")
|
|
715
|
+
self.append_line(decoded)
|
|
716
|
+
self._notify_ui()
|
|
717
|
+
except socket.timeout:
|
|
718
|
+
continue
|
|
719
|
+
except OSError:
|
|
720
|
+
break
|
|
721
|
+
|
|
722
|
+
if buf:
|
|
723
|
+
decoded = buf.decode("utf-8", errors="replace").rstrip("\r")
|
|
724
|
+
if decoded:
|
|
725
|
+
self.append_line(decoded)
|
|
726
|
+
self._notify_ui()
|
|
727
|
+
|
|
728
|
+
if self.box_client is client:
|
|
729
|
+
self.append_line(f"[DETACHED] Box {rec.box_id} exited or disconnected.")
|
|
730
|
+
self.box_client = None
|
|
731
|
+
self.box_label = ""
|
|
732
|
+
self._notify_ui()
|
|
733
|
+
try:
|
|
734
|
+
client.close()
|
|
735
|
+
except OSError:
|
|
736
|
+
pass
|
|
737
|
+
except Exception as e:
|
|
738
|
+
self.append_line(f"[ERR] Attach failed: {e}")
|
|
739
|
+
self.box_client = None
|
|
740
|
+
self.box_label = ""
|
|
741
|
+
self._notify_ui()
|
|
742
|
+
|
|
743
|
+
threading.Thread(target=_reader, daemon=True).start()
|
|
744
|
+
|
|
745
|
+
def execute(self, raw_cmd: str) -> None:
|
|
746
|
+
cmd = raw_cmd.strip()
|
|
747
|
+
if not cmd:
|
|
748
|
+
return
|
|
749
|
+
self.record_command(cmd)
|
|
750
|
+
self.append_line(f"$ {cmd}")
|
|
751
|
+
if cmd in ("clear", "cls"):
|
|
752
|
+
with self._io_lock:
|
|
753
|
+
self.history.clear()
|
|
754
|
+
self.history.append(f"[Pane #{self.pane_id}] cwd: {self.cwd}")
|
|
755
|
+
self.scroll_offset = 0
|
|
756
|
+
return
|
|
757
|
+
if cmd == "pwd":
|
|
758
|
+
self.append_line(self.cwd)
|
|
759
|
+
return
|
|
760
|
+
if cmd == "detach":
|
|
761
|
+
self.detach_box()
|
|
762
|
+
return
|
|
763
|
+
if cmd == "edit" or cmd.startswith("edit ") or cmd == "vim" or cmd.startswith("vim "):
|
|
764
|
+
parts = cmd.split(maxsplit=1)
|
|
765
|
+
if len(parts) < 2 or not parts[1].strip():
|
|
766
|
+
self.append_line("[ERR] Usage: edit <file_path>")
|
|
767
|
+
return
|
|
768
|
+
target_file = parts[1].strip().strip('"').strip("'")
|
|
769
|
+
resolved = os.path.abspath(os.path.join(self.cwd, target_file))
|
|
770
|
+
self.editor.open_file(resolved)
|
|
771
|
+
self.append_line(f"[EDITOR] Opened {resolved}")
|
|
772
|
+
return
|
|
773
|
+
if cmd == "attach" or cmd.startswith("attach "):
|
|
774
|
+
parts = cmd.split(maxsplit=1)
|
|
775
|
+
if len(parts) < 2 or not parts[1].strip():
|
|
776
|
+
self.append_line("[ERR] Usage: attach <box_id_or_name>")
|
|
777
|
+
return
|
|
778
|
+
target = parts[1].strip()
|
|
779
|
+
self.attach_to_box(target)
|
|
780
|
+
return
|
|
781
|
+
if cmd == "cd" or cmd.startswith("cd "):
|
|
782
|
+
target = cmd[2:].strip().strip('"').strip("'")
|
|
783
|
+
if not target:
|
|
784
|
+
target = os.path.expanduser("~")
|
|
785
|
+
next_dir = os.path.abspath(os.path.join(self.cwd, target))
|
|
786
|
+
if os.path.isdir(next_dir):
|
|
787
|
+
self.cwd = next_dir
|
|
788
|
+
self.title = os.path.basename(next_dir) or next_dir
|
|
789
|
+
self.append_line(f"-> {self.cwd}")
|
|
790
|
+
else:
|
|
791
|
+
self.append_line(f"[ERR] Directory not found: {next_dir}")
|
|
792
|
+
return
|
|
793
|
+
is_windows = platform.system().lower().startswith("win")
|
|
794
|
+
if cmd.startswith("ps "):
|
|
795
|
+
ps_cmd = cmd[3:].strip()
|
|
796
|
+
exec_args = (
|
|
797
|
+
["powershell", "-NoProfile", "-Command", ps_cmd]
|
|
798
|
+
if is_windows
|
|
799
|
+
else ["pwsh", "-NoProfile", "-Command", ps_cmd]
|
|
800
|
+
)
|
|
801
|
+
elif cmd.startswith("cmd "):
|
|
802
|
+
sub_cmd = cmd[4:].strip()
|
|
803
|
+
exec_args = ["cmd.exe", "/c", sub_cmd] if is_windows else ["/bin/sh", "-c", sub_cmd]
|
|
804
|
+
else:
|
|
805
|
+
exec_args = ["cmd.exe", "/c", cmd] if is_windows else ["/bin/sh", "-c", cmd]
|
|
806
|
+
env = os.environ.copy()
|
|
807
|
+
env["PYTHONUTF8"] = "1"
|
|
808
|
+
env["PYTHONIOENCODING"] = "utf-8"
|
|
809
|
+
env["PYTHONUNBUFFERED"] = "1"
|
|
810
|
+
self._stream_process_async(
|
|
811
|
+
exec_args=exec_args,
|
|
812
|
+
cwd=self.cwd,
|
|
813
|
+
env=env,
|
|
814
|
+
start_msg=f"[CMD RUN] {cmd}",
|
|
815
|
+
done_prefix="CMD",
|
|
816
|
+
from_editor=False,
|
|
817
|
+
)
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
class ProjectCatTerminalApp:
|
|
821
|
+
def __init__(self, version: str) -> None:
|
|
822
|
+
self.version = version
|
|
823
|
+
self.cfg = load_config()
|
|
824
|
+
self.mode: str = self.cfg.layout_mode if self.cfg.layout_mode in ("grid", "tabs") else "grid"
|
|
825
|
+
self.panes: list[TerminalPane] = []
|
|
826
|
+
self.active_index: int = 0
|
|
827
|
+
self.exit_prompt_open: bool = False
|
|
828
|
+
self.exit_choice_index: int = 0
|
|
829
|
+
self.kill_parent_on_exit: bool = False
|
|
830
|
+
self.is_fullscreen: bool = False
|
|
831
|
+
self.app: Application | None = None
|
|
832
|
+
self._loop: asyncio.AbstractEventLoop | None = None
|
|
833
|
+
|
|
834
|
+
first_pane = self._create_pane(pane_id=1, cwd=os.getcwd())
|
|
835
|
+
self.panes.append(first_pane)
|
|
836
|
+
self.header_window = Window(
|
|
837
|
+
content=FormattedTextControl(self._render_header),
|
|
838
|
+
height=1,
|
|
839
|
+
style="class:header",
|
|
840
|
+
)
|
|
841
|
+
self.tab_bar_window = Window(
|
|
842
|
+
content=FormattedTextControl(self._render_tab_bar),
|
|
843
|
+
height=1,
|
|
844
|
+
style="class:tabbar",
|
|
845
|
+
)
|
|
846
|
+
self.body_container = HSplit(
|
|
847
|
+
[self._build_body()],
|
|
848
|
+
height=Dimension(min=6, weight=1),
|
|
849
|
+
)
|
|
850
|
+
base_layout = HSplit(
|
|
851
|
+
[self.header_window, self.tab_bar_window, self.body_container],
|
|
852
|
+
height=Dimension(min=8, weight=1),
|
|
853
|
+
)
|
|
854
|
+
self.modal_window = Window(
|
|
855
|
+
content=FormattedTextControl(self._render_exit_modal),
|
|
856
|
+
width=60,
|
|
857
|
+
height=9,
|
|
858
|
+
style="class:modal",
|
|
859
|
+
)
|
|
860
|
+
self.modal_container = ConditionalContainer(
|
|
861
|
+
content=self.modal_window,
|
|
862
|
+
filter=Condition(lambda: self.exit_prompt_open),
|
|
863
|
+
)
|
|
864
|
+
self.root_container = FloatContainer(
|
|
865
|
+
content=base_layout,
|
|
866
|
+
floats=[
|
|
867
|
+
Float(content=self.modal_container),
|
|
868
|
+
],
|
|
869
|
+
)
|
|
870
|
+
self.layout = Layout(self.root_container)
|
|
871
|
+
self.kb = self._build_keybindings()
|
|
872
|
+
self.style = Style.from_dict(
|
|
873
|
+
{
|
|
874
|
+
"header": "bg:#141414 fg:#ffffff bold",
|
|
875
|
+
"tabbar": "bg:#1c1c1c fg:#ffffff",
|
|
876
|
+
"tab-active": "bg:#323232 fg:#ffffff bold",
|
|
877
|
+
"tab-inactive": "bg:#141414 fg:#bbbbbb",
|
|
878
|
+
"pane-active": "bg:#1e1e1e border:#ffffff",
|
|
879
|
+
"pane-inactive": "bg:#0b0b0b border:#3a3a3a",
|
|
880
|
+
"pane-active-body": "bg:#1e1e1e",
|
|
881
|
+
"pane-inactive-body": "bg:#0b0b0b",
|
|
882
|
+
"pane-divider": "fg:#3a3a3a",
|
|
883
|
+
"meta": "fg:#999999",
|
|
884
|
+
"cmd": "fg:#ff4d67 bold",
|
|
885
|
+
"out": "fg:#e6e6e6",
|
|
886
|
+
"err": "fg:#ff3b5c bold",
|
|
887
|
+
"modal": "bg:#141414 fg:#ffffff border:#ff1635",
|
|
888
|
+
"modal-title": "bg:#ff1635 fg:#ffffff bold",
|
|
889
|
+
"modal-selected": "bg:#2a2a2a fg:#ffffff bold",
|
|
890
|
+
"modal-option": "bg:#141414 fg:#cccccc",
|
|
891
|
+
"vim-header": "bg:#242424 fg:#ffffff bold",
|
|
892
|
+
"vim-lineno": "fg:#666666",
|
|
893
|
+
"vim-text": "fg:#f2f2f2",
|
|
894
|
+
"vim-cursor": "bg:#ffffff fg:#000000 bold",
|
|
895
|
+
"vim-status": "bg:#181818 fg:#ffffff",
|
|
896
|
+
}
|
|
897
|
+
)
|
|
898
|
+
self._focus_active_pane()
|
|
899
|
+
|
|
900
|
+
def _invalidate_safe(self) -> None:
|
|
901
|
+
app = self.app
|
|
902
|
+
if app is None:
|
|
903
|
+
return
|
|
904
|
+
loop = self._loop
|
|
905
|
+
if loop is not None and not loop.is_closed():
|
|
906
|
+
try:
|
|
907
|
+
loop.call_soon_threadsafe(app.invalidate)
|
|
908
|
+
return
|
|
909
|
+
except Exception:
|
|
910
|
+
pass
|
|
911
|
+
try:
|
|
912
|
+
app.invalidate()
|
|
913
|
+
except Exception:
|
|
914
|
+
pass
|
|
915
|
+
|
|
916
|
+
def _start_ui_ticker(self, stop_event: threading.Event) -> None:
|
|
917
|
+
def _tick() -> None:
|
|
918
|
+
while not stop_event.is_set():
|
|
919
|
+
self._invalidate_safe()
|
|
920
|
+
stop_event.wait(0.05)
|
|
921
|
+
|
|
922
|
+
threading.Thread(target=_tick, daemon=True).start()
|
|
923
|
+
|
|
924
|
+
def _current_pane(self) -> TerminalPane:
|
|
925
|
+
return self.panes[self.active_index]
|
|
926
|
+
|
|
927
|
+
def _create_pane(self, pane_id: int, cwd: str) -> TerminalPane:
|
|
928
|
+
pane = TerminalPane(pane_id=pane_id, cwd=cwd, _refresh_cb=self._invalidate_safe)
|
|
929
|
+
|
|
930
|
+
def _on_accept(buf: Buffer) -> bool:
|
|
931
|
+
if self.exit_prompt_open:
|
|
932
|
+
return True
|
|
933
|
+
text = buf.text
|
|
934
|
+
buf.reset()
|
|
935
|
+
if pane.box_client is not None:
|
|
936
|
+
pane.send_box_input(text)
|
|
937
|
+
return True
|
|
938
|
+
if pane.editor.active:
|
|
939
|
+
if pane.editor.mode == "CMD":
|
|
940
|
+
exited = pane.execute_editor_cmd(text)
|
|
941
|
+
if exited:
|
|
942
|
+
pane.scroll_to_bottom()
|
|
943
|
+
else:
|
|
944
|
+
pane.editor.insert_newline()
|
|
945
|
+
self._invalidate_safe()
|
|
946
|
+
return True
|
|
947
|
+
pane.execute(text)
|
|
948
|
+
self._invalidate_safe()
|
|
949
|
+
return True
|
|
950
|
+
|
|
951
|
+
pane.input_area.accept_handler = _on_accept
|
|
952
|
+
return pane
|
|
953
|
+
|
|
954
|
+
def toggle_mode(self) -> None:
|
|
955
|
+
self.mode = "tabs" if self.mode == "grid" else "grid"
|
|
956
|
+
self.cfg.layout_mode = self.mode
|
|
957
|
+
save_config(self.cfg)
|
|
958
|
+
self._rebuild_layout()
|
|
959
|
+
self._focus_active_pane()
|
|
960
|
+
self._invalidate_safe()
|
|
961
|
+
|
|
962
|
+
def add_pane(self, focus: bool = True) -> None:
|
|
963
|
+
next_id = max((p.pane_id for p in self.panes), default=0) + 1
|
|
964
|
+
base_cwd = self._current_pane().cwd if self.panes else os.getcwd()
|
|
965
|
+
pane = self._create_pane(pane_id=next_id, cwd=base_cwd)
|
|
966
|
+
self.panes.append(pane)
|
|
967
|
+
if focus:
|
|
968
|
+
self.active_index = len(self.panes) - 1
|
|
969
|
+
self._rebuild_layout()
|
|
970
|
+
self._focus_active_pane()
|
|
971
|
+
self._invalidate_safe()
|
|
972
|
+
|
|
973
|
+
def close_current_pane(self) -> None:
|
|
974
|
+
if len(self.panes) <= 1:
|
|
975
|
+
self.exit_prompt_open = True
|
|
976
|
+
self.exit_choice_index = 0
|
|
977
|
+
self._invalidate_safe()
|
|
978
|
+
return
|
|
979
|
+
self.panes[self.active_index].terminate_running_proc()
|
|
980
|
+
del self.panes[self.active_index]
|
|
981
|
+
if self.active_index >= len(self.panes):
|
|
982
|
+
self.active_index = len(self.panes) - 1
|
|
983
|
+
self._rebuild_layout()
|
|
984
|
+
self._focus_active_pane()
|
|
985
|
+
self._invalidate_safe()
|
|
986
|
+
|
|
987
|
+
def move_focus(self, direction: str) -> None:
|
|
988
|
+
count = len(self.panes)
|
|
989
|
+
if count <= 1:
|
|
990
|
+
return
|
|
991
|
+
if self.mode == "tabs":
|
|
992
|
+
if direction in ("left", "up"):
|
|
993
|
+
self.active_index = (self.active_index - 1) % count
|
|
994
|
+
elif direction in ("right", "down"):
|
|
995
|
+
self.active_index = (self.active_index + 1) % count
|
|
996
|
+
self._rebuild_layout()
|
|
997
|
+
self._focus_active_pane()
|
|
998
|
+
self._invalidate_safe()
|
|
999
|
+
return
|
|
1000
|
+
cols = max(1, math.ceil(math.sqrt(count)))
|
|
1001
|
+
row = self.active_index // cols
|
|
1002
|
+
col = self.active_index % cols
|
|
1003
|
+
if direction == "left":
|
|
1004
|
+
col = max(0, col - 1)
|
|
1005
|
+
elif direction == "right":
|
|
1006
|
+
col = min(cols - 1, col + 1)
|
|
1007
|
+
elif direction == "up":
|
|
1008
|
+
row = max(0, row - 1)
|
|
1009
|
+
elif direction == "down":
|
|
1010
|
+
row = min((count - 1) // cols, row + 1)
|
|
1011
|
+
candidate = row * cols + col
|
|
1012
|
+
if candidate < count:
|
|
1013
|
+
self.active_index = candidate
|
|
1014
|
+
elif direction in ("right", "down"):
|
|
1015
|
+
self.active_index = min(count - 1, self.active_index + 1)
|
|
1016
|
+
elif direction in ("left", "up"):
|
|
1017
|
+
self.active_index = max(0, self.active_index - 1)
|
|
1018
|
+
self._rebuild_layout()
|
|
1019
|
+
self._focus_active_pane()
|
|
1020
|
+
self._invalidate_safe()
|
|
1021
|
+
|
|
1022
|
+
def _focus_active_pane(self) -> None:
|
|
1023
|
+
if 0 <= self.active_index < len(self.panes):
|
|
1024
|
+
target_control = self.panes[self.active_index].input_area.control
|
|
1025
|
+
try:
|
|
1026
|
+
self.layout.focus(target_control)
|
|
1027
|
+
except Exception:
|
|
1028
|
+
pass
|
|
1029
|
+
|
|
1030
|
+
def _build_grid(self) -> HSplit:
|
|
1031
|
+
count = len(self.panes)
|
|
1032
|
+
cols = max(1, math.ceil(math.sqrt(count)))
|
|
1033
|
+
rows: list[VSplit] = []
|
|
1034
|
+
for r_start in range(0, count, cols):
|
|
1035
|
+
chunk = self.panes[r_start : r_start + cols]
|
|
1036
|
+
row_items = []
|
|
1037
|
+
for idx_offset, pane in enumerate(chunk):
|
|
1038
|
+
global_idx = r_start + idx_offset
|
|
1039
|
+
is_active = global_idx == self.active_index
|
|
1040
|
+
border_style = "class:pane-active" if is_active else "class:pane-inactive"
|
|
1041
|
+
body_style = "class:pane-active-body" if is_active else "class:pane-inactive-body"
|
|
1042
|
+
row_items.append(
|
|
1043
|
+
HSplit(
|
|
1044
|
+
[HSplit([pane.container], style=body_style)],
|
|
1045
|
+
style=border_style,
|
|
1046
|
+
padding=0,
|
|
1047
|
+
height=Dimension(min=6, weight=1),
|
|
1048
|
+
width=Dimension(min=16, weight=1),
|
|
1049
|
+
)
|
|
1050
|
+
)
|
|
1051
|
+
rows.append(
|
|
1052
|
+
VSplit(
|
|
1053
|
+
row_items,
|
|
1054
|
+
padding=1,
|
|
1055
|
+
height=Dimension(min=6, weight=1),
|
|
1056
|
+
)
|
|
1057
|
+
)
|
|
1058
|
+
return HSplit(rows, padding=0, height=Dimension(min=6, weight=1))
|
|
1059
|
+
|
|
1060
|
+
def _build_body(self) -> HSplit:
|
|
1061
|
+
if self.mode == "tabs":
|
|
1062
|
+
return HSplit([self._current_pane().container], height=Dimension(min=6, weight=1))
|
|
1063
|
+
return self._build_grid()
|
|
1064
|
+
|
|
1065
|
+
def _render_header(self) -> FormattedText:
|
|
1066
|
+
active_pane = self._current_pane()
|
|
1067
|
+
mode_label = "GRID" if self.mode == "grid" else "TABS"
|
|
1068
|
+
ed_suffix = ""
|
|
1069
|
+
if active_pane.editor.active:
|
|
1070
|
+
ed_suffix = f" | ED:{active_pane.editor.mode} (Ctrl+I)"
|
|
1071
|
+
text = (
|
|
1072
|
+
f" PROJECT CAT TERMINAL v{self.version} | Mode: {mode_label} (Ctrl+T) | "
|
|
1073
|
+
f"Panes: {len(self.panes)} | Focus: #{active_pane.pane_id}{ed_suffix} | "
|
|
1074
|
+
f"Ctrl+N: +pane | Ctrl+D: close | Ctrl+U/J: scroll | Ctrl+K: bottom "
|
|
1075
|
+
)
|
|
1076
|
+
return FormattedText([("class:header", text)])
|
|
1077
|
+
|
|
1078
|
+
def _render_tab_bar(self) -> FormattedText:
|
|
1079
|
+
tokens: list[tuple[str, str]] = [("class:tabbar", " Tabs: ")]
|
|
1080
|
+
for idx, pane in enumerate(self.panes):
|
|
1081
|
+
style = "class:tab-active" if idx == self.active_index else "class:tab-inactive"
|
|
1082
|
+
marker = "*" if idx == self.active_index else " "
|
|
1083
|
+
tokens.append((style, f"[{marker}#{pane.pane_id} {pane.title}]"))
|
|
1084
|
+
tokens.append(("class:tabbar", " "))
|
|
1085
|
+
return FormattedText(tokens)
|
|
1086
|
+
|
|
1087
|
+
def _render_exit_modal(self) -> FormattedText:
|
|
1088
|
+
opt0_style = "class:modal-selected" if self.exit_choice_index == 0 else "class:modal-option"
|
|
1089
|
+
opt1_style = "class:modal-selected" if self.exit_choice_index == 1 else "class:modal-option"
|
|
1090
|
+
mark0 = ">" if self.exit_choice_index == 0 else " "
|
|
1091
|
+
mark1 = ">" if self.exit_choice_index == 1 else " "
|
|
1092
|
+
return FormattedText(
|
|
1093
|
+
[
|
|
1094
|
+
("class:modal-title", " CLOSE LAST TERMINAL \n"),
|
|
1095
|
+
("class:modal", "\n"),
|
|
1096
|
+
("class:modal", " Only one terminal pane is open. Choose an action: \n"),
|
|
1097
|
+
("class:modal", "\n"),
|
|
1098
|
+
(opt0_style, f" {mark0} [1] Close pcat only (return to CMD) \n"),
|
|
1099
|
+
(opt1_style, f" {mark1} [2] Close CMD completely \n"),
|
|
1100
|
+
("class:modal", "\n"),
|
|
1101
|
+
("class:meta", " Up/Down or 1/2 — select | Enter — confirm | Esc — cancel\n"),
|
|
1102
|
+
]
|
|
1103
|
+
)
|
|
1104
|
+
|
|
1105
|
+
def _rebuild_layout(self) -> None:
|
|
1106
|
+
self.body_container.children = [self._build_body()]
|
|
1107
|
+
|
|
1108
|
+
def _confirm_exit_modal(self, event) -> None:
|
|
1109
|
+
self.kill_parent_on_exit = self.exit_choice_index == 1
|
|
1110
|
+
self.exit_prompt_open = False
|
|
1111
|
+
for p in self.panes:
|
|
1112
|
+
p.terminate_running_proc()
|
|
1113
|
+
event.app.exit()
|
|
1114
|
+
|
|
1115
|
+
def _build_keybindings(self) -> KeyBindings:
|
|
1116
|
+
kb = KeyBindings()
|
|
1117
|
+
in_modal = Condition(lambda: self.exit_prompt_open)
|
|
1118
|
+
not_in_modal = Condition(lambda: not self.exit_prompt_open)
|
|
1119
|
+
in_editor = Condition(lambda: not self.exit_prompt_open and self._current_pane().editor.active)
|
|
1120
|
+
in_editor_edit = Condition(
|
|
1121
|
+
lambda: not self.exit_prompt_open
|
|
1122
|
+
and self._current_pane().editor.active
|
|
1123
|
+
and self._current_pane().editor.mode == "EDIT"
|
|
1124
|
+
)
|
|
1125
|
+
normal_term = Condition(
|
|
1126
|
+
lambda: not self.exit_prompt_open and not self._current_pane().editor.active
|
|
1127
|
+
)
|
|
1128
|
+
|
|
1129
|
+
@kb.add("up", filter=in_modal)
|
|
1130
|
+
@kb.add("down", filter=in_modal)
|
|
1131
|
+
def _(event) -> None:
|
|
1132
|
+
self.exit_choice_index = 1 - self.exit_choice_index
|
|
1133
|
+
event.app.invalidate()
|
|
1134
|
+
|
|
1135
|
+
@kb.add("1", filter=in_modal)
|
|
1136
|
+
def _(event) -> None:
|
|
1137
|
+
self.exit_choice_index = 0
|
|
1138
|
+
self._confirm_exit_modal(event)
|
|
1139
|
+
|
|
1140
|
+
@kb.add("2", filter=in_modal)
|
|
1141
|
+
def _(event) -> None:
|
|
1142
|
+
self.exit_choice_index = 1
|
|
1143
|
+
self._confirm_exit_modal(event)
|
|
1144
|
+
|
|
1145
|
+
@kb.add("enter", filter=in_modal)
|
|
1146
|
+
def _(event) -> None:
|
|
1147
|
+
self._confirm_exit_modal(event)
|
|
1148
|
+
|
|
1149
|
+
@kb.add("escape", filter=in_modal)
|
|
1150
|
+
@kb.add("c-d", filter=in_modal)
|
|
1151
|
+
def _(event) -> None:
|
|
1152
|
+
self.exit_prompt_open = False
|
|
1153
|
+
self._focus_active_pane()
|
|
1154
|
+
event.app.invalidate()
|
|
1155
|
+
|
|
1156
|
+
@kb.add("c-i", filter=in_editor)
|
|
1157
|
+
def _(event) -> None:
|
|
1158
|
+
pane = self._current_pane()
|
|
1159
|
+
pane.editor.toggle_mode()
|
|
1160
|
+
pane.input_area.buffer.reset()
|
|
1161
|
+
event.app.invalidate()
|
|
1162
|
+
|
|
1163
|
+
@kb.add("left", filter=in_editor_edit)
|
|
1164
|
+
def _(event) -> None:
|
|
1165
|
+
self._current_pane().editor.move_left()
|
|
1166
|
+
event.app.invalidate()
|
|
1167
|
+
|
|
1168
|
+
@kb.add("right", filter=in_editor_edit)
|
|
1169
|
+
def _(event) -> None:
|
|
1170
|
+
self._current_pane().editor.move_right()
|
|
1171
|
+
event.app.invalidate()
|
|
1172
|
+
|
|
1173
|
+
@kb.add("up", filter=in_editor_edit)
|
|
1174
|
+
def _(event) -> None:
|
|
1175
|
+
self._current_pane().editor.move_up()
|
|
1176
|
+
event.app.invalidate()
|
|
1177
|
+
|
|
1178
|
+
@kb.add("down", filter=in_editor_edit)
|
|
1179
|
+
def _(event) -> None:
|
|
1180
|
+
self._current_pane().editor.move_down()
|
|
1181
|
+
event.app.invalidate()
|
|
1182
|
+
|
|
1183
|
+
@kb.add("backspace", filter=in_editor_edit)
|
|
1184
|
+
def _(event) -> None:
|
|
1185
|
+
self._current_pane().editor.backspace()
|
|
1186
|
+
event.app.invalidate()
|
|
1187
|
+
|
|
1188
|
+
@kb.add("delete", filter=in_editor_edit)
|
|
1189
|
+
def _(event) -> None:
|
|
1190
|
+
self._current_pane().editor.delete_forward()
|
|
1191
|
+
event.app.invalidate()
|
|
1192
|
+
|
|
1193
|
+
@kb.add("c-v", filter=in_editor_edit)
|
|
1194
|
+
def _(event) -> None:
|
|
1195
|
+
pasted = _get_clipboard_text()
|
|
1196
|
+
if pasted:
|
|
1197
|
+
self._current_pane().editor.insert_text(pasted)
|
|
1198
|
+
event.app.invalidate()
|
|
1199
|
+
|
|
1200
|
+
@kb.add("<any>", filter=in_editor_edit)
|
|
1201
|
+
def _(event) -> None:
|
|
1202
|
+
if event.data and event.data.isprintable():
|
|
1203
|
+
self._current_pane().editor.insert_char(event.data)
|
|
1204
|
+
event.app.invalidate()
|
|
1205
|
+
|
|
1206
|
+
@kb.add("c-v", filter=normal_term)
|
|
1207
|
+
def _(event) -> None:
|
|
1208
|
+
pasted = _get_clipboard_text()
|
|
1209
|
+
if not pasted:
|
|
1210
|
+
return
|
|
1211
|
+
clean = pasted.replace("\r\n", " ").replace("\n", " ")
|
|
1212
|
+
buf = self._current_pane().input_area.buffer
|
|
1213
|
+
buf.insert_text(clean)
|
|
1214
|
+
event.app.invalidate()
|
|
1215
|
+
|
|
1216
|
+
@kb.add("f11")
|
|
1217
|
+
def _(event) -> None:
|
|
1218
|
+
self.is_fullscreen = _toggle_console_fullscreen_state(self.is_fullscreen)
|
|
1219
|
+
event.app.invalidate()
|
|
1220
|
+
|
|
1221
|
+
@kb.add("up", filter=normal_term)
|
|
1222
|
+
def _(event) -> None:
|
|
1223
|
+
self._current_pane().history_prev()
|
|
1224
|
+
event.app.invalidate()
|
|
1225
|
+
|
|
1226
|
+
@kb.add("down", filter=normal_term)
|
|
1227
|
+
def _(event) -> None:
|
|
1228
|
+
self._current_pane().history_next()
|
|
1229
|
+
event.app.invalidate()
|
|
1230
|
+
|
|
1231
|
+
@kb.add("c-n", filter=not_in_modal)
|
|
1232
|
+
def _(event) -> None:
|
|
1233
|
+
self.add_pane(focus=True)
|
|
1234
|
+
|
|
1235
|
+
@kb.add("c-d", filter=not_in_modal)
|
|
1236
|
+
def _(event) -> None:
|
|
1237
|
+
self.close_current_pane()
|
|
1238
|
+
|
|
1239
|
+
@kb.add("c-t", filter=not_in_modal)
|
|
1240
|
+
def _(event) -> None:
|
|
1241
|
+
self.toggle_mode()
|
|
1242
|
+
|
|
1243
|
+
@kb.add("c-left", filter=not_in_modal)
|
|
1244
|
+
def _(event) -> None:
|
|
1245
|
+
self.move_focus("left")
|
|
1246
|
+
|
|
1247
|
+
@kb.add("c-right", filter=not_in_modal)
|
|
1248
|
+
def _(event) -> None:
|
|
1249
|
+
self.move_focus("right")
|
|
1250
|
+
|
|
1251
|
+
@kb.add("c-up", filter=not_in_modal)
|
|
1252
|
+
def _(event) -> None:
|
|
1253
|
+
self.move_focus("up")
|
|
1254
|
+
|
|
1255
|
+
@kb.add("c-down", filter=not_in_modal)
|
|
1256
|
+
def _(event) -> None:
|
|
1257
|
+
self.move_focus("down")
|
|
1258
|
+
|
|
1259
|
+
@kb.add("c-u", filter=normal_term)
|
|
1260
|
+
def _(event) -> None:
|
|
1261
|
+
self._current_pane().scroll_up(step=5)
|
|
1262
|
+
event.app.invalidate()
|
|
1263
|
+
|
|
1264
|
+
@kb.add("c-j", filter=normal_term)
|
|
1265
|
+
def _(event) -> None:
|
|
1266
|
+
self._current_pane().scroll_down(step=5)
|
|
1267
|
+
event.app.invalidate()
|
|
1268
|
+
|
|
1269
|
+
@kb.add("escape", "u", filter=normal_term)
|
|
1270
|
+
def _(event) -> None:
|
|
1271
|
+
self._current_pane().scroll_up(step=25)
|
|
1272
|
+
event.app.invalidate()
|
|
1273
|
+
|
|
1274
|
+
@kb.add("escape", "j", filter=normal_term)
|
|
1275
|
+
def _(event) -> None:
|
|
1276
|
+
self._current_pane().scroll_down(step=25)
|
|
1277
|
+
event.app.invalidate()
|
|
1278
|
+
|
|
1279
|
+
@kb.add("c-k", filter=normal_term)
|
|
1280
|
+
def _(event) -> None:
|
|
1281
|
+
self._current_pane().scroll_to_bottom()
|
|
1282
|
+
event.app.invalidate()
|
|
1283
|
+
|
|
1284
|
+
@kb.add("c-q", filter=not_in_modal)
|
|
1285
|
+
def _(event) -> None:
|
|
1286
|
+
for p in self.panes:
|
|
1287
|
+
p.terminate_running_proc()
|
|
1288
|
+
event.app.exit()
|
|
1289
|
+
|
|
1290
|
+
return kb
|
|
1291
|
+
|
|
1292
|
+
def run(self) -> None:
|
|
1293
|
+
loop = asyncio.new_event_loop()
|
|
1294
|
+
self._loop = loop
|
|
1295
|
+
asyncio.set_event_loop(loop)
|
|
1296
|
+
stop_ticker = threading.Event()
|
|
1297
|
+
|
|
1298
|
+
self.app = Application(
|
|
1299
|
+
layout=self.layout,
|
|
1300
|
+
key_bindings=self.kb,
|
|
1301
|
+
style=self.style,
|
|
1302
|
+
full_screen=True,
|
|
1303
|
+
mouse_support=False,
|
|
1304
|
+
)
|
|
1305
|
+
self._focus_active_pane()
|
|
1306
|
+
self._start_ui_ticker(stop_ticker)
|
|
1307
|
+
try:
|
|
1308
|
+
self.app.run()
|
|
1309
|
+
finally:
|
|
1310
|
+
stop_ticker.set()
|
|
1311
|
+
self._loop = None
|
|
1312
|
+
try:
|
|
1313
|
+
loop.close()
|
|
1314
|
+
except Exception:
|
|
1315
|
+
pass
|
|
1316
|
+
if self.kill_parent_on_exit and platform.system().lower().startswith("win"):
|
|
1317
|
+
_close_parent_console_windows()
|
|
1318
|
+
|
|
1319
|
+
|
|
1320
|
+
def run_project_cat_terminal(version: str = "0.2.0") -> None:
|
|
1321
|
+
ProjectCatTerminalApp(version=version).run()
|