-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli_client.py
More file actions
executable file
·304 lines (272 loc) · 12.7 KB
/
cli_client.py
File metadata and controls
executable file
·304 lines (272 loc) · 12.7 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
#!/usr/bin/env python3
"""
BasiCoCo - CLI Client
A standalone terminal interface for the BASIC emulator that connects to the Flask-SocketIO server.
"""
import glob
import socketio
import readline
import os
import re
import threading
from emulator.config import DEFAULT_PORT
class TRS80CLI:
def __init__(self, host='localhost', port=DEFAULT_PORT):
self.host = host
self.port = port
self.sio = socketio.Client()
self.connected = False
self.waiting_for_input = False
self.input_prompt = ""
self.input_variable = ""
self.input_metadata = {}
self.response_received = threading.Event()
self.running_program = False
self.setup_socketio_handlers()
self.setup_readline()
def setup_readline(self):
"""Configure readline for command history and editing."""
# Enable history file
histfile = os.path.join(os.path.expanduser("~"), ".trs80_history")
try:
readline.read_history_file(histfile)
readline.set_history_length(1000)
except FileNotFoundError:
pass
# Save history on exit
import atexit
atexit.register(readline.write_history_file, histfile)
# Basic tab completion for BASIC keywords and CLI commands
basic_keywords = [
'PRINT', 'LET', 'IF', 'THEN', 'ELSE', 'FOR', 'TO', 'NEXT', 'STEP',
'GOTO', 'GOSUB', 'RETURN', 'END', 'STOP', 'RUN', 'LIST', 'NEW',
'SAVE', 'LOAD', 'FILES', 'KILL', 'DELETE', 'CD', 'INPUT', 'DATA', 'READ', 'RESTORE', 'DIM',
'PSET', 'PRESET', 'PMODE', 'PCLS', 'SCREEN', 'COLOR', 'PAINT',
'LINE', 'CIRCLE', 'DRAW', 'GET', 'PUT', 'CLS', 'SOUND',
'RND', 'INT', 'ABS', 'SGN', 'SQR', 'SIN', 'COS', 'TAN', 'ATN',
'LOG', 'EXP', 'LEN', 'MID$', 'LEFT$', 'RIGHT$', 'STR$', 'VAL',
'CHR$', 'ASC', 'INKEY$', 'POS', 'PEEK', 'POKE',
'EXIT', 'QUIT', 'BYE' # CLI convenience commands
]
def get_program_names():
"""Get available .bas filenames (without extension) from programs/."""
names = []
for d in [os.getcwd(), os.path.join(os.getcwd(), 'programs')]:
if os.path.isdir(d):
for path in glob.glob(os.path.join(d, '*.bas')):
name = os.path.basename(path).removesuffix('.bas')
if name not in names:
names.append(name)
return sorted(names)
def complete(text, state):
buf = readline.get_line_buffer()
# Check for LOAD/SAVE/KILL filename context (quote optional)
file_match = re.match(r'(?:\d+\s+)?(LOAD|SAVE|KILL)\s+"?([^"]*)', buf, re.IGNORECASE)
if file_match:
partial = file_match.group(2).upper()
has_quote = '"' in buf
names = [n for n in get_program_names() if n.upper().startswith(partial)]
# Wrap completions in quotes
matches = []
for n in names:
prefix = '' if has_quote else '"'
matches.append(prefix + n + '"')
if state < len(matches):
return matches[state]
return None
matches = [cmd for cmd in basic_keywords if cmd.startswith(text.upper())]
if state < len(matches):
return matches[state]
return None
readline.set_completer(complete)
readline.set_completer_delims(' \t\n')
readline.parse_and_bind('tab: complete')
def setup_socketio_handlers(self):
"""Set up Socket.IO event handlers."""
@self.sio.event
def connect():
self.connected = True
print("Connected to BasiCoCo")
print("Type BASIC commands or programs. Press Ctrl+C to exit.")
print("=" * 60)
@self.sio.event
def disconnect():
self.connected = False
print("\nDisconnected from server")
@self.sio.event
def output(data):
"""Handle output from the BASIC emulator."""
for item in data:
if item['type'] == 'text':
if item.get('inline'):
# Handle inline text with carriage return
text = item['text']
if '\r' in text:
# Print without newline and flush
print(text.replace('\r', ''), end='', flush=True)
# Move cursor to beginning of line
print('\r', end='', flush=True)
else:
print(text, end='', flush=True)
else:
print(item['text'], flush=True)
elif item['type'] == 'error':
print(f"ERROR: {item['message']}")
elif item['type'] == 'input_request':
self.waiting_for_input = True
self.input_prompt = item.get('prompt', '?')
self.input_variable = item.get('variable', '')
# Store any additional metadata (like filename for KILL confirmation)
self.input_metadata = {k: v for k, v in item.items() if k not in ['type', 'prompt', 'variable']}
elif item['type'] == 'graphics':
# For CLI, just show that graphics command was executed
print(f"[Graphics: {item.get('command', 'unknown')}]")
elif item['type'] == 'sound':
# For CLI, just show that sound command was executed
print(f"[Sound: {item.get('frequency', 'unknown')} Hz]")
elif item['type'] == 'clear':
# Clear screen
os.system('clear' if os.name == 'posix' else 'cls')
elif item['type'] == 'pause':
# Handle non-blocking pause - schedule continuation after delay
duration = item.get('duration', 1.0)
threading.Timer(duration, self.continue_after_pause).start()
# Signal that we've received and processed the response
# Look for the universal command completion signal
has_error = any(item.get('type') == 'error' for item in data)
has_completion_signal = any(item.get('type') == 'command_complete' for item in data)
has_pause = any(item.get('type') == 'pause' for item in data)
has_input_request = any(item.get('type') == 'input_request' for item in data)
# Signal completion for: errors, explicit completion, or input requests
# Don't signal completion if we just received a pause - wait for actual completion
if (has_error or has_completion_signal or has_input_request) and not has_pause:
if self.running_program:
self.running_program = False
# Ensure all output is flushed before signaling completion
import sys
sys.stdout.flush()
# Small delay to ensure terminal output is complete
import time
time.sleep(0.01)
self.response_received.set()
# Don't signal for intermediate responses during program execution - let them stream through
def connect_to_server(self):
"""Connect to the Flask-SocketIO server."""
try:
self.sio.connect(f'http://{self.host}:{self.port}')
return True
except Exception as e:
print(f"Failed to connect to server at {self.host}:{self.port}: {e}")
return False
def send_command(self, command: str):
"""Send a command to the BASIC emulator."""
if self.connected:
# For RUN command, enable streaming mode but still wait for program completion
if command.strip().upper() == 'RUN':
self.running_program = True
self.response_received.clear()
self.sio.emit('execute_command', {'command': command})
# Wait for program to finish running (with timeout)
if not self.response_received.wait(timeout=30):
print("Program execution timed out")
self.running_program = False
else:
# For other commands, wait for complete response before next prompt
self.response_received.clear() # Reset the event
self.sio.emit('execute_command', {'command': command})
# Wait for the response to arrive and be processed
self.response_received.wait()
def send_input_response(self, value: str):
"""Send input response to the BASIC emulator."""
if self.connected and self.waiting_for_input:
# Include any metadata in the response
response = {
'variable': self.input_variable,
'value': value
}
response.update(self.input_metadata)
self.response_received.clear() # Reset the event
self.sio.emit('input_response', response)
self.waiting_for_input = False
self.input_prompt = ""
self.input_variable = ""
self.input_metadata = {}
# Wait for the response to arrive and be processed
self.response_received.wait()
def send_keypress(self, key: str):
"""Send keypress to the BASIC emulator for INKEY$ support."""
if self.connected:
self.sio.emit('keypress', {'key': key})
def send_break_signal(self):
"""Send break signal to interrupt running BASIC program."""
if self.connected:
print("BREAK")
self.sio.emit('break_execution')
self.response_received.set() # Unblock any waiting operations
def continue_after_pause(self):
"""Continue program execution after a pause completes."""
if self.connected:
self.sio.emit('continue_execution')
def run(self):
"""Main CLI loop."""
if not self.connect_to_server():
return
try:
while True:
try:
if self.waiting_for_input:
# Handle INPUT requests
prompt = f"{self.input_prompt} "
user_input = input(prompt)
self.send_input_response(user_input)
else:
# Normal command input
command = input("> ")
if command.strip():
# Handle local EXIT command
if command.strip().upper() in ['EXIT', 'QUIT', 'BYE']:
print("Goodbye!")
break
self.send_command(command)
except EOFError:
# Ctrl+D pressed
break
except KeyboardInterrupt:
# Ctrl+C pressed
if self.running_program or self.waiting_for_input:
# Send break signal to interrupt running BASIC program
print("\n^C")
self.send_break_signal()
# Reset states
self.running_program = False
self.waiting_for_input = False
self.input_prompt = ""
self.input_variable = ""
# Continue CLI (don't break)
else:
# No program running, exit CLI
print("\nInterrupted")
break
except Exception as e:
print(f"Error in main loop: {e}")
finally:
if self.connected:
self.sio.disconnect()
def main():
"""Entry point for the CLI client."""
import argparse
parser = argparse.ArgumentParser(description='BasiCoCo CLI Client')
parser.add_argument('--host', default='localhost',
help='Server host (default: localhost)')
parser.add_argument('--port', type=int, default=DEFAULT_PORT,
help=f'Server port (default: {DEFAULT_PORT})')
args = parser.parse_args()
# Display banner
print("BASICOCO V1.0")
print("EDUCATIONAL COLOR COMPUTER BASIC")
print("INSPIRED BY TANDY/RADIO SHACK")
print()
cli = TRS80CLI(args.host, args.port)
cli.run()
if __name__ == '__main__':
main()