-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·648 lines (523 loc) · 26.2 KB
/
app.py
File metadata and controls
executable file
·648 lines (523 loc) · 26.2 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
from flask import Flask, render_template, request
from flask_socketio import SocketIO
import threading
import time
import random
from assembly_to_schematic import generator
import copy
import re
import webview
app = Flask(__name__)
socketio = SocketIO(app)
SAVE_PATH: str = 'saved_input.txt'
PORT: int = 5001
EXPERIMENTAL_GUI: bool = False
ZOOM_LEVEL_GUI: str = '67%'
class Simulator:
def __init__(self, speed: int):
self.REGISTERS: dict[str, str] = {f'R{i}': 16 * '0' for i in range(32)}
self.DATA_MEMORY_ADDRESSES: dict[str, str] = {f'D{i}': 16 * '0' for i in range(256)}
self.PORTS_WRITE_ONLY: dict[str, str] = {f'P{i}': 16 * '0' for i in range(8)}
self.PORTS_READ_ONLY: dict[str, str] = {f'P{i}': 16 * '0' for i in range(8)}
self.PORTS_READ_ONLY['P1']: dict[str, str] = format(random.randint(0, 65535), '016b') # Start with random 16-bit Number
self.ALU_FLAGS: dict[str, bool] = {'BEQ': False, 'BNE': False, 'BLT': False, 'BGT': False}
self.call_stack: list[str] = []
self.simulation_running: bool = False
self.program_counter: str = 16 * '0' # To not re-write int_to_bin & bin_to_int, we consider this a 16-bit Number. Doesn't change anything.
self.screen_data: list[list[int]] = [[0 for _ in range(31)] for _ in range(31)]
self.screen_buffer: list[list[int]] = [[0 for _ in range(31)] for _ in range(31)]
self.screen_d_latch_data: int = 0
self.screen_x: int = 0
self.screen_y: int = 0
self.letters_data: list[str] = ['_' for _ in range(11)]
self.letters_buffer: list[str] = ['_' for _ in range(11)]
self.letters_pointer: int = 0
self.number: str = '___'
self.big_number: str = '_____'
self.OPERATIONS: list[str] = ['NOP', 'ADD', 'SUB', 'XOR', 'OR', 'AND', 'RSH', 'ADI', 'ST', 'LD', 'PT-ST', 'PT-LD', 'JMP', 'CAL',
'RET', 'BEQ', 'BNE', 'BLT', 'BGT', 'HLT']
self.speed: int = speed
self.controller: dict[str, int] = {'UP': 0, 'RIGHT': 0, 'DOWN': 0, 'LEFT': 0, 'START': 0, 'SELECT': 0, 'Y': 0, 'X': 0}
def read_assembly_file(self) -> list[str]:
try:
with open(SAVE_PATH, 'r') as file:
return [line.strip() for line in file if line.strip()]
except FileNotFoundError:
self.display_error_message(f'Fatal Error. File "{SAVE_PATH}"was not found. Perhaps create it?')
return []
def remove_comments(self, lines: list[str]) -> list[str]:
return [line.split('#')[0].strip() for line in lines if line.split('#')[0].strip()]
def extract_definitions(self, lines: list[str]) -> dict[str, str]:
definitions = {}
for line in lines:
if line.startswith('define '):
_, key, value = line.split()
definitions[key] = value
return definitions
def replace_definitions(self, lines: list[str], definitions: dict[str, str]) -> list[str]:
result: list[str] = []
for line in lines:
tokens = line.split()
if line.startswith('define '):
continue
new_tokens: list[str] = []
for token in tokens:
if token in definitions:
new_tokens.append(definitions[token])
else:
new_tokens.append(token)
result.append(' '.join(new_tokens))
return result
def extract_labels(self, lines: list[str]) -> dict[str, str]:
labels: dict[str, str] = {}
instruction_address: int = 0
for idx, line in enumerate(lines):
parts: list[str] = line.split()
if not parts:
continue
if parts[0].startswith('.'):
label_name: str = parts[0]
if len(parts) > 1:
labels[label_name] = str(instruction_address)
instruction_address += 1
else:
labels[label_name] = str(instruction_address)
else:
instruction_address += 1
return labels
def replace_labels(self, lines: list[str], labels: dict[str, str]) -> list[str]:
result: list[str] = []
for line in lines:
tokens = line.split()
if line.startswith('.'):
if len(tokens) == 1:
continue # line is only a label, skip it
tokens = tokens[1:]
new_tokens: list[str] = []
for token in tokens:
if token in labels:
new_tokens.append(labels[token])
else:
new_tokens.append(token)
result.append(' '.join(new_tokens))
return result
def extract_characters(self, lines: list[str]) -> list[str]:
tokens_re: re.Pattern[str] = re.compile(r'"[^"]*"|\S+')
result: list[str] = []
for line in lines:
tokens = tokens_re.findall(line)
new_tokens = []
for token in tokens:
if token.startswith('"') and token.endswith('"'):
inner = token[1:-1] # content inside quotes
if len(inner) != 1:
self.display_error_message(f'Fatal Error. Character "{inner}" not in supported characters (A-Z, Space)')
return []
if self.char_to_num(inner) != '':
new_tokens.append(self.char_to_num(inner))
else:
new_tokens.append(token)
result.append(" ".join(new_tokens))
return result
def preprocess_assembly(self) -> list[str]:
lines: list[str] = self.read_assembly_file()
if not lines:
return []
lines = self.remove_comments(lines)
definitions = self.extract_definitions(lines)
lines = self.replace_definitions(lines, definitions)
labels = self.extract_labels(lines)
lines = self.replace_labels(lines, labels)
lines = self.extract_characters(lines)
return lines
def bin_to_char(self, bin_str: str) -> str:
bin_to_char: dict[str, str] = {
'00001': 'A', '00010': 'B', '00011': 'C', '00100': 'D', '00101': 'E',
'00110': 'F', '00111': 'G', '01000': 'H', '01001': 'I', '01010': 'J',
'01011': 'K', '01100': 'L', '01101': 'M', '01110': 'N', '01111': 'O',
'10000': 'P', '10001': 'Q', '10010': 'R', '10011': 'S', '10100': 'T',
'10101': 'U', '10110': 'V', '10111': 'W', '11000': 'X', '11001': 'Y',
'11010': 'Z', '00000': ' '
}
return bin_to_char[bin_str]
def char_to_num(self, char: str) -> str:
if char == ' ':
return '0'
if char.isalpha():
return str(ord(char.upper()) - ord('A') + 1)
self.display_error_message(f'Fatal Error. Character "{char}" not in supported characters (A-Z, Space)')
return '' # represents error
def bin_to_int(self, bin_str) -> int:
return int(bin_str, 2)
def int_to_bin(self, val) -> str:
return format(val & 0xFFFF, '016b')
def update_alu_flags(self, result_bin: str) -> None:
# Minecraft Implementation
self.ALU_FLAGS = {'BEQ': False, 'BNE': False, 'BLT': False, 'BGT': False}
if result_bin[0] == '1':
self.ALU_FLAGS['BLT'] = True
if result_bin == 16 * '0':
self.ALU_FLAGS['BEQ'] = True
if not self.ALU_FLAGS['BEQ']:
self.ALU_FLAGS['BNE'] = True
if self.ALU_FLAGS['BEQ'] is False and self.ALU_FLAGS['BLT'] is False:
self.ALU_FLAGS['BGT'] = True
def execute_instruction(self, instruction: str) -> None:
parts: list[str] = instruction.split()
operation: str = parts[0]
mask: int = 0xFFFF # Ensure 16 Bit Result
jump_instruction: bool = False
if operation not in self.OPERATIONS:
self.display_error_message(f'Fatal Error. Operation {operation} not in Operations {self.OPERATIONS}')
return
if operation == 'NOP':
pass
elif operation == 'ADD':
self.REGISTERS[parts[1]] = self.int_to_bin(
(self.bin_to_int(self.REGISTERS[parts[2]]) + self.bin_to_int(self.REGISTERS[parts[3]])) & mask
)
self.update_alu_flags(self.REGISTERS[parts[1]])
elif operation == 'SUB':
self.REGISTERS[parts[1]] = self.int_to_bin(
(self.bin_to_int(self.REGISTERS[parts[2]]) - self.bin_to_int(self.REGISTERS[parts[3]])) & mask
)
self.update_alu_flags(self.REGISTERS[parts[1]])
elif operation == 'XOR':
self.REGISTERS[parts[1]] = self.int_to_bin(
(self.bin_to_int(self.REGISTERS[parts[2]]) ^ self.bin_to_int(self.REGISTERS[parts[3]])) & mask
)
self.update_alu_flags(self.REGISTERS[parts[1]])
elif operation == 'OR':
self.REGISTERS[parts[1]] = self.int_to_bin(
(self.bin_to_int(self.REGISTERS[parts[2]]) | self.bin_to_int(self.REGISTERS[parts[3]])) & mask
)
self.update_alu_flags(self.REGISTERS[parts[1]])
elif operation == 'AND':
self.REGISTERS[parts[1]] = self.int_to_bin(
(self.bin_to_int(self.REGISTERS[parts[2]]) & self.bin_to_int(self.REGISTERS[parts[3]])) & mask
)
self.update_alu_flags(self.REGISTERS[parts[1]])
elif operation == 'RSH':
self.REGISTERS[parts[1]] = self.int_to_bin(
(self.bin_to_int(self.REGISTERS[parts[2]]) >> 1) & mask
)
self.update_alu_flags(self.REGISTERS[parts[1]])
elif operation == 'ADI':
self.REGISTERS[parts[1]] = self.int_to_bin(
(self.bin_to_int(self.REGISTERS[parts[2]]) + int(parts[3])) & mask
)
self.update_alu_flags(self.REGISTERS[parts[1]])
elif operation == 'ST':
self.DATA_MEMORY_ADDRESSES['D' + str(
self.bin_to_int(self.REGISTERS[parts[2]]) + int(parts[3])
)] = self.REGISTERS[parts[1]]
elif operation == 'LD':
self.REGISTERS[parts[1]] = self.DATA_MEMORY_ADDRESSES['D' + str(
self.bin_to_int(self.REGISTERS[parts[2]]) + int(parts[3])
)]
elif operation == 'PT-ST':
self.port_store(parts[2][1:], self.REGISTERS[parts[1]])
elif operation == 'PT-LD':
self.port_load(parts[2][1:], parts[1])
elif operation == 'JMP':
self.program_counter = self.int_to_bin(int(parts[1]))
jump_instruction = True
elif operation == 'CAL':
self.call_stack.append(self.int_to_bin(
self.bin_to_int(self.program_counter) + 1
))
self.program_counter = self.int_to_bin(int(parts[1]))
jump_instruction = True
elif operation == 'RET':
self.program_counter = self.call_stack.pop()
jump_instruction = True
elif operation == 'BEQ':
if self.ALU_FLAGS['BEQ']:
self.program_counter = self.int_to_bin(int(parts[1]))
jump_instruction = True
elif operation == 'BNE':
if self.ALU_FLAGS['BNE']:
self.program_counter = self.int_to_bin(int(parts[1]))
jump_instruction = True
elif operation == 'BLT':
if self.ALU_FLAGS['BLT']:
self.program_counter = self.int_to_bin(int(parts[1]))
jump_instruction = True
elif operation == 'BGT':
if self.ALU_FLAGS['BGT']:
self.program_counter = self.int_to_bin(int(parts[1]))
jump_instruction = True
elif operation == 'HLT':
self.simulation_running = False
jump_instruction = True # In case Program gets continued again, Halt will be spammed
self.PORTS_READ_ONLY['P1'] = format(random.randint(0, 65535), '016b') # Generate Random Number at Port 1 for each clock cycle
if self.REGISTERS['R0'] != 16 * '0':
self.REGISTERS['R0'] = 16 * '0' # Make sure r0 is always 0
if self.DATA_MEMORY_ADDRESSES['D0'] != 16 * '0':
self.DATA_MEMORY_ADDRESSES['D0'] = 16 * '0' # Make sure d0 is always 0
if len(self.call_stack) > 16:
self.call_stack = self.call_stack[-16:] # Max 16 Layers Deep
if not jump_instruction:
self.program_counter = self.int_to_bin(
self.bin_to_int(self.program_counter) + 1
)
def port_load(self, address: str, bin_reg_address: str) -> None:
bin_address: str = self.int_to_bin(int(address))[13:16]
value: str = 16 * '0'
if bin_address == '000':
value: str = (8 * '0' + str(self.controller['X']) + str(self.controller['Y']) +
str(self.controller['SELECT']) + str(self.controller['START']) +
str(self.controller['LEFT']) + str(self.controller['DOWN']) +
str(self.controller['RIGHT']) + str(self.controller['UP']))
self.controller = {'UP': self.controller['UP'],
'RIGHT': self.controller['RIGHT'],
'DOWN': self.controller['DOWN'],
'LEFT': self.controller['LEFT'],
'START': 0, 'SELECT': 0, 'Y': 0, 'X': 0}
# bug fix! update the controller buttons AFTER loading it to a register.
new_controller_value = (8 * '0' + str(self.controller['X']) + str(self.controller['Y']) +
str(self.controller['SELECT']) + str(self.controller['START']) +
str(self.controller['LEFT']) + str(self.controller['DOWN']) +
str(self.controller['RIGHT']) + str(self.controller['UP']))
self.PORTS_READ_ONLY[f'P{address}'] = new_controller_value
# Bit 1 (LSB): D-Pad Up
# Bit 2: D-Pad Right
# Bit 3: D-Pad Down
# Bit 4: D-Pad Left
# Bit 5: Start
# Bit 6: Select
# Bit 7: Y
# Bit 8 (MSB): X
elif bin_address == '001':
value = self.PORTS_READ_ONLY[f'P{address}']
self.REGISTERS[bin_reg_address] = value
def port_store(self, address: str, bin_value: str) -> None:
bin_address = self.int_to_bin(int(address))[13:16]
# print(f'Port Store, {address = }, {bin_value = }')
self.PORTS_WRITE_ONLY[f'P{address}'] = bin_value
if bin_address == '000': # Format: XXXXXXXXXXXXXX (14), Clear Letter Buffer (1), Update Letter Buffer (1)
if bin_value[15] == '1': # Update Letter Buffer
self.letters_data = self.letters_buffer
if bin_value[14] == '1': # Clear Letter Buffer
self.letters_pointer = 0
self.letters_buffer = self.letters_buffer = ['_' for _ in range(11)]
elif bin_address == '001': # Format: XXXXXXXXXXX (11), Character (5)
char = self.bin_to_char(bin_value[11:16])
self.letters_buffer[self.letters_pointer] = char
self.letters_pointer += 1
if self.letters_pointer > 10:
self.letters_pointer = 0
elif bin_address == '010': # Format: XXXXXX (6), Sign Mode (1), Enable (1), Number (8)
self.number = str(format(self.bin_to_int(bin_value[8:16]), '03d'))
self.big_number = str(format(self.bin_to_int(bin_value), '05d')) # <- 16 Bit Testing Display
if bin_value[6] == '1': # Sign Mode
self.number = str(format(int(self.number), '03d') if int(self.number) < 128 else format(int(self.number) - 256, '04d'))
if bin_value[7] == '0': # Disable
self.number = '___'
elif bin_address == '011': # Format: XXXXXX (6), X (5), Y (5)
self.screen_x = self.bin_to_int(bin_value[6:11])
self.screen_y = self.bin_to_int(bin_value[11:16])
# print(self.screen_x, self.screen_y)
elif bin_address == '100': # Draws the Pixel on store with any value
try:
self.screen_buffer[31 - self.screen_y][31 - self.screen_x] = self.screen_d_latch_data
except IndexError:
self.display_error_message(f'Screen Coordinates: [X: {self.screen_x}, Y: {self.screen_y}] not found. X, Y must be in range [1;31]')
return
elif bin_address == '101': # Format: XXXXXXXXXXXXXXX (15), Screen Data Value (1)
self.screen_d_latch_data = int(bin_value[15])
elif bin_address == '110': # Sets all Pixels on store with any value
for x in range(31):
for y in range(31):
self.screen_buffer[y][x] = self.screen_d_latch_data
elif bin_address == '111': # Pushes the Buffer on store with any value
self.screen_data = copy.deepcopy(self.screen_buffer)
def reset_simulation(self) -> None:
global simulator
self.simulation_running = False
simulator = Simulator(simulator.speed)
_ = simulator.return_info(emit=True)
def step_simulation(self) -> None:
self.simulation_running = False
processed_lines = self.preprocess_assembly()
try:
current_instruction = processed_lines[self.bin_to_int(self.program_counter)]
except IndexError:
self.display_error_message('No halt at the end of the program')
return
self.execute_instruction(current_instruction.upper())
_ = self.return_info(emit=True)
def break_simulation(self) -> None:
self.simulation_running = False
_ = self.return_info(emit=True)
def run_simulation(self) -> None:
self.simulation_running = True
processed_lines = self.preprocess_assembly()
next_time = time.perf_counter()
while self.simulation_running:
if not self.simulation_running:
break # Exits, if no longer running
interval = 1 / max(1, self.speed) # Interval between executes, re-calculate every time, also avoids ZeroDivisionError
now = time.perf_counter()
if now < next_time:
sleep_duration = next_time - now
time.sleep(sleep_duration)
else:
next_time = now # catch up if we lag
if not self.simulation_running:
break # Exits, if no longer running
try:
current_instruction = processed_lines[self.bin_to_int(self.program_counter)]
except IndexError:
self.display_error_message('No halt at the end of the program')
return
self.execute_instruction(current_instruction.upper())
_ = self.return_info(emit=True)
next_time += interval
def return_info(self, emit: bool) -> list[dict[str, str] | list[list[int]] | str | int | bool | list[str]]:
decimal_info_list = [
{f'{key[0]}{format(int(key[1:]), "02d")}': f'{format(self.bin_to_int(value), "05d")}' for key, value in
self.REGISTERS.items()},
{f'{key[0]}{format(int(key[1:]), "01d")}': f'{format(self.bin_to_int(value), "05d")}' for key, value in
self.PORTS_READ_ONLY.items()},
{f'{key[0]}{format(int(key[1:]), "01d")}': f'{format(self.bin_to_int(value), "05d")}' for key, value in
self.PORTS_WRITE_ONLY.items()},
{f'{key[0]}{format(int(key[1:]), "03d")}': f'{format(self.bin_to_int(value), "05d")}' for key, value in
self.DATA_MEMORY_ADDRESSES.items()},
{key: str(value) for key, value in self.ALU_FLAGS.items()}, # Return it in a string-form
f'{format(self.bin_to_int(self.program_counter), "04d")}',
{f'{format(key, "02d")}': format(self.bin_to_int(self.call_stack[key]), '04d') if key < len(self.call_stack) else '0000' for key in range(16)}, # replace with call_stack dict
self.screen_data,
''.join(self.letters_data),
self.number,
self.simulation_running,
self.bin_to_int(self.program_counter),
self.preprocess_assembly(),
self.big_number
]
if emit:
socketio.emit('simulation_update', {
'pc': decimal_info_list[5],
'registers': decimal_info_list[0],
'ps': decimal_info_list[1],
'pd': decimal_info_list[2],
'data_memory': decimal_info_list[3],
'alu_flags': decimal_info_list[4],
'call_stack': decimal_info_list[6],
'letters': decimal_info_list[8],
'number': decimal_info_list[9],
'screen_data': decimal_info_list[7],
'int_pc': decimal_info_list[11],
'preprocessed_assembly': decimal_info_list[12],
'big_number': decimal_info_list[13]
})
return decimal_info_list
def generate_schematic(self) -> tuple[str, int]:
try:
generator.generate(assembly_file=SAVE_PATH)
except Exception as error:
self.display_error_message(error)
return '', 500 # Internal Server Error
else:
socketio.emit('generate_schematic_successful')
return '', 204 # No Content
def display_error_message(self, message) -> None:
socketio.emit('error_message', {'message': message})
simulator = Simulator(1) # Standard Speed
@socketio.on('reset_simulation')
def handle_reset() -> None:
simulator.reset_simulation()
@socketio.on('step_simulation')
def handle_step() -> None:
simulator.step_simulation()
@socketio.on('stop_simulation')
def handle_stop() -> None:
simulator.break_simulation()
@socketio.on('continue_simulation')
def handle_continue() -> None:
threading.Thread(target=simulator.run_simulation, daemon=True).start()
@socketio.on('generate_schematic')
def handle_generate_schematic() -> tuple[str, int]:
return simulator.generate_schematic()
@socketio.on('update_speed')
def handle_update_speed(data) -> None:
speed = data.get('speed')
print(f'Updating speed from {simulator.speed} -> {speed}')
simulator.speed = int(speed)
@socketio.on('request_update')
def handle_request_update() -> None:
print(f'Requested an Update')
simulator.return_info(emit=True)
@socketio.on('controller_update')
def handle_controller_update(data) -> None:
# print(f'controller update: {data}')
controller_data = data.get('controller')
# print(f'frontend: {controller_data} sent this.')
simulator.controller = {'UP': controller_data['UP'], 'RIGHT': controller_data['RIGHT'],
'DOWN': controller_data['DOWN'], 'LEFT': controller_data['LEFT'],
'START': (controller_data['START'] or simulator.controller['START']),
'SELECT': (controller_data['SELECT'] or simulator.controller['SELECT']),
'Y': (controller_data['Y'] or simulator.controller['Y']),
'X': (controller_data['X'] or simulator.controller['X'])}
value = (8 * '0' + str(simulator.controller['X']) + str(simulator.controller['Y']) +
str(simulator.controller['SELECT']) + str(simulator.controller['START']) +
str(simulator.controller['LEFT']) + str(simulator.controller['DOWN']) +
str(simulator.controller['RIGHT']) + str(simulator.controller['UP']))
simulator.PORTS_READ_ONLY['P0'] = value
simulator.return_info(emit=True)
# print(f'backend: {simulator.controller} updated this.')
@app.route('/save', methods=['POST'])
def save_via_fetch() -> tuple[str, int]:
code_input = request.form.get('codeInput', '').replace('\r\n', '\n').rstrip()
with open(SAVE_PATH, 'w') as f:
f.write(code_input)
simulator.reset_simulation()
return '', 204
@app.route('/', methods=['GET'])
def ui_index() -> str: # returns flask template (str)
saved_code = ''
try:
with open(SAVE_PATH, 'r') as file:
saved_code = file.read()
except FileNotFoundError:
simulator.display_error_message(f'Fatal Error. File "{SAVE_PATH}"was not found. Perhaps create it?')
decimal_info_list = simulator.return_info(emit=False)
return render_template(
'index.html',
saved_text=saved_code,
registers=decimal_info_list[0],
ps=decimal_info_list[1],
pd=decimal_info_list[2],
data_memory=decimal_info_list[3],
alu_flags=decimal_info_list[4],
pc=decimal_info_list[5],
call_stack=decimal_info_list[6],
screen_data=decimal_info_list[7],
letters=decimal_info_list[8],
number=decimal_info_list[9],
big_number=decimal_info_list[13],
preprocessed_assembly=simulator.preprocess_assembly()
)
@app.route('/upload', methods=['POST'])
def upload() -> tuple[str, int]:
file = request.files['file']
content = ""
if file and file.filename.endswith('.txt'):
content = file.read().decode('utf-8')
content = content.replace('\r\n', '\n').rstrip()
with open(SAVE_PATH, 'w') as f:
f.write(content)
simulator.reset_simulation()
socketio.emit('update_code', {'content': content})
return '', 204
def start_app() -> None:
socketio.run(app=app, host="0.0.0.0", port=PORT, debug=True, allow_unsafe_werkzeug=True, use_reloader=False)
def set_zoom(window) -> None:
window.evaluate_js(f"document.body.style.zoom = '{ZOOM_LEVEL_GUI}';")
def start_webview() -> None:
window = webview.create_window('Assembler UI', f'http://127.0.0.1:{PORT}')
webview.start(set_zoom, window)
if __name__ == '__main__':
threading.Thread(target=start_app).start()
if EXPERIMENTAL_GUI:
start_webview()