-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrich_terminal_handler.py
More file actions
221 lines (182 loc) · 8.81 KB
/
Copy pathrich_terminal_handler.py
File metadata and controls
221 lines (182 loc) · 8.81 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
"""
Rich-based terminal UI handler for video servo interface.
"""
import os
import cv2
import climage
import threading
import sys
# Add the parent directory to sys.path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Import CONFIG from the parent module if possible
try:
from src.video_servo_interface import CONFIG
except ImportError:
# Default config if import fails
CONFIG = {'terminal': {'refresh_rate': 10}}
from rich.console import Console
from rich.layout import Layout
from rich.live import Live
from rich.panel import Panel
from rich.text import Text
class RichTerminalHandler:
"""Rich-based terminal handler for the video servo interface."""
def __init__(self):
"""Initialize the Rich-based terminal handler."""
self.console = Console()
self.live = None
self.status_line = ""
self.interface_shown = False
self._suppress_output = False
self.last_preview_frame = None
self.preview_mode = "normal"
self.log_file_name = ""
# Get refresh rate from config
self.refresh_rate = CONFIG.get('terminal', {}).get('refresh_rate', 10)
# Create the layout
self.layout = Layout()
# Configure layout structure
self.layout.split(
Layout(name="header", size=3),
Layout(name="controls", size=7),
Layout(name="content")
)
# Split content for preview and status
self.layout["content"].split_row(
Layout(name="preview", ratio=2),
Layout(name="status", ratio=1)
)
def suppress_output(self, suppress=True):
"""Control whether output is displayed."""
self._suppress_output = suppress
def clear_screen(self):
"""Clear the terminal screen."""
if not self._suppress_output:
self.console.clear()
self.interface_shown = False
def show_interface(self, log_file):
"""Show the initial interface."""
self.log_file_name = log_file # Store for later use
if not self.interface_shown and not self._suppress_output:
# Update header section
header_content = Text.from_markup(
f"[bold]=== Pixy2 Video Servo Control ===[/bold]\n"
f"Session log: {os.path.basename(log_file)}"
)
self.layout["header"].update(Panel(header_content))
# Update controls section
controls_content = Text.from_markup(
"Controls (work in both terminal and video window):\n"
" [bold]a[/bold]/[bold]d[/bold] : Pan left/right\n"
" [bold]w[/bold]/[bold]s[/bold] : Tilt up/down\n"
" [bold]c[/bold] : Center servos\n"
" [bold]r[/bold] : Toggle recording\n"
" [bold]p[/bold] : Toggle preview (normal > terminal > off)\n"
" [bold]q[/bold] : Quit"
)
self.layout["controls"].update(Panel(controls_content, title="Controls"))
# Initialize status section
self.layout["status"].update(Panel("Status information will appear here", title="Status"))
# Initialize preview section
self.layout["preview"].update(Panel("Preview will appear here", title="Preview"))
# Start Live display if not already started
if self.live is None:
self.live = Live(
self.layout,
console=self.console,
screen=True,
refresh_per_second=self.refresh_rate
)
self.live.start()
self.interface_shown = True
def update_status(self, status):
"""Update the status line."""
if not self._suppress_output:
self.status_line = status
# If we have a Live display, update the status panel
if self.live is not None and self.live.is_started:
self.layout["status"].update(Panel(status, title="Status"))
# No need to call refresh as Live handles updates
def show_message(self, message):
"""Show a temporary message without disturbing status."""
if not self._suppress_output:
# Temporarily show message in status area
if self.live is not None and self.live.is_started:
combined_text = Text()
combined_text.append(message)
combined_text.append("\n\n")
combined_text.append(self.status_line)
self.layout["status"].update(Panel(combined_text, title="Message"))
# Use a timer to restore the original status after 2 seconds
def restore_status():
if self.live is not None and self.live.is_started:
self.layout["status"].update(Panel(self.status_line, title="Status"))
threading.Timer(2.0, restore_status).start()
def set_preview_mode(self, mode):
"""Set the preview mode (normal, terminal, off)."""
self.preview_mode = mode
# Show a message about the mode change
mode_messages = {
"normal": "Preview mode: NORMAL (external window)",
"terminal": "Preview mode: TERMINAL (in console)",
"off": "Preview mode: OFF"
}
# Update UI based on mode
if self.preview_mode == "terminal":
# Ensure live display is started for terminal preview
if self.live is None or not self.live.is_started:
self.show_interface(self.log_file_name)
# Show message about mode change
self.show_message(mode_messages.get(mode, f"Preview mode: {mode}"))
else:
# For other modes, just show the message
self.show_message(mode_messages.get(mode, f"Preview mode: {mode}"))
def render_preview(self, frame, status_lines):
"""Render preview in terminal."""
if not self._suppress_output:
# Store current frame
if frame is not None:
self.last_preview_frame = frame.copy()
# Join status lines into a single string
status_content = "\n".join(status_lines)
# Only proceed if we have a frame and live display
if self.preview_mode == "terminal" and frame is not None and self.live is not None:
# Convert frame to ASCII art
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
resized_frame = cv2.resize(rgb_frame, (80, 40)) # Larger size for better detail
output = climage.convert_array(
resized_frame,
is_unicode=True, # Unicode provides better detail
is_8color=False,
is_256color=True, # Better color representation
is_truecolor=False
)
# Update preview panel with the ASCII art
self.layout["preview"].update(Panel(output, title="Preview"))
# Update status panel with status lines
self.layout["status"].update(Panel(status_content, title="Status"))
elif self.preview_mode in ["normal", "off"] and self.last_preview_frame is not None:
# Show inactive preview for other modes
gray_frame = cv2.cvtColor(self.last_preview_frame, cv2.COLOR_BGR2GRAY)
rgb_gray = cv2.cvtColor(gray_frame, cv2.COLOR_GRAY2RGB)
resized_frame = cv2.resize(rgb_gray, (60, 30))
# Convert with lower quality for performance
output = climage.convert_array(
resized_frame,
is_unicode=False,
is_8color=True,
is_256color=False,
is_truecolor=False
)
# Add [INACTIVE] to the status content
inactive_status = status_content
if status_lines:
lines = status_content.split("\n")
lines[0] = lines[0] + " [INACTIVE]"
inactive_status = "\n".join(lines)
# Update preview panel
self.layout["preview"].update(Panel(output, title="Preview [Inactive]"))
# Update status panel
self.layout["status"].update(Panel(inactive_status, title="Status"))
# Note: The integration with the main application will require creating a factory function
# and modifying setup_logging() to use it.