-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedScript.py
More file actions
1471 lines (1299 loc) · 53.9 KB
/
RedScript.py
File metadata and controls
1471 lines (1299 loc) · 53.9 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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import re
import time
import math
import ast
import traceback
import colorsys
from dataclasses import dataclass
from typing import List, Dict, Callable, Optional, Any, Tuple
# PyQt6 imports (make sure PyQt6 is installed)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QSize, QTimer
from PyQt6.QtGui import QAction, QFont, QColor, QIcon, QKeySequence, QSyntaxHighlighter, QTextCharFormat
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
QLabel, QFileDialog, QListWidget, QListWidgetItem, QTabWidget, QPlainTextEdit,
QSplitter, QInputDialog, QToolBar, QStatusBar, QDialog, QTableWidget,
QTableWidgetItem, QMessageBox
)
from functools import partial
class InterpreterError(Exception):
def __init__(self, message: str, line: Optional[int] = None):
if line is not None:
message = f"Line {line}: {message}"
super().__init__(message)
self.line = line
# Safe evaluator
def safe_eval_expr(expr: str, vars_map: Dict[str, Any]) -> float:
if expr is None or str(expr).strip() == "":
raise InterpreterError("Empty expression")
try:
node = ast.parse(expr, mode='eval')
except Exception as e:
raise InterpreterError(f"Parse error: {e}")
def _eval(n):
if isinstance(n, ast.Expression):
return _eval(n.body)
if isinstance(n, ast.Constant):
if isinstance(n.value, (int, float)):
return float(n.value)
raise InterpreterError("Only numeric constants allowed")
if isinstance(n, ast.BinOp):
left = _eval(n.left)
right = _eval(n.right)
if isinstance(n.op, ast.Add):
return left + right
if isinstance(n.op, ast.Sub):
return left - right
if isinstance(n.op, ast.Mult):
return left * right
if isinstance(n.op, ast.Div):
return left / right
if isinstance(n.op, ast.Pow):
return left ** right
if isinstance(n.op, ast.Mod):
return left % right
raise InterpreterError("Unsupported binary operator")
if isinstance(n, ast.UnaryOp):
v = _eval(n.operand)
if isinstance(n.op, ast.UAdd):
return +v
if isinstance(n.op, ast.USub):
return -v
raise InterpreterError("Unsupported unary operator")
if isinstance(n, ast.Name):
if n.id in vars_map:
try:
return float(vars_map[n.id])
except Exception:
raise InterpreterError(f"Variable {n.id} is not numeric")
raise InterpreterError(f"Unknown variable: {n.id}")
if isinstance(n, ast.Call):
if isinstance(n.func, ast.Name):
fname = n.func.id
allowed = {'sin','cos','tan','sqrt','log','ceil','floor'}
if fname in allowed and len(n.args) == 1:
aval = _eval(n.args[0])
if fname == 'ceil':
return float(math.ceil(aval))
if fname == 'floor':
return float(math.floor(aval))
return float(getattr(math, fname)(aval))
raise InterpreterError("Function calls not allowed except limited math funcs")
raise InterpreterError(f"Unsupported expression element: {type(n)}")
return float(_eval(node))
# CommandSpec
@dataclass
class CommandSpec:
name: str
category: str
signature: str
description: str
safe: bool = True
# CommandRegistry
class CommandRegistry:
def __init__(self, bulk_n: int = 1000):
self.commands = {}
self.handlers = {}
self.aliases = {}
self.macros = {}
self.meta = {}
self._init_realtime_gui()
self._register_core()
self._register_more_commands()
self.generate_bulk_commands(bulk_n)
self._register_gui_commands()
def _init_realtime_gui(self):
if not QApplication.instance():
QApplication([])
self._gui_engine = {}
self._last_ctx = None
self._gui_timer = QTimer()
self._gui_timer.setInterval(50)
self._gui_timer.timeout.connect(self._process_gui_queue)
self._gui_timer.start()
def _process_gui_queue(self):
ctx = self._last_ctx
if not ctx:
return
queue = ctx.get('__gui_queue__', [])
while queue:
cmd = queue.pop(0)
if not cmd:
continue
action = cmd[0]
if action == 'CREATE_WINDOW':
_, title, w, h = cmd
if title in self._gui_engine:
continue
win = QMainWindow()
win.setWindowTitle(title)
win.resize(w, h)
central = QWidget()
layout = QVBoxLayout()
central.setLayout(layout)
win.setCentralWidget(central)
self._gui_engine[title] = {'window': win, 'layout': layout}
elif action == 'ADD_LABEL':
_, title, text = cmd
if title in self._gui_engine:
lbl = QLabel(text)
self._gui_engine[title]['layout'].addWidget(lbl)
elif action == 'ADD_BUTTON':
_, title, label, callback_cmd = cmd
if title in self._gui_engine:
btn = QPushButton(label)
def _on_click(cb=callback_cmd, cctx=ctx):
try:
self.call(cb, [], cctx)
except Exception as e:
cctx.setdefault('__output__', []).append(f'[GUI CALLBACK ERROR] {e}')
btn.clicked.connect(partial(_on_click))
self._gui_engine[title]['layout'].addWidget(btn)
elif action == 'SHOW_WINDOW':
_, title = cmd
if title in self._gui_engine:
self._gui_engine[title]['window'].show()
elif action == 'CLEAR_WINDOW':
_, title = cmd
if title in self._gui_engine:
layout = self._gui_engine[title]['layout']
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget:
widget.deleteLater()
elif action == 'CLOSE_WINDOW':
_, title = cmd
if title in self._gui_engine:
self._gui_engine[title]['window'].close()
del self._gui_engine[title]
ctx['__gui_queue__'] = []
def _register_gui_commands(self):
@self.register(CommandSpec('GUI_WINDOW_CREATE', 'gui', 'GUI_WINDOW_CREATE title width height', '...'))
def _gui_window_create(args, ctx):
self._last_ctx = ctx
# queue CREATE_WINDOW
title = args[0].strip('"\'')
w, h = int(args[1]), int(args[2])
ctx.setdefault('__gui_queue__', []).append(('CREATE_WINDOW', title, w, h))
return title
@self.register(CommandSpec('GUI_WINDOW_CREATE', 'gui', 'GUI_WINDOW_CREATE title width height',
'Create window (real-time).'))
def _gui_window_create(args, ctx):
self._last_ctx = ctx
if len(args) < 3:
raise RuntimeError('GUI_WINDOW_CREATE requires title width height')
title = args[0].strip('"\'')
try:
w = int(args[1])
h = int(args[2])
except Exception:
raise RuntimeError('Width/height must be integers')
ctx.setdefault('__gui_queue__', []).append(('CREATE_WINDOW', title, w, h))
ctx.setdefault('__output__', []).append(f'[GUI] queued create window {title}')
return title
@self.register(CommandSpec('GUI_LABEL_ADD', 'gui', 'GUI_LABEL_ADD window_title text',
'Add label to window (real-time).'))
def _gui_label_add(args, ctx):
self._last_ctx = ctx
if len(args) < 2:
raise RuntimeError('GUI_LABEL_ADD requires window_title text')
title = args[0].strip('"\'')
text = args[1].strip('"\'')
ctx.setdefault('__gui_queue__', []).append(('ADD_LABEL', title, text))
ctx.setdefault('__output__', []).append(f'[GUI] queued add label "{text}" -> {title}')
return f'{title}:{text}'
@self.register(CommandSpec('GUI_BUTTON_ADD', 'gui', 'GUI_BUTTON_ADD window_title label callback_cmd',
'Add button with callback (real-time).'))
def _gui_button_add(args, ctx):
self._last_ctx = ctx
if len(args) < 3:
raise RuntimeError('GUI_BUTTON_ADD requires window_title label callback_cmd')
title = args[0].strip('"\'')
label = args[1].strip('"\'')
cb = args[2]
ctx.setdefault('__gui_queue__', []).append(('ADD_BUTTON', title, label, cb))
ctx.setdefault('__output__', []).append(f'[GUI] queued add button {label} -> {title}')
return f'{title}:{label}'
@self.register(CommandSpec('GUI_SHOW', 'gui', 'GUI_SHOW window_title', 'Show window (real-time).'))
def _gui_show(args, ctx):
self._last_ctx = ctx
if not args:
raise RuntimeError('GUI_SHOW requires window_title')
title = args[0].strip('"\'')
ctx.setdefault('__gui_queue__', []).append(('SHOW_WINDOW', title))
ctx.setdefault('__output__', []).append(f'[GUI] queued show {title}')
return title
@self.register(CommandSpec('GUI_CLEAR', 'gui', 'GUI_CLEAR window_title', 'Clear window contents.'))
def _gui_clear(args, ctx):
self._last_ctx = ctx
if not args:
raise RuntimeError('GUI_CLEAR requires window_title')
title = args[0].strip('"\'')
ctx.setdefault('__gui_queue__', []).append(('CLEAR_WINDOW', title))
ctx.setdefault('__output__', []).append(f'[GUI] queued clear window {title}')
return title
@self.register(CommandSpec('GUI_CLOSE', 'gui', 'GUI_CLOSE window_title', 'Close window.'))
def _gui_close(args, ctx):
self._last_ctx = ctx
if not args:
raise RuntimeError('GUI_CLOSE requires window_title')
title = args[0].strip('"\'')
ctx.setdefault('__gui_queue__', []).append(('CLOSE_WINDOW', title))
ctx.setdefault('__output__', []).append(f'[GUI] queued close {title}')
return title
# registration helper
def register(self, spec: CommandSpec):
key = spec.name.upper()
self.commands[key] = spec
# assign deterministic pastel color for UI/highlighter
self.meta[key] = {
'category': spec.category,
'signature': spec.signature,
'description': spec.description,
'color': self._color_from_name_hex(key)
}
def decorator(fn: Callable):
self.handlers[key] = fn
return fn
return decorator
# macro helpers
def define_macro(self, name: str, lines: List[str], ctx: Optional[Dict[str, Any]] = None) -> str:
if not name:
raise RuntimeError("[MACRO] Missing macro name!")
cleaned = [ln.strip() for ln in lines if ln and ln.strip()]
if not cleaned:
raise RuntimeError(f"[MACRO] Macro '{name}' has empty body!")
self.macros[name.upper()] = cleaned
if ctx is not None:
ctx.setdefault('__output__', []).append(f"[MACRO] Macro '{name}' registered ({len(cleaned)} lines)")
return f"Macro {name.upper()} registered"
def execute_macro(self, name: str, extra_lines: Optional[List[str]], ctx: Dict[str, Any]) -> List[Any]:
name_u = name.upper()
if name_u not in self.macros:
raise RuntimeError(f"Macro {name} not defined")
macro_lines = list(self.macros[name_u])
if extra_lines:
macro_lines += [ln for ln in extra_lines if ln and ln.strip()]
results = []
for mline in macro_lines:
if not mline.strip() or mline.strip().startswith('#'):
continue
# execute each line (use core.execute? use call path)
try:
# If line starts with CALL(...) pattern, _execute_line will parse it.
parts = self._tokenize(mline)
if not parts:
continue
cmd = parts[0]
args = parts[1:]
# If macro references another macro name, expansion will happen at interpreter loop normally.
res = self.call(cmd, args, ctx)
results.append(res)
except Exception as e:
results.append(f"[MACRO ERROR] {e}")
return results
# call/lookup
def call(self, name: str, args: List[str], ctx: Dict[str, Any]):
if name is None:
raise ValueError("Command name required")
key = name.upper()
# expand aliases with loop detection
visited = set()
while key in self.aliases:
if key in visited:
raise RuntimeError(f"Alias loop detected for {key}")
visited.add(key)
expansion = self.aliases[key]
parts = expansion.split()
if not parts:
break
name = parts[0]
args = parts[1:] + args
key = name.upper()
if key not in self.handlers:
raise RuntimeError(f"Unknown command: {name}")
ctx = ctx or {}
ctx.setdefault('__output__', [])
ctx.setdefault('vars', {})
ctx.setdefault('__gui_queue__', [])
ctx.setdefault('__cmd_meta__', {})
ctx['__cmd_meta__']['last_called'] = key
ctx['__cmd_meta__']['meta'] = self.meta.get(key, {})
return self.handlers[key](args, ctx)
def get_spec(self, name: str) -> Optional[CommandSpec]:
return self.commands.get(name.upper())
def list_all(self) -> List[CommandSpec]:
return list(self.commands.values())
# color utils
def _color_from_name_hex(self, name: str) -> str:
# deterministic pastel HSL -> hex
h = abs(hash(name)) % 360
s = 64 + (abs(hash(name[::-1])) % 20)
l = 45 + (abs(hash(name + 'L')) % 12)
hn, sn, ln = h/360.0, s/100.0, l/100.0
r, g, b = colorsys.hls_to_rgb(hn, ln, sn)
return f'#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}'
def get_color_for_command(self, name: str) -> Optional[str]:
m = self.meta.get(name.upper())
return m.get('color') if m else None
def set_color_for_command(self, name: str, hex_color: str):
if name.upper() in self.meta:
self.meta[name.upper()]['color'] = hex_color
# bulk generation
def generate_bulk_commands(self, n: int = 500):
cats = ['math','str','io_safe','util','time','simulate','net']
for i in range(1, n+1):
name = f'AUTO_CMD_{i}'
cat = cats[i % len(cats)]
sig = f'{name} <args...>'
desc = f'Auto-generated command #{i} ({cat})'
key = name.upper()
if key in self.commands:
continue
spec = CommandSpec(name, cat, sig, desc)
self.commands[key] = spec
self.meta[key] = {'category': cat, 'signature': sig, 'description': desc, 'color': self._color_from_name_hex(key)}
def make_handler(nm):
def handler(args, ctx):
msg = f'[AUTO] {nm}: args={args}'
ctx.setdefault('__output__', []).append(msg)
return msg
return handler
self.handlers[key] = make_handler(name)
# core commands
def _register_core(self):
@self.register(CommandSpec('PRINT','core','PRINT <items...>','Print strings or expressions (quoted strings or numeric expr).'))
def _print(args, ctx):
out = []
vars_map = ctx.setdefault('vars', {})
i = 0
while i < len(args):
token = args[i]
# skip explicit '+' tokens (support classic concatenation)
if token == '+':
i += 1
continue
if (token.startswith('"') and token.endswith('"')) or (token.startswith("'") and token.endswith("'")):
out.append(token[1:-1])
else:
# try variable lookup first
if re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', token) and token in vars_map:
val = vars_map[token]
else:
# try evaluate numeric expression (caller must provide safe_eval_expr)
try:
val = safe_eval_expr(token, vars_map)
except InterpreterError:
# fallback: treat as raw string
val = token
# format ints without .0
try:
if isinstance(val, (int, float)) and float(val).is_integer():
out.append(str(int(val)))
else:
out.append(str(val))
except Exception:
out.append(str(val))
i += 1
result = " ".join(out)
ctx.setdefault('__output__', []).append(result)
return result
@self.register(CommandSpec('LET','core','LET var = expr','Assign expression to variable.'))
def _let(args, ctx):
if not args:
raise RuntimeError("LET requires arguments")
vars_map = ctx.setdefault('vars', {})
if '=' in args:
eq = args.index('=')
name = args[0]
expr = ' '.join(args[eq+1:])
else:
name = args[0]
expr = ' '.join(args[1:])
val = safe_eval_expr(expr, vars_map)
vars_map[name] = val
return val
@self.register(CommandSpec('ADD','core','ADD var expr','Add value to variable.'))
def _add(args, ctx):
if len(args) < 2:
raise RuntimeError("ADD needs var and expr")
vars_map = ctx.setdefault('vars', {})
target = args[0]
expr = ' '.join(args[1:])
val = safe_eval_expr(expr, vars_map)
prev = float(vars_map.get(target, 0))
res = prev + val
vars_map[target] = res
return res
@self.register(CommandSpec('SUB','core','SUB var expr','Subtract value from variable.'))
def _sub(args, ctx):
if len(args) < 2:
raise RuntimeError("SUB needs var and expr")
vars_map = ctx.setdefault('vars', {})
target = args[0]
expr = ' '.join(args[1:])
val = safe_eval_expr(expr, vars_map)
prev = float(vars_map.get(target, 0))
res = prev - val
vars_map[target] = res
return res
@self.register(CommandSpec('MUL','core','MUL var expr','Multiply variable by expr.'))
def _mul(args, ctx):
if len(args) < 2:
raise RuntimeError("MUL needs var and expr")
vars_map = ctx.setdefault('vars', {})
target = args[0]; expr = ' '.join(args[1:])
val = safe_eval_expr(expr, vars_map)
prev = float(vars_map.get(target, 0))
res = prev * val
vars_map[target] = res
return res
@self.register(CommandSpec('DIV','core','DIV var expr','Divide variable by expr.'))
def _div(args, ctx):
if len(args) < 2:
raise RuntimeError("DIV needs var and expr")
vars_map = ctx.setdefault('vars', {})
target = args[0]; expr = ' '.join(args[1:])
val = safe_eval_expr(expr, vars_map)
if val == 0:
raise RuntimeError("Division by zero")
prev = float(vars_map.get(target, 0))
res = prev / val
vars_map[target] = res
return res
@self.register(CommandSpec('ENDIF', 'control', 'ENDIF', 'End IF block (no-op, handled by interpreter).'))
def _endif(args, ctx):
ctx.setdefault('__output__', []).append('[ENDIF] control token')
return True
@self.register(CommandSpec('ENDLOOP', 'control', 'ENDLOOP', 'End LOOP block (no-op, handled by interpreter).'))
def _endloop(args, ctx):
ctx.setdefault('__output__', []).append('[ENDLOOP] control token')
return True
@self.register(CommandSpec('SLEEP','core','SLEEP seconds','Sleep for up to 5 seconds (capped).', safe=True))
def _sleep(args, ctx):
try:
secs = float(args[0]) if args else 0
except Exception:
secs = 0
secs = max(0, min(5, secs))
time.sleep(secs)
return secs
@self.register(CommandSpec('IF','control','IF <cond> THEN ... ENDIF','Control keyword - prefer handled by core/interpreter.'))
def _if(args, ctx):
# no-op, handled by interpreter
ctx.setdefault('__output__', []).append('[IF] control token (handled by core)')
return True
@self.register(CommandSpec('LOOP','control','LOOP n ... ENDLOOP','Control keyword - prefer handled by core/interpreter.'))
def _loop(args, ctx):
ctx.setdefault('__output__', []).append('[LOOP] control token (handled by core)')
return True
@self.register(CommandSpec('ALIAS','meta','ALIAS name expansion','Create alias.'))
def _alias(args, ctx):
if len(args) < 2:
raise RuntimeError('ALIAS needs name and expansion')
name = args[0].upper()
expansion = ' '.join(args[1:])
self.aliases[name] = expansion
return f'Alias {name} -> {expansion}'
@self.register(CommandSpec('UNALIAS','meta','UNALIAS name','Remove alias.'))
def _unalias(args, ctx):
if not args:
raise RuntimeError('UNALIAS needs name')
name = args[0].upper()
self.aliases.pop(name, None)
return f'Alias {name} removed'
@self.register(CommandSpec('MACRO','meta','MACRO name ; cmd1 ; cmd2','Define macro (semicolon-separated).'))
def _macro(args, ctx):
if len(args) < 2:
raise RuntimeError('MACRO requires name and body')
name = args[0].upper()
body = ' '.join(args[1:]).split(';')
self.macros[name] = [b.strip() for b in body if b.strip()]
return f'Macro {name} set'
@self.register(CommandSpec('UNMACRO','meta','UNMACRO name','Remove macro.'))
def _unmacro(args, ctx):
if not args:
raise RuntimeError('UNMACRO needs name')
name = args[0].upper()
self.macros.pop(name, None)
return f'Macro {name} removed'
@self.register(CommandSpec('ALL_COMMANDS','meta','ALL_COMMANDS','Return structured list of all commands.'))
def _all_cmds(args, ctx):
out = {}
for spec in self.list_all():
out.setdefault(spec.category, []).append({'name': spec.name, 'signature': spec.signature, 'description': spec.description})
ctx.setdefault('__output__', []).append('[ALL_COMMANDS]')
return out
@self.register(CommandSpec('HELP','meta','HELP [cmd]','Show help for command or categories.'))
def _help(args, ctx):
if args:
nm = args[0].upper()
spec = self.get_spec(nm)
if not spec:
raise RuntimeError(f'No help for {nm}')
info = f'{spec.name}: {spec.signature} - {spec.description}'
ctx.setdefault('__output__', []).append(info)
return info
# otherwise list categories summary
cats = {}
for s in self.list_all():
cats.setdefault(s.category, 0)
cats[s.category] += 1
out = ', '.join([f'{k}({v})' for k,v in cats.items()])
ctx.setdefault('__output__', []).append(out)
return out
def _register_more_commands(self):
@self.register(CommandSpec('ECHO','util','ECHO text','Alias to PRINT; prints raw text.'))
def _echo(args, ctx):
return self.call('PRINT', args, ctx)
@self.register(CommandSpec('STR_LEN','str','STR_LEN s','Return length of string.'))
def _strlen(args, ctx):
if not args:
raise RuntimeError('STR_LEN needs argument')
token = args[0]
if (token.startswith('"') and token.endswith('"')) or (token.startswith("'") and token.endswith("'")):
s = token[1:-1]
else:
s = str(ctx.setdefault('vars', {}).get(token, token))
out = str(len(s))
ctx.setdefault('__output__', []).append(out)
return out
@self.register(CommandSpec('STR_UPPER','str','STR_UPPER s','Uppercase string.'))
def _upper(args, ctx):
if not args:
raise RuntimeError('STR_UPPER needs arg')
token = args[0]
if (token.startswith('"') and token.endswith('"')) or (token.startswith("'") and token.endswith("'")):
s = token[1:-1]
else:
s = str(ctx.setdefault('vars', {}).get(token, token))
out = s.upper()
ctx.setdefault('__output__', []).append(out)
return out
@self.register(CommandSpec('REPLACE','str','REPLACE s old new','Replace substring.'))
def _replace(args, ctx):
if len(args) < 3:
raise RuntimeError('REPLACE needs s old new')
token, old, new = args[0], args[1].strip('"\'') , args[2].strip('"\'')
if (token.startswith('"') and token.endswith('"')) or (token.startswith("'") and token.endswith("'")):
s = token[1:-1]
else:
s = str(ctx.setdefault('vars', {}).get(token, token))
out = s.replace(old, new)
ctx.setdefault('__output__', []).append(out)
return out
@self.register(CommandSpec('READ','io_safe','READ path','Read file in project (safe).'))
def _read(args, ctx):
path = args[0] if args else ''
proj = ctx.get('project')
if proj:
full = os.path.join(proj.folder_path, path)
if os.path.exists(full):
with open(full, 'r', encoding='utf-8') as f:
content = f.read()
ctx.setdefault('__output__', []).append(content)
return content
raise RuntimeError('File not found in project')
@self.register(CommandSpec('WRITE','io_safe','WRITE path text','Write file in project (safe).'))
def _write(args, ctx):
if not args:
raise RuntimeError('WRITE requires path and text')
path = args[0]
text = ' '.join(args[1:]) if len(args) > 1 else ''
proj = ctx.get('project')
if proj:
full = os.path.join(proj.folder_path, path)
with open(full, 'w', encoding='utf-8') as f:
f.write(text)
return f'Written {path}'
raise RuntimeError('No project open')
# simulated red-team educational commands (safe)
@self.register(CommandSpec('SIM_SCAN','red','SIM_SCAN target','Simulated port scan (educational).'))
def _sim_scan(args, ctx):
tgt = args[0] if args else 'localhost'
res = f'Simulated scan for {tgt}: open ports 22,80'
ctx.setdefault('__output__', []).append(res)
return res
@self.register(CommandSpec('SIM_PAYLOAD','red','SIM_PAYLOAD name','Simulated payload (no real code).'))
def _sim_payload(args, ctx):
name = args[0] if args else 'demo'
res = f'[SIMULATED_PAYLOAD] {name} -> <stub>'
ctx.setdefault('__output__', []).append(res)
return res
@self.register(CommandSpec('CRYPTO_HASH','crypto','CRYPTO_HASH algo text','Return simulated hash digest.'))
def _crypto_hash(args, ctx):
algo = args[0] if args else 'md5'
txt = ' '.join(args[1:]) if len(args)>1 else ''
h = abs(hash((algo, txt))) % (10**9)
res = f'{algo}:{h:09d}'
ctx.setdefault('__output__', []).append(res)
return res
# RedScriptCore
class RedScriptCore:
def __init__(self, registry: Optional[CommandRegistry] = None):
self.registry = registry or CommandRegistry()
def execute(self, source: str, ctx: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
ctx = ctx or {}
ctx.setdefault('__output__', [])
ctx.setdefault('vars', {})
ctx.setdefault('__gui_queue__', [])
lines = source.splitlines()
i = 0
while i < len(lines):
raw = lines[i]
i += 1
line = raw.strip()
if not line or line.startswith('#'):
continue
parts = self._tokenize(line)
if not parts:
continue
cmd = parts[0].upper()
# MACRO block detection
if cmd == 'MACRO':
if len(parts) < 2:
ctx.setdefault('__output__', []).append("[ERROR] MACRO name missing")
continue
name = parts[1].strip()
block_lines = []
while i < len(lines):
l = lines[i].rstrip('\n')
i += 1
if l.strip().upper() == 'ENDMACRO':
break
block_lines.append(l)
else:
ctx.setdefault('__output__', []).append(f"[ERROR] ENDMACRO not found for macro '{name}'")
continue
# define macro in registry (store body)
try:
self.registry.define_macro(name, block_lines, ctx)
except Exception as e:
ctx.setdefault('__output__', []).append(f"[ERROR] {e}")
continue
# macro invocation by name (simple expansion)
if cmd in self.registry.macros:
try:
# execute stored macro lines
self.registry.execute_macro(cmd, None, ctx)
except Exception as e:
ctx.setdefault('__output__', []).append(f"[ERROR] Macro execution failed: {e}")
continue
# IF support (handled at interpreter level)
if cmd == 'IF':
cond = ' '.join(parts[1:])
try:
result, new_i = self._eval_if_block(cond, lines, i, ctx)
except InterpreterError as e:
ctx.setdefault('__output__', []).append(f'[ERROR] {e}')
break
if not result:
i = new_i
continue
# LOOP support
if cmd == 'LOOP':
try:
n = int(parts[1])
except Exception:
n = 0
start = i
end = self._find_block_end(lines, start - 1, 'ENDLOOP')
block = '\n'.join(lines[start:end])
for _ in range(n):
# reuse execute for block
self.execute(block, ctx)
i = end + 1
continue
# regular command
try:
self._execute_line(line, ctx)
except InterpreterError as e:
ctx.setdefault('__output__', []).append(f'[ERROR] {e}')
break
except Exception as e:
ctx.setdefault('__output__', []).append(f'[ERROR] {e}')
break
return ctx
def _execute_line(self, line: str, ctx: Dict[str, Any]):
parts = self._tokenize(line)
if not parts:
return None
cmd = parts[0]
args = parts[1:]
# support CALL FOO("a", 1)
m = re.match(r"CALL\s+([A-Za-z_][A-Za-z0-9_]*)\s*\((.*)\)\s*$", line, re.IGNORECASE)
if m:
name = m.group(1)
argtext = m.group(2)
# split on commas that are not escaped
args = [a.strip().strip('\"\'') for a in re.split(r'(?<!\\),', argtext) if a.strip()]
return self.registry.call(name, args, ctx)
# normal call
return self.registry.call(cmd, args, ctx)
def _tokenize(self, line: str) -> List[str]:
tokens = []
buf = ''
in_q = False
qch = ''
for ch in line:
if in_q:
buf += ch
if ch == qch:
tokens.append(buf)
buf = ''
in_q = False
continue
if ch in ('"', "'"):
in_q = True
qch = ch
buf += ch
continue
if ch.isspace():
if buf:
tokens.append(buf)
buf = ''
continue
buf += ch
if buf:
tokens.append(buf)
return tokens
def _find_block_end(self, lines: List[str], start_index: int, token_end: str) -> int:
for i in range(start_index + 1, len(lines)):
if lines[i].strip().upper().startswith(token_end):
return i
raise InterpreterError(f'Block end {token_end} not found')
def _eval_if_block(self, condition: str, lines: List[str], index_after_if: int, ctx: Dict[str, Any]) -> Tuple[bool, int]:
cond = condition
if cond.upper().endswith('THEN'):
cond = cond[:-4].strip()
try:
if cond == '':
result = False
else:
result = bool(safe_eval_expr(cond, ctx.get('vars', {})))
except InterpreterError:
# comparator fallback (string/numeric)
m = re.match(r"(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)", cond)
if m:
try:
a = float(safe_eval_expr(m.group(1), ctx.get('vars', {})))
b = float(safe_eval_expr(m.group(3), ctx.get('vars', {})))
except InterpreterError:
# fallback to string compare
a = m.group(1).strip().strip('"\'')
b = m.group(3).strip().strip('"\'')
op = m.group(2)
if op == '==':
result = a == b
elif op == '!=':
result = a != b
elif op == '>=':
result = a >= b
elif op == '<=':
result = a <= b
elif op == '>':
result = a > b
elif op == '<':
result = a < b
else:
result = False
else:
result = False
# find matching ENDIF
for i in range(index_after_if, len(lines)):
if lines[i].strip().upper().startswith('ENDIF'):
return result, i + 1
raise InterpreterError('ENDIF not found for IF')
# GUIWindowManager
class GUIWindowManager:
def __init__(self):
self.windows: Dict[str, Dict[str, Any]] = {}
def create_window(self, title: str, w: int, h: int):
win = QWidget()
win.setWindowTitle(title)
win.resize(w, h)
layout = QVBoxLayout(win)
win.setLayout(layout)
self.windows[title] = {'widget': win, 'layout': layout}
return title
def add_button(self, window_title: str, label: str, callback: Optional[Callable], interpreter: Any):
if window_title not in self.windows:
return
info = self.windows[window_title]
btn = QPushButton(label)
try:
registry = getattr(interpreter, 'registry', None)
if registry:
hex_color = registry.get_color_for_command(label) or registry._color_from_name_hex(label.upper())
btn.setStyleSheet(f'background:{hex_color}; padding:6px; border-radius:6px; color:#ffffff;')
except Exception:
pass
def on_click():
try:
if callback:
callback()
elif hasattr(interpreter, 'registry'):
interpreter.registry.call('PRINT', [f'"{label} clicked!"'], {'__output__': []})
except Exception:
pass
btn.clicked.connect(on_click)
info['layout'].addWidget(btn)
def show_window(self, title: str):
if title in self.windows:
self.windows[title]['widget'].show()
global_gui_manager = GUIWindowManager()
# Runner
class RedScriptRunner(QThread):
output = pyqtSignal(str)
error = pyqtSignal(str)
finished = pyqtSignal()
def __init__(self, code: str, core: RedScriptCore, project=None):
super().__init__()
self.code = code
self.core = core
self._running = True
self.project = project
def run(self):
try:
ctx = {'project': self.project}
out = self.core.execute(self.code, ctx)
for line in out.get('__output__', []):
if not self._running:
break
self.output.emit(str(line))
self.finished.emit()
except Exception:
self.error.emit(traceback.format_exc())
def stop(self):
self._running = False
# Highlighter
class RedScriptHighlighter(QSyntaxHighlighter):
def __init__(self, parent):
super().__init__(parent.document())
self.parent = parent
self.rules: List[Tuple[re.Pattern, QTextCharFormat]] = []
self._init_formats()
self._build_rules()
def _init_formats(self):
self.fmt_keyword = QTextCharFormat()
self.fmt_keyword.setForeground(QColor('#57c7ff'))
self.fmt_keyword.setFontWeight(600)
self.fmt_builtin = QTextCharFormat()
self.fmt_builtin.setForeground(QColor('#ffb86c'))
self.fmt_builtin.setFontWeight(600)
self.fmt_string = QTextCharFormat()
self.fmt_string.setForeground(QColor('#98c379'))
self.fmt_number = QTextCharFormat()
self.fmt_number.setForeground(QColor('#bd93f9'))
self.fmt_comment = QTextCharFormat()
self.fmt_comment.setForeground(QColor('#6272a4'))
self.fmt_comment.setFontItalic(True)
def _build_rules(self):
keywords = ['PRINT','LET','SET','ADD','SUB','MUL','DIV','MOD','POW','IF','ENDIF','LOOP','ENDLOOP','SLEEP','RUN','CALL','MACRO']