-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
315 lines (254 loc) · 9.52 KB
/
main.py
File metadata and controls
315 lines (254 loc) · 9.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import argparse
import importlib.util
import random
import sys
import time
from typing import Optional
from rich.align import Align
from rich.columns import Columns
from rich.console import Console, Group
from rich.live import Live
from rich.panel import Panel
from rich.prompt import Prompt
from rich.text import Text
from src.app import WatchXApp
try:
from pyfiglet import Figlet
except ImportError:
Figlet = None
console = Console()
WATCHX_ASCII_FALLBACK = r"""
██╗ ██╗ █████╗ ████████╗ ██████╗██╗ ██╗██╗ ██╗
██║ ██║██╔══██╗╚══██╔══╝██╔════╝██║ ██║╚██╗██╔╝
██║ █╗ ██║███████║ ██║ ██║ ███████║ ╚███╔╝
██║███╗██║██╔══██║ ██║ ██║ ██╔══██║ ██╔██╗
╚███╔███╔╝██║ ██║ ██║ ╚██████╗██║ ██║██╔╝ ██╗
╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝
"""
def _render_watchx_ascii() -> str:
if Figlet is not None:
try:
return Figlet(font="sub-zero", width=200).renderText("WATCHX")
except Exception:
pass
return WATCHX_ASCII_FALLBACK
WATCHX_ASCII = _render_watchx_ascii()
def _glitch_title_to_digits(ascii_text: str) -> str:
return "".join(
random.choice("0123456789") if ch not in {" ", "\n"} else ch
for ch in ascii_text
)
def _blank_title_shape(ascii_text: str) -> str:
return "".join(" " if ch != "\n" else "\n" for ch in ascii_text)
def _build_landing(title_mode: str = "normal", command_buffer: str = "", frame: int = 0):
if title_mode == "blank":
title_text = _blank_title_shape(WATCHX_ASCII)
elif title_mode == "digits":
title_text = _glitch_title_to_digits(WATCHX_ASCII)
else:
title_text = WATCHX_ASCII
title = Text(title_text, style="bold cyan")
subtitle = Text("Terminal Command Center", style="bold magenta")
byline = Text("Live System Insights", style="bright_black")
cursor = "▌" if frame % 2 == 0 else " "
left = Panel(
Group(
Align.center(title),
Align.center(subtitle),
Align.center(byline),
),
title="WatchX",
border_style="cyan",
)
commands = Text.from_markup(
"\n".join(
[
"[bold yellow]Commands[/bold yellow]",
"[green]start[/green] / [green]run[/green] Launch monitor",
"[green]help[/green] Command guide",
"[green]health[/green] Runtime diagnostics",
"[green]about[/green] Project info",
"[green]clear[/green] Redraw screen",
"[green]quit[/green] Exit launcher",
]
)
)
prompt = Text(f"watchx> {command_buffer}{cursor}", style="bold cyan")
right = Panel(
Group(
commands,
Text("\n"),
Text("\n"),
Text("Input", style="bold magenta"),
prompt,
),
title="Console",
border_style="bright_blue",
)
return Columns(
[left, right],
equal=False,
expand=True,
)
def _show_landing() -> None:
console.print(_build_landing("normal", "", 0))
def _hard_clear_terminal() -> None:
"""Clear visible screen and, where supported, clear terminal scrollback."""
console.clear()
try:
# ESC[2J: clear screen, ESC[3J: clear scrollback, ESC[H: cursor home
console.file.write("\x1b[2J\x1b[3J\x1b[H")
console.file.flush()
except Exception:
pass
def _read_char_nonblocking() -> Optional[str]:
try:
import msvcrt
if not msvcrt.kbhit():
return None
char = msvcrt.getwch()
if char in {"\r", "\n"}:
return "ENTER"
if char == "\x08":
return "BACKSPACE"
if char in {"\x00", "\xe0"}:
msvcrt.getwch()
return None
if char == "\x03":
raise KeyboardInterrupt
return char
except ImportError:
return None
def _animated_command_input(start_frame: int = 0, fps: int = 12) -> tuple[str, int]:
sequence = (["normal"] * 8) + (["digits"] * 6) + (["blank"] * 3) + (["digits"] * 4) + (["normal"] * 7)
frame = start_frame
command_buffer = ""
with Live(console=console, refresh_per_second=fps, screen=False) as live:
while True:
mode = sequence[frame % len(sequence)]
live.update(_build_landing(mode, command_buffer, frame))
frame += 1
key = _read_char_nonblocking()
if key is None:
time.sleep(1 / fps)
continue
if key == "ENTER":
return command_buffer.strip().lower(), frame
if key == "BACKSPACE":
command_buffer = command_buffer[:-1]
continue
if key.isprintable():
command_buffer += key
def _show_help() -> None:
help_text = Text.from_markup(
"\n".join(
[
"[bold cyan]WatchX Commands[/bold cyan]",
"[green]start[/green] / [green]run[/green] Launch system monitor",
"[green]help[/green] Show this command guide",
"[green]health[/green] Show Python/dependency/terminal diagnostics",
"[green]about[/green] Show project info",
"[green]clear[/green] Clear terminal and redraw landing",
"[green]quit[/green] / [green]exit[/green] Exit WatchX launcher",
]
)
)
console.print(Panel(help_text, title="Usage", border_style="cyan"))
def _show_health() -> None:
dependencies = [
("psutil", "psutil"),
("gputil", "GPUtil"),
("rich", "rich"),
("textual", "textual"),
("pyfiglet", "pyfiglet"),
]
dep_lines = []
for dep_label, module_name in dependencies:
available = importlib.util.find_spec(module_name) is not None
icon = "✅" if available else "❌"
dep_lines.append(f"{icon} {dep_label}")
terminal_type = "TTY" if console.is_terminal else "Non-TTY"
color_support = str(console.color_system or "none")
unicode_ok = "Yes" if console.encoding and "UTF" in console.encoding.upper() else "Maybe"
health_text = Text.from_markup(
"\n".join(
[
"[bold cyan]WatchX Health[/bold cyan]",
f"Python: {sys.version.split()[0]}",
f"Platform: {sys.platform}",
f"Terminal: {terminal_type}",
f"Color Support: {color_support}",
f"Unicode Support: {unicode_ok} ({console.encoding})",
"",
"[bold yellow]Dependencies[/bold yellow]",
*dep_lines,
]
)
)
console.print(Panel(health_text, title="Health", border_style="green"))
def _show_about() -> None:
about_text = Text.from_markup(
"[bold]WatchX[/bold]\n"
"Modern terminal system monitor with live metrics, process control, and multi-pane UI.\n"
"Use this launcher as a command shell, similar to CLI assistants."
)
console.print(Panel(about_text, title="About", border_style="magenta"))
def _run_shell() -> None:
frame = 0
try:
import msvcrt # noqa: F401
windows_nonblocking = True
except ImportError:
windows_nonblocking = False
while True:
if windows_nonblocking:
try:
command, frame = _animated_command_input(frame)
except KeyboardInterrupt:
console.print("\n[bold yellow]Exiting WatchX launcher. Bye![/bold yellow]")
break
else:
if frame == 0:
_show_landing()
command = Prompt.ask("[bold cyan]watchx>[/bold cyan]").strip().lower()
if command in {"start", "run", "monitor"}:
console.print("[bold green]Launching WatchX monitor...[/bold green]")
try:
WatchXApp().run()
except Exception as exc:
console.print(f"[bold red]Monitor failed:[/bold red] {exc}")
continue
if command in {"help", "?"}:
_show_help()
continue
if command == "about":
_show_about()
continue
if command == "health":
_show_health()
continue
if command == "clear":
_hard_clear_terminal()
continue
if command in {"quit", "exit"}:
console.print("[bold yellow]Exiting WatchX launcher. Bye![/bold yellow]")
break
if not command:
continue
console.print(
"[red]Unknown command.[/red] Try [bold]help[/bold] or type [bold]start[/bold] to launch monitor."
)
def main() -> None:
parser = argparse.ArgumentParser(description="WatchX launcher")
parser.add_argument(
"--direct",
action="store_true",
help="Launch monitor directly without launcher shell",
)
args = parser.parse_args()
if args.direct:
WatchXApp().run()
else:
_run_shell()
if __name__ == "__main__":
main()