flexcode-editor 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
flexcode.py ADDED
@@ -0,0 +1,2368 @@
1
+
2
+ import json
3
+ import math
4
+ import os
5
+ import pty
6
+ import queue
7
+ import shlex
8
+ import shutil
9
+ import signal
10
+ import re
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ import threading
15
+ import pygame
16
+
17
+ pygame.init()
18
+
19
+ APP_NAME = "FLEXCODE"
20
+ APP_VERSION = "1.0"
21
+ HERE = os.path.dirname(os.path.abspath(__file__))
22
+
23
+ # ------------------------------------------------------------------ theme
24
+ # FLEXCODE palette: graphite surfaces with a teal accent.
25
+ C = {
26
+ "title": (16, 20, 27),
27
+ "title_text": (200, 208, 218),
28
+ "search_bg": (26, 31, 40),
29
+ "search_border": (48, 56, 68),
30
+ "activity": (12, 15, 21),
31
+ "icon": (120, 130, 145),
32
+ "icon_active": (240, 245, 250),
33
+ "sidebar": (19, 23, 31),
34
+ "sidebar_sel": (40, 50, 64),
35
+ "sidebar_hover": (30, 38, 50),
36
+ "section": (200, 208, 218),
37
+ "text": (201, 209, 217),
38
+ "dim": (116, 126, 140),
39
+ "input_bg": (34, 40, 52),
40
+ "btn": (18, 140, 126),
41
+ "btn_text": (8, 20, 22),
42
+ "editor": (14, 17, 24),
43
+ "tabbar": (19, 23, 31),
44
+ "tab_inactive": (24, 29, 38),
45
+ "tab_active": (14, 17, 24),
46
+ "tab_text_active": (240, 245, 250),
47
+ "tab_text_inactive": (116, 126, 140),
48
+ "accent": (24, 190, 170),
49
+ "border": (30, 36, 46),
50
+ "line_num": (76, 86, 100),
51
+ "line_num_active": (201, 209, 217),
52
+ "cur_line": (22, 28, 38),
53
+ "sel": (30, 70, 80),
54
+ "caret": (24, 190, 170),
55
+ "status": (24, 190, 170),
56
+ "status_text": (8, 22, 24),
57
+ "scroll": (48, 56, 68),
58
+ "hint": (80, 90, 104),
59
+ "green": (120, 220, 160),
60
+ "error": (255, 123, 114),
61
+ "warn": (240, 190, 90),
62
+ "modified": (226, 192, 141),
63
+ "added": (115, 201, 145),
64
+ "deleted": (201, 103, 103),
65
+ "find_match": (90, 80, 30),
66
+ "find_cur": (170, 130, 30),
67
+ "menu_bg": (22, 27, 36),
68
+ "menu_hover": (36, 46, 60),
69
+ # syntax
70
+ "kw": (100, 160, 255),
71
+ "ctrl": (196, 134, 255),
72
+ "str": (229, 190, 128),
73
+ "com": (92, 124, 104),
74
+ "num": (172, 214, 160),
75
+ "fn": (240, 214, 140),
76
+ "typ": (88, 214, 190),
77
+ "plain": (210, 218, 226),
78
+ }
79
+
80
+ # ----------------------------------------------------------------- layout
81
+ TITLE_H = 30
82
+ ACT_W = 48
83
+ SIDE_W = 250
84
+ TAB_H = 35
85
+ CRUMB_H = 22
86
+ STATUS_H = 22
87
+ PANEL_H = 230
88
+ PANEL_TAB_H = 35
89
+ ROW_H = 22
90
+ RES_H = 38
91
+ EXT_H = 40
92
+ ACTIVITY = [
93
+ ("files", "explorer", "EXPLORER"),
94
+ ("search", "search", "SEARCH"),
95
+ ("git", "git", "SOURCE CONTROL"),
96
+ ("debug", "debug", "RUN AND DEBUG"),
97
+ ("ext", "extensions", "EXTENSIONS"),
98
+ ]
99
+
100
+
101
+ # ------------------------------------------------------------------ fonts
102
+ def _font(bundled, names, size, bold=False):
103
+ path = os.path.join(HERE, "fonts", bundled)
104
+ if os.path.exists(path):
105
+ return pygame.font.Font(path, size)
106
+ return pygame.font.SysFont(names, size, bold=bold)
107
+
108
+
109
+ CODE_FONT = _font("CodeFont.ttf", "cascadiacode,consolas,menlo,dejavusansmono,couriernew,monospace", 16)
110
+ UI_FONT = _font("UIFont.ttf", "segoeui,helveticaneue,helvetica,arial,dejavusans,sans", 14)
111
+ UI_SMALL = _font("UIFont.ttf", "segoeui,helveticaneue,helvetica,arial,dejavusans,sans", 12)
112
+ UI_BOLD = _font("UIFont.ttf", "segoeui,helveticaneue,helvetica,arial,dejavusans,sans", 12, bold=True)
113
+ LINE_H = CODE_FONT.get_linesize()
114
+ CODE_CW = CODE_FONT.size("0")[0]
115
+
116
+
117
+ # -------------------------------------------------------------- clipboard
118
+ _CLIP = {"text": ""}
119
+
120
+
121
+ def clipboard_get():
122
+ try:
123
+ data = pygame.scrap.get_text()
124
+ if data:
125
+ return data
126
+ except Exception:
127
+ pass
128
+ return _CLIP["text"]
129
+
130
+
131
+ def clipboard_set(text):
132
+ _CLIP["text"] = text
133
+ try:
134
+ pygame.scrap.put_text(text)
135
+ except Exception:
136
+ pass
137
+
138
+
139
+ # ------------------------------------------------------------------ icons
140
+ _ICON_CACHE = {}
141
+
142
+
143
+ def icon(name, color, size=24, bg=None):
144
+ # Antialiased monoline icon, drawn at 4x on a 24-unit grid then smoothed.
145
+ key = (name, color, size, bg)
146
+ if key in _ICON_CACHE:
147
+ return _ICON_CACHE[key]
148
+ K = 4
149
+ S = size * K
150
+ surf = pygame.Surface((S, S), pygame.SRCALPHA)
151
+ k = S / 24.0
152
+ sw = max(1, int(1.5 * k))
153
+
154
+ def P(x, y):
155
+ return (int(x * k), int(y * k))
156
+
157
+ def poly(points, closed=True):
158
+ pygame.draw.lines(surf, color, closed, [P(x, y) for x, y in points], sw)
159
+
160
+ def fill(points, c):
161
+ pygame.draw.polygon(surf, c, [P(x, y) for x, y in points])
162
+
163
+ def circ(x, y, r):
164
+ pygame.draw.circle(surf, color, P(x, y), max(1, int(r * k)), sw)
165
+
166
+ def ln(a, b):
167
+ pygame.draw.line(surf, color, P(*a), P(*b), sw)
168
+
169
+ def box(x, y, w, h):
170
+ pygame.draw.rect(surf, color, (int(x * k), int(y * k), int(w * k), int(h * k)), sw)
171
+
172
+ if name == "files":
173
+ poly([(9, 2), (17, 2), (21, 6), (21, 19), (9, 19)])
174
+ front = [(3, 6), (13, 6), (17, 10), (17, 22), (3, 22)]
175
+ if bg:
176
+ fill(front, bg)
177
+ poly(front)
178
+ elif name == "search":
179
+ circ(10, 10, 6)
180
+ ln((15, 15), (21, 21))
181
+ elif name == "git":
182
+ circ(6, 5, 2.6)
183
+ circ(6, 19, 2.6)
184
+ circ(18, 7, 2.6)
185
+ ln((6, 7.6), (6, 16.4))
186
+ ln((18, 9.6), (8, 16.8))
187
+ elif name == "debug":
188
+ poly([(7, 4), (20, 12), (7, 20)])
189
+ elif name == "play":
190
+ fill([(7, 4), (20, 12), (7, 20)], color)
191
+ elif name == "stop":
192
+ fill([(6, 6), (18, 6), (18, 18), (6, 18)], color)
193
+ elif name == "ext":
194
+ box(3, 3, 7, 7)
195
+ box(14, 3, 7, 7)
196
+ box(3, 14, 7, 7)
197
+ box(14, 14, 7, 7)
198
+ elif name == "account":
199
+ circ(12, 8, 4)
200
+ pygame.draw.arc(surf, color, (int(4 * k), int(13 * k), int(16 * k), int(14 * k)), 0, math.pi, sw)
201
+ elif name == "gear":
202
+ circ(12, 12, 5)
203
+ for i in range(8):
204
+ a = i * math.pi / 4
205
+ ln((12 + 6.5 * math.cos(a), 12 + 6.5 * math.sin(a)),
206
+ (12 + 10 * math.cos(a), 12 + 10 * math.sin(a)))
207
+ elif name == "bell":
208
+ poly([(6, 16), (6, 11), (12, 4), (18, 11), (18, 16)], closed=False)
209
+ ln((4, 16), (20, 16))
210
+ circ(12, 19.5, 1.6)
211
+ elif name == "close":
212
+ ln((6, 6), (18, 18))
213
+ ln((18, 6), (6, 18))
214
+
215
+ out = pygame.transform.smoothscale(surf, (size, size))
216
+ _ICON_CACHE[key] = out
217
+ return out
218
+
219
+
220
+ _LOGO_CACHE = {}
221
+
222
+
223
+ def logo(size=28):
224
+ # The FLEXCODE mark: a teal-to-violet tile with a white F and a cursor.
225
+ if size in _LOGO_CACHE:
226
+ return _LOGO_CACHE[size]
227
+ K = 4
228
+ S = size * K
229
+ k = S / 24.0
230
+ tile = pygame.Surface((S, S), pygame.SRCALPHA)
231
+ top, bottom = (24, 190, 170), (124, 92, 255)
232
+ for y in range(S):
233
+ t = y / (S - 1)
234
+ col = tuple(int(a + (b - a) * t) for a, b in zip(top, bottom))
235
+ pygame.draw.line(tile, col + (255,), (0, y), (S - 1, y))
236
+ mask = pygame.Surface((S, S), pygame.SRCALPHA)
237
+ pygame.draw.rect(mask, (255, 255, 255, 255), (0, 0, S, S), border_radius=int(S * 0.26))
238
+ tile.blit(mask, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
239
+
240
+ def R(x, y, w, h):
241
+ return pygame.Rect(int(x * k), int(y * k), int(w * k), int(h * k))
242
+
243
+ white = (250, 252, 255)
244
+ tile.fill(white, R(6, 5, 3.4, 14))
245
+ tile.fill(white, R(6, 5, 11, 3.2))
246
+ tile.fill(white, R(6, 10.4, 8.5, 2.8))
247
+ tile.fill(white, R(16.2, 14.5, 2.2, 5.2))
248
+ out = pygame.transform.smoothscale(tile, (size, size))
249
+ _LOGO_CACHE[size] = out
250
+ return out
251
+
252
+
253
+ def draw_chevron(s, x, cy, down, color):
254
+ if down:
255
+ pts = [(x - 4, cy - 2), (x + 4, cy - 2), (x, cy + 3)]
256
+ else:
257
+ pts = [(x - 2, cy - 4), (x + 3, cy), (x - 2, cy + 4)]
258
+ pygame.draw.polygon(s, color, pts)
259
+
260
+
261
+ def fit_text(font, text, max_w):
262
+ if font.size(text)[0] <= max_w:
263
+ return text
264
+ while text and font.size(text + "...")[0] > max_w:
265
+ text = text[:-1]
266
+ return text + "..."
267
+
268
+
269
+ def expand(s):
270
+ return s.replace("\t", " ")
271
+
272
+
273
+ # -------------------------------------------------------------- languages
274
+ def compile_lang(L):
275
+ rules = []
276
+ if L["multi"]:
277
+ opens = "|".join(re.escape(o) for o, _, _ in L["multi"])
278
+ rules.append(f"(?P<mopen>{opens})")
279
+ if L["comment"]:
280
+ rules.append(f"(?P<com>{L['comment']})")
281
+ for i, (_, rx, _) in enumerate(L["extra"]):
282
+ rules.append(f"(?P<x{i}>{rx})")
283
+ if L["strings"]:
284
+ alts = []
285
+ for q in L["strings"]:
286
+ qe = re.escape(q)
287
+ alts.append(qe + r"(?:\\.|(?!" + qe + r")[^\\])*" + qe)
288
+ rules.append("(?P<str>" + "|".join(alts) + ")")
289
+ rules.append(r"(?P<num>\b\d+(?:\.\d+)?\b)")
290
+ rules.append(r"(?P<fn>[A-Za-z_]\w*(?=\s*\())")
291
+ rules.append(r"(?P<word>[A-Za-z_]\w*)")
292
+ rules.append(r"(?P<other>\s+|.)")
293
+ return re.compile("|".join(rules))
294
+
295
+
296
+ def make_lang(id, name, ext, badge, comment=None, line_comment=None, strings=(), kw=(),
297
+ ctrl=(), builtin=(), extra=(), multi=(), heading=False, run=None):
298
+ L = dict(id=id, name=name, ext=list(ext), badge=badge, comment=comment,
299
+ line_comment=line_comment, strings=list(strings), kw=set(kw),
300
+ ctrl=set(ctrl), builtin=set(builtin), extra=list(extra), multi=list(multi),
301
+ heading=heading, run=run, enabled=True)
302
+ L["rx"] = compile_lang(L)
303
+ return L
304
+
305
+
306
+ PY_CTRL = {"if", "elif", "else", "for", "while", "return", "try", "except", "finally",
307
+ "raise", "break", "continue", "with", "yield", "await"}
308
+ PY_KW = {"def", "class", "import", "from", "as", "lambda", "global", "nonlocal", "pass",
309
+ "True", "False", "None", "and", "or", "not", "in", "is", "del", "assert", "async"}
310
+ PY_BUILTIN = {"print", "len", "range", "int", "str", "float", "list", "dict", "set", "tuple",
311
+ "bool", "open", "input", "type", "super", "self", "cls", "object", "isinstance",
312
+ "enumerate", "zip", "map", "filter", "min", "max", "sum"}
313
+ JS_CTRL = {"if", "else", "for", "while", "do", "return", "switch", "case", "break", "continue",
314
+ "try", "catch", "finally", "throw", "yield", "await"}
315
+ JS_KW = {"function", "const", "let", "var", "class", "new", "this", "import", "export", "from",
316
+ "default", "extends", "typeof", "instanceof", "null", "undefined", "true", "false",
317
+ "async", "static", "of", "delete", "void", "super"}
318
+ JS_BUILTIN = {"console", "Math", "JSON", "Object", "Array", "String", "Number", "Promise", "Map",
319
+ "Set", "document", "window", "Error", "Date", "Boolean"}
320
+ TS_KW = JS_KW | {"interface", "type", "enum", "implements", "private", "public", "protected",
321
+ "readonly", "as", "namespace", "declare", "keyof", "abstract"}
322
+ TS_BUILTIN = JS_BUILTIN | {"any", "string", "number", "boolean", "unknown", "never"}
323
+
324
+ LANGUAGES = [
325
+ make_lang("python", "Python", [".py"], ("PY", (55, 118, 171)),
326
+ comment=r"#.*", line_comment="# ", strings=['"', "'"],
327
+ kw=PY_KW, ctrl=PY_CTRL, builtin=PY_BUILTIN,
328
+ extra=[("decorator", r"@\w+", "fn")],
329
+ multi=[('"""', '"""', "str"), ("'''", "'''", "str")],
330
+ run=[sys.executable]),
331
+ make_lang("javascript", "JavaScript", [".js", ".jsx", ".mjs"], ("JS", (241, 224, 90)),
332
+ comment=r"//.*", line_comment="// ", strings=['"', "'", "`"],
333
+ kw=JS_KW, ctrl=JS_CTRL, builtin=JS_BUILTIN,
334
+ multi=[("/*", "*/", "com"), ("`", "`", "str")], run=["node"]),
335
+ make_lang("typescript", "TypeScript", [".ts", ".tsx"], ("TS", (49, 120, 198)),
336
+ comment=r"//.*", line_comment="// ", strings=['"', "'", "`"],
337
+ kw=TS_KW, ctrl=JS_CTRL, builtin=TS_BUILTIN,
338
+ multi=[("/*", "*/", "com"), ("`", "`", "str")]),
339
+ make_lang("json", "JSON", [".json"], ("{}", (203, 203, 65)),
340
+ strings=['"'], kw={"true", "false", "null"},
341
+ extra=[("key", r'"(?:\\.|[^"\\])*"(?=\s*:)', "typ")]),
342
+ make_lang("html", "HTML", [".html", ".htm"], ("<>", (227, 79, 38)),
343
+ strings=['"', "'"], multi=[("<!--", "-->", "com")],
344
+ extra=[("tag", r"</?[A-Za-z][\w-]*", "kw"),
345
+ ("attr", r"[A-Za-z_][\w-]*(?=\s*=)", "typ")]),
346
+ make_lang("css", "CSS", [".css"], ("#", (86, 156, 214)),
347
+ strings=['"', "'"], multi=[("/*", "*/", "com")],
348
+ kw={"inherit", "initial", "none", "auto", "important"},
349
+ extra=[("hex", r"#[0-9A-Fa-f]{3,8}\b", "num"),
350
+ ("prop", r"[A-Za-z-]+(?=\s*:)", "typ"),
351
+ ("selector", r"[.#]?[A-Za-z][\w-]*(?=\s*\{)", "fn")]),
352
+ make_lang("markdown", "Markdown", [".md"], ("MD", (81, 154, 186)), heading=True,
353
+ extra=[("link", r"\[[^\]]*\]\([^)]*\)", "fn"),
354
+ ("code", r"`[^`]*`", "str")]),
355
+ make_lang("plain", "Plain Text", [".txt"], ("TXT", (150, 150, 150))),
356
+ ]
357
+ LANG_BY_EXT = {ext: L for L in LANGUAGES for ext in L["ext"]}
358
+ PLAIN_LANG = LANGUAGES[-1]
359
+ _MAP = {"com": "com", "str": "str", "num": "num"}
360
+
361
+
362
+ def lang_for(name):
363
+ return LANG_BY_EXT.get(os.path.splitext(name)[1].lower(), PLAIN_LANG)
364
+
365
+
366
+ def tokenize(line, L, state=None):
367
+ # Split one line into (text, colour) tokens.
368
+ # `state` is None or (closing_delimiter, colour_key) when the line starts
369
+ # inside a multi-line string or comment. Returns (tokens, state_after_line).
370
+ if not L["enabled"]:
371
+ return [(line, C["plain"])], None
372
+ if L["heading"] and state is None and line.lstrip().startswith("#"):
373
+ return [(line, C["kw"])], None
374
+ out = []
375
+ pos = 0
376
+ opens = {o: (c, k) for o, c, k in L["multi"]}
377
+ while pos < len(line):
378
+ if state is not None:
379
+ close, ckey = state
380
+ idx = line.find(close, pos)
381
+ if idx < 0:
382
+ out.append((line[pos:], C[ckey]))
383
+ return out, state
384
+ end = idx + len(close)
385
+ out.append((line[pos:end], C[ckey]))
386
+ pos = end
387
+ state = None
388
+ continue
389
+ m = L["rx"].search(line, pos)
390
+ if m is None:
391
+ out.append((line[pos:], C["plain"]))
392
+ break
393
+ if m.start() > pos:
394
+ out.append((line[pos:m.start()], C["plain"]))
395
+ kind, text = m.lastgroup, m.group()
396
+ if m.end() <= pos: # safety: never loop on an empty match
397
+ out.append((line[pos], C["plain"]))
398
+ pos += 1
399
+ continue
400
+ if kind == "mopen":
401
+ close, ckey = opens[text]
402
+ out.append((text, C[ckey]))
403
+ state = (close, ckey)
404
+ elif kind.startswith("x"):
405
+ out.append((text, C[L["extra"][int(kind[1:])][2]]))
406
+ elif kind == "word":
407
+ if text in L["ctrl"]:
408
+ color = C["ctrl"]
409
+ elif text in L["kw"]:
410
+ color = C["kw"]
411
+ elif text in L["builtin"]:
412
+ color = C["typ"]
413
+ else:
414
+ color = C["plain"]
415
+ out.append((text, color))
416
+ elif kind == "fn":
417
+ if text in L["ctrl"]:
418
+ color = C["ctrl"]
419
+ elif text in L["kw"]:
420
+ color = C["kw"]
421
+ else:
422
+ color = C["fn"]
423
+ out.append((text, color))
424
+ else:
425
+ out.append((text, C[_MAP[kind]] if kind in _MAP else C["plain"]))
426
+ pos = m.end()
427
+ return out, state
428
+
429
+
430
+ # ----------------------------------------------------------- diagnostics
431
+ def diagnose(doc):
432
+ # Return [(row, message)] for syntax errors. Python is compiled, JSON parsed.
433
+ text = doc.text()
434
+ if doc.lang["id"] == "python":
435
+ try:
436
+ compile(text, doc.name, "exec")
437
+ return []
438
+ except SyntaxError as e:
439
+ return [(max(0, (e.lineno or 1) - 1), e.msg or "invalid syntax")]
440
+ except ValueError as e:
441
+ return [(0, str(e))]
442
+ if doc.lang["id"] == "json":
443
+ try:
444
+ json.loads(text)
445
+ return []
446
+ except json.JSONDecodeError as e:
447
+ return [(max(0, e.lineno - 1), e.msg)]
448
+ return []
449
+
450
+
451
+ # ------------------------------------------------------- cursor movement
452
+ def m_left(d):
453
+ if d.col > 0:
454
+ d.col -= 1
455
+ elif d.row > 0:
456
+ d.row -= 1
457
+ d.col = len(d.lines[d.row])
458
+
459
+
460
+ def m_right(d):
461
+ if d.col < len(d.lines[d.row]):
462
+ d.col += 1
463
+ elif d.row < len(d.lines) - 1:
464
+ d.row += 1
465
+ d.col = 0
466
+
467
+
468
+ def _is_word(ch):
469
+ return ch.isalnum() or ch == "_"
470
+
471
+
472
+ def m_word_left(d):
473
+ if d.col == 0:
474
+ m_left(d)
475
+ return
476
+ line = d.lines[d.row]
477
+ i = d.col
478
+ while i > 0 and not _is_word(line[i - 1]):
479
+ i -= 1
480
+ while i > 0 and _is_word(line[i - 1]):
481
+ i -= 1
482
+ d.col = i
483
+
484
+
485
+ def m_word_right(d):
486
+ line = d.lines[d.row]
487
+ if d.col >= len(line):
488
+ m_right(d)
489
+ return
490
+ i = d.col
491
+ while i < len(line) and _is_word(line[i]):
492
+ i += 1
493
+ while i < len(line) and not _is_word(line[i]):
494
+ i += 1
495
+ d.col = i
496
+
497
+
498
+ def m_up(d):
499
+ if d.row > 0:
500
+ d.row -= 1
501
+ d.col = min(d.col, len(d.lines[d.row]))
502
+
503
+
504
+ def m_down(d):
505
+ if d.row < len(d.lines) - 1:
506
+ d.row += 1
507
+ d.col = min(d.col, len(d.lines[d.row]))
508
+
509
+
510
+ def m_home(d):
511
+ line = d.lines[d.row]
512
+ first = len(line) - len(line.lstrip())
513
+ d.col = 0 if d.col == first else first
514
+
515
+
516
+ def m_end(d):
517
+ d.col = len(d.lines[d.row])
518
+
519
+
520
+ # ------------------------------------------------------------- document
521
+ class Document:
522
+ MAX_UNDO = 300
523
+
524
+ def __init__(self, path=None, name=None):
525
+ self.path = path
526
+ self.name = os.path.basename(path) if path else (name or "Untitled")
527
+ if path:
528
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
529
+ text = f.read()
530
+ self.lines = text.replace("\r\n", "\n").split("\n")
531
+ else:
532
+ self.lines = [""]
533
+ self.lang = lang_for(self.name)
534
+ self.row = 0
535
+ self.col = 0
536
+ self.scroll = 0
537
+ self.hscroll = 0
538
+ self.anchor = None
539
+ self.dirty = False
540
+ self.version = 0
541
+ self.undo_stack = []
542
+ self.redo_stack = []
543
+ self.last_kind = None
544
+ self._states = None
545
+ self._states_key = None
546
+
547
+ def text(self):
548
+ return "\n".join(self.lines)
549
+
550
+ def touch(self):
551
+ self.version += 1
552
+ self.dirty = True
553
+
554
+ def clamp(self):
555
+ self.row = max(0, min(self.row, len(self.lines) - 1))
556
+ self.col = max(0, min(self.col, len(self.lines[self.row])))
557
+
558
+ def line_states(self):
559
+ # State at the start of every line, so multi-line strings colour correctly.
560
+ key = (self.version, self.lang["id"], self.lang["enabled"])
561
+ if self._states_key != key:
562
+ states = []
563
+ st = None
564
+ for line in self.lines:
565
+ states.append(st)
566
+ _, st = tokenize(line, self.lang, st)
567
+ self._states = states
568
+ self._states_key = key
569
+ return self._states
570
+
571
+ def find_all(self, query):
572
+ if not query:
573
+ return []
574
+ q = query.lower()
575
+ out = []
576
+ for r, line in enumerate(self.lines):
577
+ low = line.lower()
578
+ start = 0
579
+ while True:
580
+ i = low.find(q, start)
581
+ if i < 0:
582
+ break
583
+ out.append((r, i, len(query)))
584
+ start = i + len(q)
585
+ return out
586
+
587
+ # selection
588
+ def has_sel(self):
589
+ return self.anchor is not None and self.anchor != (self.row, self.col)
590
+
591
+ def sel_range(self):
592
+ a, b = self.anchor, (self.row, self.col)
593
+ return (a, b) if a <= b else (b, a)
594
+
595
+ def selected_text(self):
596
+ (r1, c1), (r2, c2) = self.sel_range()
597
+ if r1 == r2:
598
+ return self.lines[r1][c1:c2]
599
+ return "\n".join([self.lines[r1][c1:]] + self.lines[r1 + 1:r2] + [self.lines[r2][:c2]])
600
+
601
+ def select_all(self):
602
+ self.anchor = (0, 0)
603
+ self.row = len(self.lines) - 1
604
+ self.col = len(self.lines[self.row])
605
+
606
+ def delete_selection(self):
607
+ (r1, c1), (r2, c2) = self.sel_range()
608
+ self.lines[r1:r2 + 1] = [self.lines[r1][:c1] + self.lines[r2][c2:]]
609
+ self.row, self.col = r1, c1
610
+ self.anchor = None
611
+
612
+ def word_at(self, row, col):
613
+ for m in re.finditer(r"\w+|[^\w\s]+", self.lines[row]):
614
+ if m.start() <= col <= m.end():
615
+ return m.start(), m.end()
616
+ return col, col
617
+
618
+ # undo / redo
619
+ def _snapshot(self):
620
+ self.undo_stack.append((list(self.lines), self.row, self.col))
621
+ if len(self.undo_stack) > self.MAX_UNDO:
622
+ self.undo_stack.pop(0)
623
+ self.redo_stack.clear()
624
+
625
+ def _pre(self, kind):
626
+ coalesce = kind in ("type", "back", "del") and self.last_kind == kind and not self.has_sel()
627
+ if not coalesce:
628
+ self._snapshot()
629
+ self.last_kind = kind
630
+ if self.has_sel():
631
+ self.delete_selection()
632
+ self.touch()
633
+
634
+ def undo(self):
635
+ if not self.undo_stack:
636
+ return
637
+ self.redo_stack.append((list(self.lines), self.row, self.col))
638
+ self.lines, self.row, self.col = self.undo_stack.pop()
639
+ self.anchor = None
640
+ self.last_kind = None
641
+ self.touch()
642
+
643
+ def redo(self):
644
+ if not self.redo_stack:
645
+ return
646
+ self.undo_stack.append((list(self.lines), self.row, self.col))
647
+ self.lines, self.row, self.col = self.redo_stack.pop()
648
+ self.anchor = None
649
+ self.last_kind = None
650
+ self.touch()
651
+
652
+ # editing
653
+ def insert(self, text, kind="type"):
654
+ self._pre(kind)
655
+ line = self.lines[self.row]
656
+ head, tail = line[:self.col], line[self.col:]
657
+ parts = text.split("\n")
658
+ if len(parts) == 1:
659
+ self.lines[self.row] = head + parts[0] + tail
660
+ self.col += len(parts[0])
661
+ else:
662
+ self.lines[self.row] = head + parts[0]
663
+ for p in parts[1:-1]:
664
+ self.row += 1
665
+ self.lines.insert(self.row, p)
666
+ self.row += 1
667
+ self.lines.insert(self.row, parts[-1] + tail)
668
+ self.col = len(parts[-1])
669
+
670
+ def newline(self):
671
+ self._pre("newline")
672
+ line = self.lines[self.row]
673
+ indent = re.match(r"[ \t]*", line).group()
674
+ head, tail = line[:self.col], line[self.col:]
675
+ extra = " " if head.rstrip().endswith(":") else ""
676
+ self.lines[self.row] = head
677
+ self.lines.insert(self.row + 1, indent + extra + tail)
678
+ self.row += 1
679
+ self.col = len(indent) + len(extra)
680
+
681
+ def backspace(self):
682
+ if self.has_sel():
683
+ self._pre("sel")
684
+ return
685
+ if self.row == 0 and self.col == 0:
686
+ return
687
+ self._pre("back")
688
+ if self.col > 0:
689
+ line = self.lines[self.row]
690
+ self.lines[self.row] = line[:self.col - 1] + line[self.col:]
691
+ self.col -= 1
692
+ else:
693
+ prev = self.lines[self.row - 1]
694
+ self.col = len(prev)
695
+ self.lines[self.row - 1] = prev + self.lines.pop(self.row)
696
+ self.row -= 1
697
+
698
+ def delete(self):
699
+ if self.has_sel():
700
+ self._pre("sel")
701
+ return
702
+ line = self.lines[self.row]
703
+ if self.col >= len(line) and self.row >= len(self.lines) - 1:
704
+ return
705
+ self._pre("del")
706
+ if self.col < len(line):
707
+ self.lines[self.row] = line[:self.col] + line[self.col + 1:]
708
+ else:
709
+ self.lines[self.row] = line + self.lines.pop(self.row + 1)
710
+
711
+ def toggle_comment(self):
712
+ prefix = self.lang["line_comment"]
713
+ if not prefix:
714
+ return
715
+ if self.has_sel():
716
+ (r1, _), (r2, _) = self.sel_range()
717
+ else:
718
+ r1 = r2 = self.row
719
+ self._snapshot()
720
+ self.last_kind = "comment"
721
+ block = self.lines[r1:r2 + 1]
722
+ bare = prefix.strip()
723
+ commented = all(l.strip() == "" or l.lstrip().startswith(bare) for l in block)
724
+ if commented:
725
+ for i in range(r1, r2 + 1):
726
+ l = self.lines[i]
727
+ s = l.lstrip()
728
+ ind = l[:len(l) - len(s)]
729
+ if s.startswith(prefix):
730
+ self.lines[i] = ind + s[len(prefix):]
731
+ elif s.startswith(bare):
732
+ self.lines[i] = ind + s[len(bare):]
733
+ else:
734
+ indent = min((len(l) - len(l.lstrip()) for l in block if l.strip()), default=0)
735
+ for i in range(r1, r2 + 1):
736
+ l = self.lines[i]
737
+ if l.strip():
738
+ self.lines[i] = l[:indent] + prefix + l[indent:]
739
+ self.touch()
740
+ self.clamp()
741
+
742
+
743
+ # ---------------------------------------------------------------- self-test
744
+ SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv"}
745
+ SEARCH_LIMIT = 500
746
+
747
+
748
+ def list_tree(root, expanded, limit=3000):
749
+ # Flat list of (path, depth, is_dir) for the explorer, honouring expanded folders.
750
+ rows = []
751
+
752
+ def walk(path, depth):
753
+ try:
754
+ names = os.listdir(path)
755
+ except OSError:
756
+ return
757
+ names.sort(key=lambda n: (not os.path.isdir(os.path.join(path, n)), n.lower()))
758
+ for n in names:
759
+ if n.startswith("."):
760
+ continue
761
+ full = os.path.join(path, n)
762
+ isdir = os.path.isdir(full)
763
+ rows.append((full, depth, isdir))
764
+ if isdir and full in expanded and len(rows) < limit:
765
+ walk(full, depth + 1)
766
+
767
+ walk(root, 0)
768
+ return rows
769
+
770
+
771
+ # output from the shell: CSI codes, OSC codes, other escapes, or one character
772
+ TERM_TOKEN = re.compile(r"\x1b\[([0-?]*)([ -/]*)([@-~])|\x1b\][^\x07]*\x07|\x1b.|[\s\S]")
773
+
774
+ # keys the shell needs as escape sequences
775
+ TERM_KEYS = {
776
+ pygame.K_UP: "\x1b[A", pygame.K_DOWN: "\x1b[B", pygame.K_RIGHT: "\x1b[C", pygame.K_LEFT: "\x1b[D",
777
+ pygame.K_HOME: "\x1b[H", pygame.K_END: "\x1b[F", pygame.K_DELETE: "\x1b[3~",
778
+ pygame.K_PAGEUP: "\x1b[5~", pygame.K_PAGEDOWN: "\x1b[6~", pygame.K_TAB: "\t",
779
+ pygame.K_RETURN: "\r", pygame.K_KP_ENTER: "\r", pygame.K_BACKSPACE: "\x7f", pygame.K_ESCAPE: "\x1b",
780
+ }
781
+
782
+
783
+ def open_system_terminal(folder):
784
+ # open the desktop's own terminal app in the project folder
785
+ options = [
786
+ ["gnome-terminal", f"--working-directory={folder}"],
787
+ ["x-terminal-emulator"],
788
+ ["konsole", "--workdir", folder],
789
+ ["xfce4-terminal", f"--working-directory={folder}"],
790
+ ]
791
+ for argv in options:
792
+ if shutil.which(argv[0]):
793
+ subprocess.Popen(argv, cwd=folder, start_new_session=True)
794
+ return True
795
+ return False
796
+
797
+
798
+ class Services:
799
+ def __init__(self, root):
800
+ self.root = root
801
+ self.inbox = queue.Queue()
802
+ self.master = None
803
+ self.pid = None
804
+ self.dead = True
805
+
806
+ # ---- processes (terminal and run) -----------------------------------
807
+ def alive(self):
808
+ return self.master is not None and not self.dead
809
+
810
+ def start_shell(self):
811
+ # start the real shell (bash, or $SHELL) on a pseudo-terminal
812
+ if self.alive():
813
+ return True
814
+ shell = os.environ.get("SHELL") or "/bin/bash"
815
+ pid, master = pty.fork()
816
+ if pid == 0:
817
+ try:
818
+ os.chdir(self.root)
819
+ os.environ["TERM"] = "xterm-256color"
820
+ os.execvp(shell, [shell, "-i"])
821
+ finally:
822
+ os._exit(127)
823
+ self.pid, self.master, self.dead = pid, master, False
824
+ threading.Thread(target=self._pty_reader, args=(master, pid), daemon=True).start()
825
+ return True
826
+
827
+ def _pty_reader(self, fd, pid):
828
+ while True:
829
+ try:
830
+ data = os.read(fd, 4096)
831
+ except OSError:
832
+ break
833
+ if not data:
834
+ break
835
+ self.inbox.put(("pty", data.decode("utf-8", "replace")))
836
+ self.dead = True
837
+ try:
838
+ _, status = os.waitpid(pid, 0)
839
+ code = os.waitstatus_to_exitcode(status)
840
+ except OSError:
841
+ code = -1
842
+ self.inbox.put(("done", "shell", code))
843
+
844
+ def write(self, text):
845
+ # type text into the shell as if on a keyboard
846
+ if not self.alive():
847
+ return False
848
+ try:
849
+ os.write(self.master, text.encode("utf-8"))
850
+ return True
851
+ except OSError:
852
+ return False
853
+
854
+ def set_root(self, folder):
855
+ self.root = folder
856
+ if self.alive():
857
+ self.write(f"cd {shlex.quote(folder)} && clear\n")
858
+ else:
859
+ self.start_shell()
860
+
861
+ def pick_file(self):
862
+ # use the desktop file picker (zenity) when it is installed
863
+ def work():
864
+ if not shutil.which("zenity"):
865
+ self.inbox.put(("picked", None, "nopicker"))
866
+ return
867
+ p = subprocess.run(["zenity", "--file-selection", "--title=Open file"],
868
+ capture_output=True, text=True)
869
+ if p.returncode == 0 and p.stdout.strip():
870
+ self.inbox.put(("picked", p.stdout.strip(), "ok"))
871
+ else:
872
+ self.inbox.put(("picked", None, "cancel"))
873
+
874
+ threading.Thread(target=work, daemon=True).start()
875
+
876
+
877
+
878
+
879
+
880
+
881
+ def kill(self):
882
+ if self.alive():
883
+ try:
884
+ os.kill(self.pid, signal.SIGHUP)
885
+ except OSError:
886
+ pass
887
+
888
+ # ---- git ------------------------------------------------------------
889
+ def git_refresh(self):
890
+ def work(root):
891
+ def git(*args):
892
+ return subprocess.run(["git", *args], cwd=root, capture_output=True,
893
+ text=True, errors="replace", timeout=10)
894
+ try:
895
+ top = git("rev-parse", "--show-toplevel")
896
+ if top.returncode != 0:
897
+ self.inbox.put(("git", None, [], False, "Not a git repository.", root))
898
+ return
899
+ repo = top.stdout.strip()
900
+ branch = git("rev-parse", "--abbrev-ref", "HEAD").stdout.strip()
901
+ changes = []
902
+ for line in git("status", "--porcelain").stdout.splitlines():
903
+ if len(line) > 3:
904
+ code = line[:2].strip() or "?"
905
+ changes.append((code, os.path.join(repo, line[3:].strip().strip('"'))))
906
+ self.inbox.put(("git", branch, changes, True, "", repo))
907
+ except (OSError, subprocess.SubprocessError):
908
+ self.inbox.put(("git", None, [], False, "Git is not available.", root))
909
+
910
+ threading.Thread(target=work, args=(self.root,), daemon=True).start()
911
+
912
+ # ---- search ---------------------------------------------------------
913
+ def search(self, query):
914
+ def work(q, root):
915
+ results = []
916
+ ql = q.lower()
917
+ for dirpath, dirnames, filenames in os.walk(root):
918
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and not d.startswith(".")]
919
+ for fn in filenames:
920
+ path = os.path.join(dirpath, fn)
921
+ try:
922
+ if os.path.getsize(path) > 2_000_000:
923
+ continue
924
+ with open(path, "r", encoding="utf-8", errors="ignore") as f:
925
+ for no, line in enumerate(f, 1):
926
+ if ql in line.lower():
927
+ results.append((path, no, line.strip()))
928
+ if len(results) >= SEARCH_LIMIT:
929
+ break
930
+ except OSError:
931
+ continue
932
+ if len(results) >= SEARCH_LIMIT:
933
+ break
934
+ if len(results) >= SEARCH_LIMIT:
935
+ break
936
+ self.inbox.put(("search", results))
937
+
938
+ threading.Thread(target=work, args=(query, self.root), daemon=True).start()
939
+
940
+
941
+ # ---------------------------------------------------------------- self-test
942
+
943
+ # ======================================================================
944
+ # Window: menus, UI, main loop
945
+ # ======================================================================
946
+ pygame.key.set_repeat(400, 35)
947
+ WIN_W, WIN_H = 1200, 800
948
+
949
+ PROJECTS_DIR = os.path.join(os.path.expanduser("~"), "FlexCodeProjects")
950
+
951
+
952
+ def default_project():
953
+ path = os.path.join(PROJECTS_DIR, "Scratch")
954
+ os.makedirs(path, exist_ok=True)
955
+ return path
956
+
957
+
958
+ MENUS = [
959
+ ("File", [("New File...", "Ctrl+N", "newfile"), ("Open File...", "Ctrl+O", "openfile"), ("New Project...", "Ctrl+Shift+N", "newproject"), ("Save", "Ctrl+S", "save"),
960
+ ("Close Editor", "Ctrl+W", "close"), None, ("Exit", "", "exit")]),
961
+ ("Edit", [("Undo", "Ctrl+Z", "undo"), ("Redo", "Ctrl+Y", "redo"), None,
962
+ ("Cut", "Ctrl+X", "cut"), ("Copy", "Ctrl+C", "copy"), ("Paste", "Ctrl+V", "paste"), None,
963
+ ("Find", "Ctrl+F", "find"), ("Toggle Line Comment", "Ctrl+/", "comment")]),
964
+ ("Selection", [("Select All", "Ctrl+A", "selectall")]),
965
+ ("View", [("Toggle Side Bar", "Ctrl+B", "sidebar"), ("Toggle Panel", "Ctrl+`", "panel"), None,
966
+ ("Explorer", "Ctrl+Shift+E", "mode_explorer"), ("Search", "Ctrl+Shift+F", "mode_search"),
967
+ ("Source Control", "Ctrl+Shift+G", "mode_git"), ("Run and Debug", "Ctrl+Shift+D", "mode_debug"),
968
+ ("Extensions", "", "mode_ext")]),
969
+ ("Go", [("Next Match", "Enter", "next_match"), ("Previous Match", "Shift+Enter", "prev_match"),
970
+ ("Next Problem", "", "next_problem")]),
971
+ ("Run", [("Run Active File", "F5", "run"), ("Stop Running", "Ctrl+C", "stop")]),
972
+ ("Terminal", [("Focus Terminal", "Ctrl+`", "term_focus"), ("Clear Terminal", "Ctrl+L", "term_clear"), ("Open System Terminal", "", "systerm")]),
973
+ ("Help", [("About FLEXCODE", "", "about")]),
974
+ ]
975
+ MODE_OF = {"explorer": "explorer", "search": "search", "git": "git", "debug": "debug", "ext": "extensions"}
976
+
977
+
978
+ class FlexCode:
979
+ def __init__(self, root):
980
+ self.root = os.path.abspath(root)
981
+ self.root_name = os.path.basename(self.root.rstrip(os.sep)) or self.root
982
+ self.svc = Services(self.root)
983
+ self.expanded = {self.root}
984
+ self.tree_rows = list_tree(self.root, self.expanded)
985
+ self.docs = []
986
+ self.active = -1
987
+ self.untitled = 0
988
+ self.sidebar_open = True
989
+ self.panel_open = True
990
+ self.mode = "explorer"
991
+ self.focus = "editor" # editor | search | terminal | find
992
+ self.panel_tab = "TERMINAL"
993
+ self.open_menu = None
994
+ self.quit = False
995
+
996
+ self.menu_label_rects = []
997
+ self.menu_item_rects = []
998
+ self.tab_rects = []
999
+ self.panel_tab_rects = []
1000
+ self.problem_rects = []
1001
+ self.panel_close = pygame.Rect(0, 0, 0, 0)
1002
+ self.expl_scroll = 0
1003
+ self.res_scroll = 0
1004
+ self.vis_lines = 20
1005
+ self.dragging = False
1006
+ self.last_click = (0, -1, -1)
1007
+
1008
+ self.output = [(f"{APP_NAME} {APP_VERSION} ready.", C["dim"])]
1009
+ self.term = [("Terminal ready. Type a command and press Enter.", C["dim"])]
1010
+ self.term_partial = ""
1011
+ self.tcol = 0
1012
+ self.prompt = None
1013
+ self.run_rect = pygame.Rect(0, 0, 0, 0)
1014
+ self.newfile_rect = pygame.Rect(0, 0, 0, 0)
1015
+
1016
+ self.problems = []
1017
+ self.diag_key = None
1018
+ self.diag_seen = None
1019
+ self.diag_time = 0
1020
+
1021
+ self.find_open = False
1022
+ self.find_query = ""
1023
+ self.find_list = []
1024
+ self.find_idx = 0
1025
+ self.find_key = None
1026
+
1027
+ self.search_query = ""
1028
+ self.search_results = []
1029
+ self.search_busy = False
1030
+ self.search_done = False
1031
+
1032
+ self.git_ok = False
1033
+ self.git_branch = None
1034
+ self.git_changes = []
1035
+ self.git_msg = ""
1036
+ self.git_root = self.root
1037
+ self.run_status = "Press F5 to run the active file in the terminal."
1038
+
1039
+ self.new_doc()
1040
+ self.svc.git_refresh()
1041
+ self.svc.start_shell()
1042
+
1043
+ # ------------------------------------------------------------ helpers
1044
+ def doc(self):
1045
+ if 0 <= self.active < len(self.docs):
1046
+ return self.docs[self.active]
1047
+ return None
1048
+
1049
+ def notify(self, msg, color=None):
1050
+ self.output.append((msg, color or C["dim"]))
1051
+ self.output = self.output[-500:]
1052
+
1053
+ def new_doc(self):
1054
+ self.untitled += 1
1055
+ self.docs.append(Document(name=f"Untitled-{self.untitled}"))
1056
+ self.active = len(self.docs) - 1
1057
+
1058
+ def open_file(self, path):
1059
+ for i, d in enumerate(self.docs):
1060
+ if d.path == path:
1061
+ self.active = i
1062
+ return True
1063
+ try:
1064
+ self.docs.append(Document(path))
1065
+ except OSError as e:
1066
+ self.notify(f"Could not open {path}: {e}", C["error"])
1067
+ return False
1068
+ self.active = len(self.docs) - 1
1069
+ self.notify(f"Opened {os.path.basename(path)}")
1070
+ return True
1071
+
1072
+ def close_tab(self, i):
1073
+ del self.docs[i]
1074
+ if not self.docs:
1075
+ self.new_doc()
1076
+ return
1077
+ if i < self.active:
1078
+ self.active -= 1
1079
+ elif i == self.active:
1080
+ self.active = min(i, len(self.docs) - 1)
1081
+
1082
+ def save(self):
1083
+ d = self.doc()
1084
+ if d is None:
1085
+ return
1086
+ if not d.path:
1087
+ name = d.name if "." in d.name else d.name + ".txt"
1088
+ d.name = name
1089
+ d.lang = LANG_BY_EXT.get(os.path.splitext(name)[1].lower(), d.lang)
1090
+ d.path = os.path.join(self.root, name)
1091
+ try:
1092
+ with open(d.path, "w", encoding="utf-8") as f:
1093
+ f.write(d.text())
1094
+ d.dirty = False
1095
+ self.tree_rows = list_tree(self.root, self.expanded)
1096
+ self.notify(f"Saved {d.name}")
1097
+ self.svc.git_refresh()
1098
+ except OSError as e:
1099
+ self.notify(f"Save failed: {e}", C["error"])
1100
+
1101
+ def set_mode(self, mode):
1102
+ if self.mode == mode and self.sidebar_open:
1103
+ self.sidebar_open = False
1104
+ self.focus = "editor"
1105
+ return
1106
+ self.mode = mode
1107
+ self.sidebar_open = True
1108
+ self.focus = "search" if mode == "search" else "editor"
1109
+ if mode == "git":
1110
+ self.svc.git_refresh()
1111
+
1112
+ def geometry(self, w, h):
1113
+ bottom = h - STATUS_H
1114
+ side_w = SIDE_W if self.sidebar_open else 0
1115
+ x = ACT_W + side_w
1116
+ ph = PANEL_H if self.panel_open else 0
1117
+ return {
1118
+ "activity": pygame.Rect(0, TITLE_H, ACT_W, bottom - TITLE_H),
1119
+ "side": pygame.Rect(ACT_W, TITLE_H, side_w, bottom - TITLE_H),
1120
+ "editor": pygame.Rect(x, TITLE_H, w - x, bottom - TITLE_H - ph),
1121
+ "panel": pygame.Rect(x, bottom - ph, w - x, ph),
1122
+ "status": pygame.Rect(0, bottom, w, STATUS_H),
1123
+ }
1124
+
1125
+ def code_rect(self, ed):
1126
+ top = ed.y + TAB_H + CRUMB_H
1127
+ return pygame.Rect(ed.x, top, ed.w, ed.bottom - top)
1128
+
1129
+ def gutter_width(self, d):
1130
+ return CODE_CW * max(3, len(str(len(d.lines)))) + 36
1131
+
1132
+ def pos_to_rc(self, d, x, y, code):
1133
+ row = max(0, min(len(d.lines) - 1, d.scroll + (y - code.y) // LINE_H))
1134
+ target = x - (code.x + self.gutter_width(d) - d.hscroll)
1135
+ line = d.lines[row]
1136
+ best, best_d = 0, 10 ** 9
1137
+ for c in range(len(line) + 1):
1138
+ dx = abs(CODE_FONT.size(expand(line[:c]))[0] - target)
1139
+ if dx < best_d:
1140
+ best, best_d = c, dx
1141
+ return row, best
1142
+
1143
+ # ------------------------------------------------------- background
1144
+ def pump(self):
1145
+ while True:
1146
+ try:
1147
+ m = self.svc.inbox.get_nowait()
1148
+ except queue.Empty:
1149
+ break
1150
+ kind = m[0]
1151
+ if kind == "pty":
1152
+ self.feed_terminal(m[1])
1153
+ elif kind == "done":
1154
+ self.term.append((f"[shell exited with code {m[2]}]", C["dim"]))
1155
+ self.term_partial, self.tcol = "", 0
1156
+ elif kind == "search":
1157
+ self.search_results = m[1]
1158
+ self.search_busy = False
1159
+ self.search_done = True
1160
+ self.res_scroll = 0
1161
+ elif kind == "git":
1162
+ _, branch, changes, ok, err, repo = m
1163
+ self.git_ok, self.git_branch = ok, branch
1164
+ self.git_changes, self.git_msg, self.git_root = changes, err, repo
1165
+ elif kind == "picked":
1166
+ _, path, reason = m
1167
+ if reason == "ok" and path:
1168
+ self.open_file(path)
1169
+ elif reason == "nopicker":
1170
+ self.prompt = {"label": "Open file (full path)", "text": "", "action": "openpath"}
1171
+
1172
+ def update_diagnostics(self):
1173
+ d = self.doc()
1174
+ if d is None:
1175
+ self.problems = []
1176
+ return
1177
+ now = pygame.time.get_ticks()
1178
+ key = (id(d), d.version)
1179
+ if key == self.diag_key:
1180
+ return
1181
+ if self.diag_seen != key:
1182
+ self.diag_seen, self.diag_time = key, now
1183
+ return
1184
+ if now - self.diag_time >= 500: # wait until typing pauses
1185
+ self.problems = diagnose(d)
1186
+ self.diag_key = key
1187
+
1188
+ def update_find(self):
1189
+ if not self.find_open:
1190
+ return
1191
+ d = self.doc()
1192
+ if d is None:
1193
+ self.find_list = []
1194
+ return
1195
+ key = (id(d), d.version, self.find_query)
1196
+ if key != self.find_key:
1197
+ self.find_key = key
1198
+ self.find_list = d.find_all(self.find_query)
1199
+ self.find_idx = min(self.find_idx, max(0, len(self.find_list) - 1))
1200
+
1201
+ # ------------------------------------------------------------ find
1202
+ def open_find(self):
1203
+ d = self.doc()
1204
+ if d is not None and d.has_sel() and d.sel_range()[0][0] == d.sel_range()[1][0]:
1205
+ self.find_query = d.selected_text()
1206
+ self.find_open = True
1207
+ self.find_key = None
1208
+ self.focus = "find"
1209
+ self.update_find()
1210
+ self.jump_to_match(first_after_cursor=True)
1211
+
1212
+ def close_find(self):
1213
+ self.find_open = False
1214
+ self.focus = "editor"
1215
+
1216
+ def jump_to_match(self, first_after_cursor=False):
1217
+ d = self.doc()
1218
+ if d is None or not self.find_list:
1219
+ return
1220
+ if first_after_cursor:
1221
+ here = (d.row, d.col)
1222
+ for i, (r, c, _) in enumerate(self.find_list):
1223
+ if (r, c) >= here:
1224
+ self.find_idx = i
1225
+ break
1226
+ else:
1227
+ self.find_idx = 0
1228
+ r, c, n = self.find_list[self.find_idx]
1229
+ d.anchor = (r, c)
1230
+ d.row, d.col = r, c + n
1231
+ d.clamp()
1232
+
1233
+ def find_step(self, step):
1234
+ if not self.find_open:
1235
+ self.open_find()
1236
+ return
1237
+ if self.find_list:
1238
+ self.find_idx = (self.find_idx + step) % len(self.find_list)
1239
+ self.jump_to_match()
1240
+
1241
+ def find_key_handler(self, e, shift):
1242
+ k = e.key
1243
+ if k == pygame.K_ESCAPE:
1244
+ self.close_find()
1245
+ elif k in (pygame.K_RETURN, pygame.K_KP_ENTER):
1246
+ self.find_step(-1 if shift else 1)
1247
+ elif k == pygame.K_BACKSPACE:
1248
+ self.find_query = self.find_query[:-1]
1249
+ self.find_key = None
1250
+ self.update_find()
1251
+ self.jump_to_match(first_after_cursor=True)
1252
+
1253
+ # ------------------------------------------------------- problems
1254
+ def jump_problem(self, forward=True):
1255
+ d = self.doc()
1256
+ if d is None or not self.problems:
1257
+ return
1258
+ rows = sorted(r for r, _ in self.problems)
1259
+ if forward:
1260
+ nxt = [r for r in rows if r > d.row] or rows
1261
+ d.row = nxt[0]
1262
+ else:
1263
+ prv = [r for r in rows if r < d.row] or rows[::-1]
1264
+ d.row = prv[-1]
1265
+ d.col = len(d.lines[d.row]) - len(d.lines[d.row].lstrip())
1266
+ d.anchor = None
1267
+
1268
+ # ---------------------------------------------------------- actions
1269
+ def run_active(self):
1270
+ d = self.doc()
1271
+ if d is None:
1272
+ return
1273
+ if d.lang["run"] is None:
1274
+ self.notify(f"No runner is set up for {d.lang['name']} files.", C["error"])
1275
+ return
1276
+ if not d.path or d.dirty:
1277
+ self.save()
1278
+ if not d.path:
1279
+ return
1280
+ self.panel_open = True
1281
+ self.panel_tab = "TERMINAL"
1282
+ self.focus = "terminal"
1283
+ self.svc.start_shell()
1284
+ command = " ".join(shlex.quote(a) for a in d.lang["run"] + [d.path])
1285
+ self.svc.write(command + "\n")
1286
+
1287
+ def do(self, action):
1288
+ d = self.doc()
1289
+ if action == "new":
1290
+ self.new_doc()
1291
+ self.focus = "editor"
1292
+ elif action == "save":
1293
+ self.save()
1294
+ elif action == "close":
1295
+ if self.docs:
1296
+ self.close_tab(self.active)
1297
+ elif action == "exit":
1298
+ self.quit = True
1299
+ elif action == "undo" and d:
1300
+ d.undo()
1301
+ elif action == "redo" and d:
1302
+ d.redo()
1303
+ elif action in ("cut", "copy", "paste"):
1304
+ self.editor_ctrl({"cut": pygame.K_x, "copy": pygame.K_c, "paste": pygame.K_v}[action], False)
1305
+ elif action == "selectall" and d:
1306
+ d.select_all()
1307
+ elif action == "find":
1308
+ self.open_find()
1309
+ elif action == "comment" and d:
1310
+ d.toggle_comment()
1311
+ elif action == "sidebar":
1312
+ self.sidebar_open = not self.sidebar_open
1313
+ elif action == "panel":
1314
+ self.panel_open = not self.panel_open
1315
+ self.focus = "terminal" if self.panel_open and self.panel_tab == "TERMINAL" else "editor"
1316
+ elif action.startswith("mode_"):
1317
+ self.set_mode(MODE_OF[action[5:]])
1318
+ elif action == "run":
1319
+ self.run_active()
1320
+ elif action == "stop":
1321
+ self.svc.write("\x03")
1322
+ elif action == "term_focus":
1323
+ self.svc.start_shell()
1324
+ self.panel_open = True
1325
+ self.panel_tab = "TERMINAL"
1326
+ self.focus = "terminal"
1327
+ elif action == "term_clear":
1328
+ self.term.clear()
1329
+ elif action == "next_match":
1330
+ self.find_step(1)
1331
+ elif action == "prev_match":
1332
+ self.find_step(-1)
1333
+ elif action == "next_problem":
1334
+ self.jump_problem(True)
1335
+ elif action == "newfile":
1336
+ self.prompt = {"label": "New file name", "text": "", "action": "newfile"}
1337
+ elif action == "newproject":
1338
+ self.prompt = {"label": "Project name (created in ~/FlexCodeProjects)", "text": "", "action": "newproject"}
1339
+ elif action == "openfile":
1340
+ self.svc.pick_file()
1341
+ elif action == "systerm":
1342
+ if not open_system_terminal(self.root):
1343
+ self.notify("No terminal app found. Install gnome-terminal.", C["error"])
1344
+ elif action == "about":
1345
+ self.notify(f"{APP_NAME} {APP_VERSION}: a code editor built with pygame.", C["added"])
1346
+ self.panel_open = True
1347
+ self.panel_tab = "OUTPUT"
1348
+ self.open_menu = None
1349
+
1350
+ # ---------------------------------------------------------- events
1351
+ def handle_event(self, e, w, h):
1352
+ if e.type == pygame.KEYDOWN:
1353
+ self.on_key(e)
1354
+ elif e.type == pygame.TEXTINPUT:
1355
+ self.on_text(e.text)
1356
+ elif e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
1357
+ self.on_click(e.pos, self.geometry(w, h))
1358
+ elif e.type == pygame.MOUSEBUTTONUP and e.button == 1:
1359
+ self.dragging = False
1360
+ d = self.doc()
1361
+ if d is not None and d.anchor == (d.row, d.col):
1362
+ d.anchor = None
1363
+ elif e.type == pygame.MOUSEMOTION:
1364
+ self.on_motion(e.pos, self.geometry(w, h))
1365
+ elif e.type == pygame.MOUSEWHEEL:
1366
+ self.on_wheel(e.y, self.geometry(w, h))
1367
+
1368
+ def on_text(self, text):
1369
+ if self.prompt is not None:
1370
+ self.prompt["text"] += text
1371
+ return
1372
+ if pygame.key.get_mods() & (pygame.KMOD_CTRL | pygame.KMOD_META) or not text:
1373
+ return
1374
+ if self.focus == "editor":
1375
+ d = self.doc()
1376
+ if d is not None:
1377
+ d.insert(text.replace("\r", ""))
1378
+ elif self.focus == "search":
1379
+ self.search_query += text
1380
+ elif self.focus == "terminal":
1381
+ self.svc.write(text)
1382
+ elif self.focus == "find":
1383
+ self.find_query += text
1384
+ self.find_key = None
1385
+ self.update_find()
1386
+ self.jump_to_match(first_after_cursor=True)
1387
+
1388
+ def on_motion(self, pos, g):
1389
+ if self.dragging:
1390
+ d = self.doc()
1391
+ if d is not None:
1392
+ d.row, d.col = self.pos_to_rc(d, pos[0], pos[1], self.code_rect(g["editor"]))
1393
+ d.clamp()
1394
+ elif self.open_menu is not None:
1395
+ for i, (rect, _) in enumerate(self.menu_label_rects):
1396
+ if rect.collidepoint(pos):
1397
+ self.open_menu = i
1398
+ break
1399
+
1400
+ def on_wheel(self, dy, g):
1401
+ mouse = pygame.mouse.get_pos()
1402
+ if g["editor"].collidepoint(mouse):
1403
+ d = self.doc()
1404
+ if d is not None:
1405
+ d.scroll = max(0, min(len(d.lines) - 1, d.scroll - dy * 3))
1406
+ elif g["side"].collidepoint(mouse):
1407
+ if self.mode == "explorer":
1408
+ limit = max(0, len(self.tree_rows) * ROW_H - (g["side"].h - 62))
1409
+ self.expl_scroll = max(0, min(limit, self.expl_scroll - dy * ROW_H))
1410
+ elif self.mode == "search":
1411
+ limit = max(0, len(self.search_results) * RES_H - (g["side"].h - 110))
1412
+ self.res_scroll = max(0, min(limit, self.res_scroll - dy * RES_H))
1413
+
1414
+ def on_key(self, e):
1415
+ if self.prompt is not None:
1416
+ self.prompt_key(e)
1417
+ return
1418
+ mods = e.mod
1419
+ ctrl = mods & (pygame.KMOD_CTRL | pygame.KMOD_META)
1420
+ shift = bool(mods & pygame.KMOD_SHIFT)
1421
+ k = e.key
1422
+
1423
+ if k == pygame.K_ESCAPE and self.open_menu is not None:
1424
+ self.open_menu = None
1425
+ return
1426
+ if k == pygame.K_F5:
1427
+ self.run_active()
1428
+ return
1429
+ if ctrl:
1430
+ if shift:
1431
+ sh = {pygame.K_f: "mode_search", pygame.K_g: "mode_git",
1432
+ pygame.K_e: "mode_explorer", pygame.K_d: "mode_debug", pygame.K_n: "newproject"}
1433
+ if k in sh:
1434
+ self.do(sh[k])
1435
+ return
1436
+ simple = {pygame.K_s: "save", pygame.K_o: "openfile", pygame.K_n: "newfile", pygame.K_w: "close",
1437
+ pygame.K_b: "sidebar", pygame.K_BACKQUOTE: "panel"}
1438
+ if k in simple:
1439
+ self.do(simple[k])
1440
+ return
1441
+ if k == pygame.K_f:
1442
+ self.do("find")
1443
+ return
1444
+ if k == pygame.K_l and self.focus != "terminal":
1445
+ self.do("term_clear")
1446
+ return
1447
+ if self.focus == "terminal":
1448
+ self.terminal_ctrl(k)
1449
+ elif self.focus == "search":
1450
+ if k == pygame.K_v:
1451
+ self.search_query += clipboard_get().replace("\n", " ")
1452
+ elif self.focus in ("editor", "find"):
1453
+ self.editor_ctrl(k, shift)
1454
+ return
1455
+
1456
+ if self.focus == "terminal":
1457
+ self.terminal_key(e)
1458
+ elif self.focus == "search":
1459
+ self.search_key(e)
1460
+ elif self.focus == "find":
1461
+ self.find_key_handler(e, shift)
1462
+ else:
1463
+ self.editor_key(e, shift)
1464
+
1465
+ def terminal_ctrl(self, k):
1466
+ if k == pygame.K_v:
1467
+ self.svc.write(clipboard_get().replace("\n", "\r"))
1468
+ elif pygame.K_a <= k <= pygame.K_z:
1469
+ self.svc.write(chr(k - 96))
1470
+
1471
+ def terminal_key(self, e):
1472
+ seq = TERM_KEYS.get(e.key)
1473
+ if seq:
1474
+ self.svc.write(seq)
1475
+
1476
+ def search_key(self, e):
1477
+ k = e.key
1478
+ if k in (pygame.K_RETURN, pygame.K_KP_ENTER):
1479
+ query = self.search_query.strip()
1480
+ if query:
1481
+ self.search_busy, self.search_done = True, False
1482
+ self.search_results = []
1483
+ self.svc.search(query)
1484
+ elif k == pygame.K_BACKSPACE:
1485
+ self.search_query = self.search_query[:-1]
1486
+ elif k in (pygame.K_ESCAPE, pygame.K_TAB):
1487
+ self.focus = "editor"
1488
+
1489
+ def editor_ctrl(self, k, shift):
1490
+ d = self.doc()
1491
+ if d is None:
1492
+ return
1493
+ if shift and k == pygame.K_z:
1494
+ d.redo()
1495
+ elif k == pygame.K_a:
1496
+ d.select_all()
1497
+ elif k == pygame.K_c:
1498
+ clipboard_set(d.selected_text() if d.has_sel() else d.lines[d.row] + "\n")
1499
+ elif k == pygame.K_x:
1500
+ if d.has_sel():
1501
+ clipboard_set(d.selected_text())
1502
+ d.insert("", kind="cut")
1503
+ else:
1504
+ clipboard_set(d.lines[d.row] + "\n")
1505
+ d.anchor = (d.row, 0)
1506
+ if d.row < len(d.lines) - 1:
1507
+ d.row += 1
1508
+ d.col = 0
1509
+ else:
1510
+ d.col = len(d.lines[d.row])
1511
+ d.insert("", kind="cut")
1512
+ elif k == pygame.K_v:
1513
+ text = clipboard_get().replace("\r\n", "\n").replace("\r", "\n")
1514
+ d.insert(text, kind="paste")
1515
+ elif k == pygame.K_z:
1516
+ d.undo()
1517
+ elif k == pygame.K_y:
1518
+ d.redo()
1519
+ elif k == pygame.K_SLASH:
1520
+ d.toggle_comment()
1521
+ elif k == pygame.K_LEFT:
1522
+ self._move(d, shift, m_word_left)
1523
+ elif k == pygame.K_RIGHT:
1524
+ self._move(d, shift, m_word_right)
1525
+ d.clamp()
1526
+
1527
+ def _move(self, d, shift, fn):
1528
+ if shift:
1529
+ if d.anchor is None:
1530
+ d.anchor = (d.row, d.col)
1531
+ else:
1532
+ d.anchor = None
1533
+ fn(d)
1534
+ d.clamp()
1535
+ if shift and d.anchor == (d.row, d.col):
1536
+ d.anchor = None
1537
+ d.last_kind = None
1538
+
1539
+ def editor_key(self, e, shift):
1540
+ d = self.doc()
1541
+ if d is None:
1542
+ return
1543
+ k = e.key
1544
+ moves = {pygame.K_LEFT: m_left, pygame.K_RIGHT: m_right, pygame.K_UP: m_up,
1545
+ pygame.K_DOWN: m_down, pygame.K_HOME: m_home, pygame.K_END: m_end}
1546
+ if k in moves:
1547
+ self._move(d, shift, moves[k])
1548
+ elif k == pygame.K_PAGEUP:
1549
+ self._move(d, shift, lambda dd: setattr(dd, "row", max(0, dd.row - self.vis_lines)))
1550
+ elif k == pygame.K_PAGEDOWN:
1551
+ self._move(d, shift, lambda dd: setattr(dd, "row", min(len(dd.lines) - 1, dd.row + self.vis_lines)))
1552
+ elif k == pygame.K_BACKSPACE:
1553
+ d.backspace()
1554
+ elif k == pygame.K_DELETE:
1555
+ d.delete()
1556
+ elif k in (pygame.K_RETURN, pygame.K_KP_ENTER):
1557
+ d.newline()
1558
+ elif k == pygame.K_TAB:
1559
+ d.insert(" ")
1560
+ elif k == pygame.K_ESCAPE:
1561
+ if self.find_open:
1562
+ self.close_find()
1563
+ d.anchor = None
1564
+ d.clamp()
1565
+
1566
+ # ------------------------------------------------------------ clicks
1567
+ def _on_click_base(self, pos, g):
1568
+ x, y = pos
1569
+
1570
+ # an open menu: an item click runs it, anything else closes the menu
1571
+ if self.open_menu is not None:
1572
+ for rect, action in self.menu_item_rects:
1573
+ if rect.collidepoint(pos):
1574
+ if action:
1575
+ self.do(action)
1576
+ self.open_menu = None
1577
+ return
1578
+ for i, (rect, _) in enumerate(self.menu_label_rects):
1579
+ if rect.collidepoint(pos):
1580
+ self.open_menu = None if self.open_menu == i else i
1581
+ return
1582
+ self.open_menu = None
1583
+ return
1584
+
1585
+ for i, (rect, _) in enumerate(self.menu_label_rects):
1586
+ if rect.collidepoint(pos):
1587
+ self.open_menu = i
1588
+ return
1589
+
1590
+ if g["activity"].collidepoint(pos):
1591
+ bottom = g["status"].y
1592
+ for i, (_, mode, _) in enumerate(ACTIVITY):
1593
+ if pygame.Rect(0, TITLE_H + 4 + i * 48, ACT_W, 48).collidepoint(pos):
1594
+ self.set_mode(mode)
1595
+ return
1596
+ if pygame.Rect(0, bottom - 96, ACT_W, 48).collidepoint(pos):
1597
+ self.notify("Accounts are not available in this build.")
1598
+ elif pygame.Rect(0, bottom - 48, ACT_W, 48).collidepoint(pos):
1599
+ self.notify("Settings are in the constants at the top of this file.")
1600
+ return
1601
+
1602
+ if g["side"].collidepoint(pos) and self.sidebar_open:
1603
+ self.on_side_click(pos, g["side"])
1604
+ return
1605
+
1606
+ if g["panel"].collidepoint(pos) and self.panel_open:
1607
+ self.on_panel_click(pos)
1608
+ return
1609
+
1610
+ for i, tr, close_r in self.tab_rects:
1611
+ if close_r.collidepoint(pos):
1612
+ self.close_tab(i)
1613
+ return
1614
+ if tr.collidepoint(pos):
1615
+ self.active = i
1616
+ self.focus = "editor"
1617
+ return
1618
+
1619
+ ed = g["editor"]
1620
+ d = self.doc()
1621
+ code = self.code_rect(ed)
1622
+ if d is None or not code.collidepoint(pos):
1623
+ return
1624
+ self.focus = "editor"
1625
+ row, col = self.pos_to_rc(d, x, y, code)
1626
+ now = pygame.time.get_ticks()
1627
+ last_t, last_row, last_col = self.last_click
1628
+ if now - last_t < 400 and last_row == row and last_col == col:
1629
+ a, b = d.word_at(row, col)
1630
+ d.anchor = (row, a)
1631
+ d.row, d.col = row, b
1632
+ self.last_click = (0, -1, -1)
1633
+ else:
1634
+ d.row, d.col = row, col
1635
+ d.anchor = (row, col)
1636
+ self.dragging = True
1637
+ self.last_click = (now, row, col)
1638
+ d.last_kind = None
1639
+
1640
+ def on_panel_click(self, pos):
1641
+ if self.panel_close.collidepoint(pos):
1642
+ self.panel_open = False
1643
+ self.focus = "editor"
1644
+ return
1645
+ for name, rect in self.panel_tab_rects:
1646
+ if rect.collidepoint(pos):
1647
+ self.panel_tab = name
1648
+ self.focus = "terminal" if name == "TERMINAL" else "editor"
1649
+ return
1650
+ if self.panel_tab == "PROBLEMS":
1651
+ for rect, idx in self.problem_rects:
1652
+ if rect.collidepoint(pos):
1653
+ d = self.doc()
1654
+ if d is not None:
1655
+ d.row = self.problems[idx][0]
1656
+ d.col = 0
1657
+ d.anchor = None
1658
+ self.focus = "editor"
1659
+ return
1660
+ if self.panel_tab == "TERMINAL":
1661
+ self.focus = "terminal"
1662
+
1663
+ def on_side_click(self, pos, side):
1664
+ x, y = pos
1665
+ if self.mode == "explorer":
1666
+ top = side.y + 62
1667
+ if y >= top:
1668
+ idx = (y - top + self.expl_scroll) // ROW_H
1669
+ if 0 <= idx < len(self.tree_rows):
1670
+ path, _, isdir = self.tree_rows[idx]
1671
+ if isdir:
1672
+ if path in self.expanded:
1673
+ self.expanded.discard(path)
1674
+ else:
1675
+ self.expanded.add(path)
1676
+ self.tree_rows = list_tree(self.root, self.expanded)
1677
+ else:
1678
+ self.open_file(path)
1679
+
1680
+ elif self.mode == "search":
1681
+ box = pygame.Rect(side.x + 12, side.y + 36, side.w - 24, 26)
1682
+ if box.collidepoint(pos):
1683
+ self.focus = "search"
1684
+ return
1685
+ top = side.y + 110
1686
+ if y >= top:
1687
+ idx = (y - top + self.res_scroll) // RES_H
1688
+ if 0 <= idx < len(self.search_results):
1689
+ path, no, _ = self.search_results[idx]
1690
+ if self.open_file(path):
1691
+ d = self.doc()
1692
+ d.row, d.col = no - 1, 0
1693
+ d.anchor = None
1694
+ d.clamp()
1695
+ self.focus = "editor"
1696
+
1697
+ elif self.mode == "git":
1698
+ top = side.y + 82
1699
+ if y >= top and self.git_ok:
1700
+ idx = (y - top) // ROW_H
1701
+ if 0 <= idx < len(self.git_changes):
1702
+ path = self.git_changes[idx][1]
1703
+ if os.path.isfile(path):
1704
+ self.open_file(path)
1705
+
1706
+ elif self.mode == "debug":
1707
+ if pygame.Rect(side.x + 12, side.y + 44, side.w - 24, 30).collidepoint(pos):
1708
+ self.run_active()
1709
+
1710
+ elif self.mode == "extensions":
1711
+ top = side.y + 40
1712
+ if y >= top:
1713
+ idx = (y - top) // EXT_H
1714
+ if 0 <= idx < len(LANGUAGES):
1715
+ L = LANGUAGES[idx]
1716
+ L["enabled"] = not L["enabled"]
1717
+ self.notify(f"{L['name']} highlighting {'on' if L['enabled'] else 'off'}")
1718
+
1719
+ # ------------------------------------------------------------ drawing
1720
+ def draw(self, s):
1721
+ self.pump()
1722
+ self.update_diagnostics()
1723
+ self.update_find()
1724
+ w, h = s.get_size()
1725
+ g = self.geometry(w, h)
1726
+ s.fill(C["editor"])
1727
+ self.draw_titlebar(s, w)
1728
+ self.draw_activity(s, g["activity"])
1729
+ if self.sidebar_open:
1730
+ self.draw_sidebar(s, g["side"])
1731
+ self.draw_editor(s, g["editor"])
1732
+ if self.panel_open:
1733
+ self.draw_panel(s, g["panel"])
1734
+ self.draw_status(s, g["status"])
1735
+ self.draw_menu(s)
1736
+ self.draw_prompt(s)
1737
+
1738
+ def blink(self):
1739
+ return (pygame.time.get_ticks() // 500) % 2 == 0
1740
+
1741
+ def _draw_titlebar_base(self, s, w):
1742
+ pygame.draw.rect(s, C["title"], (0, 0, w, TITLE_H))
1743
+ s.blit(logo(20), (8, (TITLE_H - 20) // 2))
1744
+ self.menu_label_rects = []
1745
+ x = 36
1746
+ for i, (name, _) in enumerate(MENUS):
1747
+ img = UI_SMALL.render(name, True, C["title_text"])
1748
+ rect = pygame.Rect(x - 6, 0, img.get_width() + 12, TITLE_H)
1749
+ if self.open_menu == i:
1750
+ pygame.draw.rect(s, C["menu_hover"], rect)
1751
+ s.blit(img, (x, (TITLE_H - img.get_height()) // 2))
1752
+ self.menu_label_rects.append((rect, name))
1753
+ x += img.get_width() + 14
1754
+ d = self.doc()
1755
+ label = f"{d.name} - {self.root_name} - {APP_NAME}" if d else f"{self.root_name} - {APP_NAME}"
1756
+ box = pygame.Rect(w // 2 - 200, 4, 400, TITLE_H - 8)
1757
+ pygame.draw.rect(s, C["search_bg"], box, border_radius=5)
1758
+ pygame.draw.rect(s, C["search_border"], box, 1, border_radius=5)
1759
+ img = UI_SMALL.render(label, True, C["title_text"])
1760
+ s.blit(img, img.get_rect(center=box.center))
1761
+ cy = TITLE_H // 2
1762
+ for i in range(3):
1763
+ cx = w - 23 - i * 46
1764
+ col = C["title_text"]
1765
+ if i == 0:
1766
+ pygame.draw.line(s, col, (cx - 5, cy), (cx + 5, cy), 1)
1767
+ elif i == 1:
1768
+ pygame.draw.rect(s, col, (cx - 5, cy - 5, 10, 10), 1)
1769
+ else:
1770
+ pygame.draw.line(s, col, (cx - 5, cy - 5), (cx + 5, cy + 5), 1)
1771
+ pygame.draw.line(s, col, (cx + 5, cy - 5), (cx - 5, cy + 5), 1)
1772
+
1773
+ def draw_menu(self, s):
1774
+ self.menu_item_rects = []
1775
+ if self.open_menu is None:
1776
+ return
1777
+ name, items = MENUS[self.open_menu]
1778
+ label_rect = self.menu_label_rects[self.open_menu][0]
1779
+ width = 260
1780
+ row_h, sep_h = 24, 8
1781
+ height = sum(sep_h if it is None else row_h for it in items) + 8
1782
+ box = pygame.Rect(label_rect.x, TITLE_H, width, height)
1783
+ pygame.draw.rect(s, C["menu_bg"], box, border_radius=4)
1784
+ pygame.draw.rect(s, C["search_border"], box, 1, border_radius=4)
1785
+ mouse = pygame.mouse.get_pos()
1786
+ y = box.y + 4
1787
+ for it in items:
1788
+ if it is None:
1789
+ pygame.draw.line(s, C["border"], (box.x + 8, y + sep_h // 2), (box.right - 8, y + sep_h // 2))
1790
+ y += sep_h
1791
+ continue
1792
+ label, shortcut, action = it
1793
+ row = pygame.Rect(box.x + 4, y, box.w - 8, row_h)
1794
+ if row.collidepoint(mouse):
1795
+ pygame.draw.rect(s, C["menu_hover"], row, border_radius=3)
1796
+ s.blit(UI_SMALL.render(label, True, C["text"]), (row.x + 12, row.y + 5))
1797
+ if shortcut:
1798
+ img = UI_SMALL.render(shortcut, True, C["dim"])
1799
+ s.blit(img, (row.right - img.get_width() - 12, row.y + 5))
1800
+ self.menu_item_rects.append((row, action))
1801
+ y += row_h
1802
+
1803
+ def draw_activity(self, s, r):
1804
+ pygame.draw.rect(s, C["activity"], r)
1805
+ for i, (name, mode, _) in enumerate(ACTIVITY):
1806
+ rect = pygame.Rect(0, TITLE_H + 4 + i * 48, ACT_W, 48)
1807
+ active = self.mode == mode and self.sidebar_open
1808
+ color = C["icon_active"] if active else C["icon"]
1809
+ if active:
1810
+ pygame.draw.rect(s, C["accent"], (0, rect.y + 8, 2, 32))
1811
+ img = icon(name, color, 24, C["activity"])
1812
+ s.blit(img, img.get_rect(center=rect.center))
1813
+ for name, cy in (("account", r.bottom - 72), ("gear", r.bottom - 24)):
1814
+ img = icon(name, C["icon"], 24, C["activity"])
1815
+ s.blit(img, img.get_rect(center=(ACT_W // 2, cy)))
1816
+
1817
+ def draw_sidebar(self, s, r):
1818
+ pygame.draw.rect(s, C["sidebar"], r)
1819
+ title = next(t for _, m, t in ACTIVITY if m == self.mode)
1820
+ s.blit(UI_SMALL.render(title, True, C["section"]), (r.x + 20, r.y + 11))
1821
+ {"explorer": self.draw_explorer, "search": self.draw_search, "git": self.draw_git,
1822
+ "debug": self.draw_debug, "extensions": self.draw_extensions}[self.mode](s, r)
1823
+
1824
+ def _draw_explorer_base(self, s, r):
1825
+ root_rect = pygame.Rect(r.x, r.y + 38, r.w, ROW_H)
1826
+ draw_chevron(s, r.x + 12, root_rect.centery, True, C["text"])
1827
+ img = UI_BOLD.render(self.root_name.upper(), True, C["text"])
1828
+ s.blit(img, (r.x + 22, root_rect.centery - img.get_height() // 2))
1829
+ top = r.y + 62
1830
+ clip_prev = s.get_clip()
1831
+ s.set_clip(pygame.Rect(r.x, top, r.w, r.bottom - top))
1832
+ mouse = pygame.mouse.get_pos()
1833
+ cur = self.doc()
1834
+ for idx, (path, depth, isdir) in enumerate(self.tree_rows):
1835
+ y = top + idx * ROW_H - self.expl_scroll
1836
+ if y + ROW_H < top or y > r.bottom:
1837
+ continue
1838
+ row = pygame.Rect(r.x, y, r.w, ROW_H)
1839
+ if cur is not None and cur.path == path:
1840
+ pygame.draw.rect(s, C["sidebar_sel"], row)
1841
+ elif row.collidepoint(mouse):
1842
+ pygame.draw.rect(s, C["sidebar_hover"], row)
1843
+ base = r.x + 8 + depth * 12
1844
+ cy = row.centery
1845
+ name = os.path.basename(path)
1846
+ if isdir:
1847
+ draw_chevron(s, base + 6, cy, path in self.expanded, C["text"])
1848
+ img = UI_SMALL.render(name, True, C["text"])
1849
+ s.blit(img, (base + 16, cy - img.get_height() // 2))
1850
+ else:
1851
+ L = LANG_BY_EXT.get(os.path.splitext(name)[1].lower())
1852
+ if L:
1853
+ txt, col = L["badge"]
1854
+ img = UI_BOLD.render(txt, True, col)
1855
+ s.blit(img, (base + 14, cy - img.get_height() // 2))
1856
+ img = UI_SMALL.render(name, True, C["text"])
1857
+ s.blit(img, (base + 40, cy - img.get_height() // 2))
1858
+ s.set_clip(clip_prev)
1859
+
1860
+ def draw_search(self, s, r):
1861
+ box = pygame.Rect(r.x + 12, r.y + 36, r.w - 24, 26)
1862
+ pygame.draw.rect(s, C["input_bg"], box)
1863
+ pygame.draw.rect(s, C["accent"] if self.focus == "search" else C["input_bg"], box, 1)
1864
+ if self.search_query:
1865
+ img = UI_SMALL.render(self.search_query, True, C["text"])
1866
+ else:
1867
+ img = UI_SMALL.render("Type, then press Enter", True, C["dim"])
1868
+ s.blit(img, (box.x + 6, box.y + (box.h - img.get_height()) // 2))
1869
+ if self.focus == "search" and self.search_query and self.blink():
1870
+ cx = box.x + 6 + UI_SMALL.size(self.search_query)[0]
1871
+ pygame.draw.rect(s, C["caret"], (cx, box.y + 6, 1, box.h - 12))
1872
+ if self.search_busy:
1873
+ status = "Searching..."
1874
+ elif self.search_done:
1875
+ n = len(self.search_results)
1876
+ status = f"{n} result{'s' if n != 1 else ''}" + (" (limit reached)" if n >= 500 else "")
1877
+ else:
1878
+ status = ""
1879
+ s.blit(UI_SMALL.render(status, True, C["dim"]), (r.x + 12, r.y + 72))
1880
+ top = r.y + 110
1881
+ clip_prev = s.get_clip()
1882
+ s.set_clip(pygame.Rect(r.x, top, r.w, r.bottom - top))
1883
+ mouse = pygame.mouse.get_pos()
1884
+ for idx, (path, no, text) in enumerate(self.search_results):
1885
+ y = top + idx * RES_H - self.res_scroll
1886
+ if y + RES_H < top or y > r.bottom:
1887
+ continue
1888
+ row = pygame.Rect(r.x, y, r.w, RES_H)
1889
+ if row.collidepoint(mouse):
1890
+ pygame.draw.rect(s, C["sidebar_hover"], row)
1891
+ rel = os.path.relpath(path, self.root)
1892
+ s.blit(UI_SMALL.render(fit_text(UI_SMALL, f"{rel}:{no}", r.w - 24), True, C["accent"]), (r.x + 12, y + 4))
1893
+ s.blit(UI_SMALL.render(fit_text(UI_SMALL, text, r.w - 24), True, C["text"]), (r.x + 12, y + 20))
1894
+ s.set_clip(clip_prev)
1895
+
1896
+ def draw_git(self, s, r):
1897
+ if not self.git_ok:
1898
+ s.blit(UI_SMALL.render(fit_text(UI_SMALL, self.git_msg or "No git information.", r.w - 24),
1899
+ True, C["dim"]), (r.x + 12, r.y + 40))
1900
+ return
1901
+ s.blit(icon("git", C["text"], 16), (r.x + 12, r.y + 38))
1902
+ s.blit(UI_BOLD.render(self.git_branch or "detached", True, C["text"]), (r.x + 34, r.y + 39))
1903
+ top = r.y + 62
1904
+ if not self.git_changes:
1905
+ s.blit(UI_SMALL.render("No changes. Working tree clean.", True, C["dim"]), (r.x + 12, top))
1906
+ return
1907
+ s.blit(UI_SMALL.render(f"CHANGES ({len(self.git_changes)})", True, C["dim"]), (r.x + 12, top))
1908
+ top += 20
1909
+ clip_prev = s.get_clip()
1910
+ s.set_clip(pygame.Rect(r.x, top, r.w, r.bottom - top))
1911
+ mouse = pygame.mouse.get_pos()
1912
+ for idx, (code, path) in enumerate(self.git_changes):
1913
+ y = top + idx * ROW_H
1914
+ row = pygame.Rect(r.x, y, r.w, ROW_H)
1915
+ if row.collidepoint(mouse):
1916
+ pygame.draw.rect(s, C["sidebar_hover"], row)
1917
+ if code in ("M", "MM", "AM"):
1918
+ col = C["modified"]
1919
+ elif code in ("A", "??", "U"):
1920
+ col = C["added"]
1921
+ elif code == "D":
1922
+ col = C["deleted"]
1923
+ else:
1924
+ col = C["text"]
1925
+ s.blit(UI_BOLD.render(code[:2], True, col), (r.x + 12, y + 4))
1926
+ rel = os.path.relpath(path, self.git_root)
1927
+ s.blit(UI_SMALL.render(fit_text(UI_SMALL, rel, r.w - 50), True, C["text"]), (r.x + 40, y + 4))
1928
+ s.set_clip(clip_prev)
1929
+
1930
+ def draw_debug(self, s, r):
1931
+ btn = pygame.Rect(r.x + 12, r.y + 44, r.w - 24, 30)
1932
+ hot = btn.collidepoint(pygame.mouse.get_pos())
1933
+ pygame.draw.rect(s, (30, 170, 150) if hot else C["btn"], btn, border_radius=4)
1934
+ s.blit(icon("play", C["btn_text"], 14), (btn.x + 12, btn.centery - 7))
1935
+ s.blit(UI_SMALL.render("Run active file (F5)", True, C["btn_text"]), (btn.x + 34, btn.centery - 7))
1936
+ d = self.doc()
1937
+ y = btn.bottom + 16
1938
+ s.blit(UI_SMALL.render(f"Active file: {d.name if d else 'none'}", True, C["text"]), (r.x + 12, y))
1939
+ runnable = ", ".join(L["name"] for L in LANGUAGES if L["run"] and L["enabled"]) or "nothing"
1940
+ s.blit(UI_SMALL.render(f"Runs: {runnable}", True, C["dim"]), (r.x + 12, y + 22))
1941
+ for i, line in enumerate(self.run_status.splitlines() or [""]):
1942
+ s.blit(UI_SMALL.render(fit_text(UI_SMALL, line, r.w - 24), True, C["dim"]), (r.x + 12, y + 50 + i * 18))
1943
+
1944
+ def draw_extensions(self, s, r):
1945
+ top = r.y + 40
1946
+ clip_prev = s.get_clip()
1947
+ s.set_clip(pygame.Rect(r.x, top, r.w, r.bottom - top))
1948
+ mouse = pygame.mouse.get_pos()
1949
+ for idx, L in enumerate(LANGUAGES):
1950
+ y = top + idx * EXT_H
1951
+ row = pygame.Rect(r.x, y, r.w, EXT_H)
1952
+ if row.collidepoint(mouse):
1953
+ pygame.draw.rect(s, C["sidebar_hover"], row)
1954
+ txt, col = L["badge"]
1955
+ on = L["enabled"]
1956
+ s.blit(UI_BOLD.render(txt, True, col if on else C["dim"]), (r.x + 12, y + 6))
1957
+ s.blit(UI_SMALL.render(L["name"], True, C["text"] if on else C["dim"]), (r.x + 44, y + 6))
1958
+ s.blit(UI_SMALL.render(", ".join(L["ext"]), True, C["dim"]), (r.x + 44, y + 22))
1959
+ state = UI_SMALL.render("Enabled" if on else "Disabled", True, C["dim"])
1960
+ s.blit(state, (r.right - state.get_width() - 12, y + 12))
1961
+ s.set_clip(clip_prev)
1962
+
1963
+ def draw_editor(self, s, ed):
1964
+ pygame.draw.rect(s, C["editor"], ed)
1965
+
1966
+ pygame.draw.rect(s, C["tabbar"], (ed.x, ed.y, ed.w, TAB_H))
1967
+ self.tab_rects = []
1968
+ x = ed.x
1969
+ mouse = pygame.mouse.get_pos()
1970
+ for i, d in enumerate(self.docs):
1971
+ if x > ed.right:
1972
+ break
1973
+ tr = pygame.Rect(x, ed.y, UI_FONT.size(d.name)[0] + 66, TAB_H)
1974
+ active = i == self.active
1975
+ pygame.draw.rect(s, C["tab_active"] if active else C["tab_inactive"], tr)
1976
+ if active:
1977
+ pygame.draw.rect(s, C["accent"], (tr.x, tr.y, tr.w, 2))
1978
+ pygame.draw.line(s, C["border"], (tr.right - 1, tr.y), (tr.right - 1, tr.bottom - 1))
1979
+ col = C["tab_text_active"] if active else C["tab_text_inactive"]
1980
+ img = UI_FONT.render(d.name, True, col)
1981
+ s.blit(img, (tr.x + 12, tr.y + (TAB_H - img.get_height()) // 2))
1982
+ close_r = pygame.Rect(tr.right - 24, tr.y + 9, 16, 16)
1983
+ hovered = tr.collidepoint(mouse)
1984
+ if d.dirty and not hovered:
1985
+ pygame.draw.circle(s, col, close_r.center, 4)
1986
+ elif active or hovered:
1987
+ s.blit(icon("close", col, 16), close_r)
1988
+ self.tab_rects.append((i, tr, close_r))
1989
+ x = tr.right
1990
+ pygame.draw.line(s, C["border"], (ed.x, ed.y + TAB_H - 1), (ed.right, ed.y + TAB_H - 1))
1991
+
1992
+ d = self.doc()
1993
+ if d is None:
1994
+ return
1995
+
1996
+ crumb = pygame.Rect(ed.x, ed.y + TAB_H, ed.w, CRUMB_H)
1997
+ pygame.draw.rect(s, C["editor"], crumb)
1998
+ parts = os.path.relpath(d.path, self.root).split(os.sep) if d.path else [d.name]
1999
+ img = UI_SMALL.render(" > ".join(parts), True, C["dim"])
2000
+ s.blit(img, (ed.x + 12, crumb.y + (CRUMB_H - img.get_height()) // 2))
2001
+
2002
+ code = self.code_rect(ed)
2003
+ self.vis_lines = max(1, code.h // LINE_H)
2004
+ gutter = self.gutter_width(d)
2005
+ text_area = pygame.Rect(code.x + gutter, code.y, code.w - gutter, code.h)
2006
+ if d.row < d.scroll:
2007
+ d.scroll = d.row
2008
+ if d.row >= d.scroll + self.vis_lines:
2009
+ d.scroll = d.row - self.vis_lines + 1
2010
+ d.scroll = max(0, min(d.scroll, len(d.lines) - 1))
2011
+ cursor_x = CODE_FONT.size(expand(d.lines[d.row][:d.col]))[0]
2012
+ visible_w = text_area.w - 24
2013
+ if cursor_x - d.hscroll > visible_w:
2014
+ d.hscroll = cursor_x - visible_w
2015
+ if cursor_x - d.hscroll < 0:
2016
+ d.hscroll = max(0, cursor_x)
2017
+ d.hscroll = max(0, d.hscroll)
2018
+
2019
+ tx = code.x + gutter - d.hscroll
2020
+ states = d.line_states()
2021
+ sel = d.sel_range() if d.has_sel() else None
2022
+ last = min(len(d.lines), d.scroll + self.vis_lines + 1)
2023
+ show_caret = self.focus == "editor" and self.blink()
2024
+
2025
+ find_rows = {}
2026
+ if self.find_open:
2027
+ for idx, (r, c, n) in enumerate(self.find_list):
2028
+ find_rows.setdefault(r, []).append((c, n, idx == self.find_idx))
2029
+ problem_rows = {r for r, _ in self.problems}
2030
+
2031
+ s.set_clip(text_area)
2032
+ for i in range(d.scroll, last):
2033
+ y = code.y + (i - d.scroll) * LINE_H
2034
+ line = d.lines[i]
2035
+ if i == d.row and sel is None:
2036
+ pygame.draw.rect(s, C["cur_line"], (code.x + gutter, y, code.w - gutter, LINE_H))
2037
+ for c, n, current in find_rows.get(i, []):
2038
+ x1 = tx + CODE_FONT.size(expand(line[:c]))[0]
2039
+ x2 = tx + CODE_FONT.size(expand(line[:c + n]))[0]
2040
+ pygame.draw.rect(s, C["find_cur"] if current else C["find_match"], (x1, y, x2 - x1, LINE_H))
2041
+ if sel and sel[0][0] <= i <= sel[1][0]:
2042
+ c1 = sel[0][1] if i == sel[0][0] else 0
2043
+ c2 = sel[1][1] if i == sel[1][0] else len(line)
2044
+ x1 = tx + CODE_FONT.size(expand(line[:c1]))[0]
2045
+ x2 = tx + CODE_FONT.size(expand(line[:c2]))[0]
2046
+ if i != sel[1][0]:
2047
+ x2 += CODE_CW // 2
2048
+ pygame.draw.rect(s, C["sel"], (x1, y, max(0, x2 - x1), LINE_H))
2049
+ x = tx
2050
+ tokens, _ = tokenize(expand(line), d.lang, states[i])
2051
+ for text, color in tokens:
2052
+ if text:
2053
+ img = CODE_FONT.render(text, True, color)
2054
+ s.blit(img, (x, y + 1))
2055
+ x += img.get_width()
2056
+ if i in problem_rows: # zigzag under a syntax error
2057
+ width = max(40, CODE_FONT.size(expand(line))[0])
2058
+ pts = [(tx + px, y + LINE_H - 3 - (2 if (px // 3) % 2 else 0)) for px in range(0, width, 3)]
2059
+ if len(pts) > 1:
2060
+ pygame.draw.lines(s, C["error"], False, pts, 1)
2061
+ if i == d.row and show_caret:
2062
+ cx = tx + CODE_FONT.size(expand(line[:d.col]))[0]
2063
+ pygame.draw.rect(s, C["caret"], (cx, y + 2, 2, LINE_H - 4))
2064
+
2065
+ s.set_clip(code)
2066
+ for i in range(d.scroll, last):
2067
+ y = code.y + (i - d.scroll) * LINE_H
2068
+ num_col = C["line_num_active"] if i == d.row else C["line_num"]
2069
+ num = CODE_FONT.render(str(i + 1), True, num_col)
2070
+ s.blit(num, (code.x + gutter - 14 - num.get_width(), y + 1))
2071
+ if i in problem_rows:
2072
+ pygame.draw.circle(s, C["error"], (code.x + 9, y + LINE_H // 2), 3)
2073
+ total = len(d.lines)
2074
+ if total > self.vis_lines:
2075
+ thumb_h = max(30, code.h * self.vis_lines // total)
2076
+ thumb_y = code.y + (code.h - thumb_h) * d.scroll // max(1, total - self.vis_lines)
2077
+ pygame.draw.rect(s, C["scroll"], (code.right - 12, thumb_y, 10, thumb_h), border_radius=4)
2078
+ if self.find_open:
2079
+ self.draw_find_bar(s, code)
2080
+ s.set_clip(None)
2081
+
2082
+ if len(self.docs) == 1 and d.path is None and not d.text():
2083
+ s.blit(logo(64), logo(64).get_rect(center=(code.centerx, code.centery - 80)))
2084
+ hints = [f"{APP_NAME}", "Open a file from the Explorer, or Ctrl+N",
2085
+ "Ctrl+Shift+F search files Ctrl+F find in file"]
2086
+ for j, t in enumerate(hints):
2087
+ img = UI_FONT.render(t, True, C["hint"] if j else C["text"])
2088
+ s.blit(img, img.get_rect(center=(code.centerx, code.centery - 8 + j * 24)))
2089
+
2090
+ def draw_find_bar(self, s, code):
2091
+ bar = pygame.Rect(code.right - 392, code.y + 8, 380, 32)
2092
+ pygame.draw.rect(s, C["menu_bg"], bar, border_radius=4)
2093
+ pygame.draw.rect(s, C["accent"] if self.focus == "find" else C["search_border"], bar, 1, border_radius=4)
2094
+ img = UI_SMALL.render(self.find_query or "Find", True, C["text"] if self.find_query else C["dim"])
2095
+ s.blit(img, (bar.x + 10, bar.y + (bar.h - img.get_height()) // 2))
2096
+ if self.focus == "find" and self.blink():
2097
+ cx = bar.x + 10 + UI_SMALL.size(self.find_query)[0]
2098
+ pygame.draw.rect(s, C["caret"], (cx, bar.y + 7, 1, bar.h - 14))
2099
+ if self.find_query:
2100
+ status = f"{self.find_idx + 1} of {len(self.find_list)}" if self.find_list else "No results"
2101
+ else:
2102
+ status = ""
2103
+ st = UI_SMALL.render(status, True, C["dim"])
2104
+ s.blit(st, (bar.right - st.get_width() - 10, bar.y + (bar.h - st.get_height()) // 2))
2105
+
2106
+ def draw_panel(self, s, r):
2107
+ pygame.draw.rect(s, C["editor"], r)
2108
+ pygame.draw.line(s, C["border"], r.topleft, r.topright)
2109
+ self.panel_tab_rects = []
2110
+ x = r.x + 16
2111
+ n_problems = len(self.problems)
2112
+ for name in ["PROBLEMS", "OUTPUT", "TERMINAL", "PORTS"]:
2113
+ label = f"PROBLEMS {n_problems}" if name == "PROBLEMS" and n_problems else name
2114
+ active = name == self.panel_tab
2115
+ col = C["tab_text_active"] if active else C["tab_text_inactive"]
2116
+ if name == "PROBLEMS" and n_problems and not active:
2117
+ col = C["error"]
2118
+ img = UI_SMALL.render(label, True, col)
2119
+ s.blit(img, (x, r.y + (PANEL_TAB_H - img.get_height()) // 2))
2120
+ rect = pygame.Rect(x - 6, r.y, img.get_width() + 12, PANEL_TAB_H)
2121
+ if active:
2122
+ pygame.draw.rect(s, C["accent"], (x, r.y + PANEL_TAB_H - 2, img.get_width(), 2))
2123
+ self.panel_tab_rects.append((name, rect))
2124
+ x += img.get_width() + 28
2125
+ self.panel_close = pygame.Rect(r.right - 28, r.y + PANEL_TAB_H // 2 - 8, 16, 16)
2126
+ s.blit(icon("close", C["tab_text_inactive"], 16), self.panel_close)
2127
+
2128
+ body = pygame.Rect(r.x, r.y + PANEL_TAB_H, r.w, r.h - PANEL_TAB_H)
2129
+ clip_prev = s.get_clip()
2130
+ s.set_clip(body)
2131
+ fit = max(1, (body.h - 10) // LINE_H)
2132
+ self.problem_rects = []
2133
+
2134
+ if self.panel_tab == "TERMINAL":
2135
+ self.draw_terminal(s, body, fit)
2136
+ elif self.panel_tab == "OUTPUT":
2137
+ y = body.y + 6
2138
+ for text, color in self.output[-fit:]:
2139
+ s.blit(CODE_FONT.render(fit_text(CODE_FONT, text, body.w - 32), True, color), (body.x + 16, y))
2140
+ y += LINE_H
2141
+ elif self.panel_tab == "PROBLEMS":
2142
+ if not self.problems:
2143
+ s.blit(UI_SMALL.render("No problems in the active file.", True, C["dim"]), (body.x + 16, body.y + 10))
2144
+ mouse = pygame.mouse.get_pos()
2145
+ name = self.doc().name if self.doc() else ""
2146
+ for idx, (row, msg) in enumerate(self.problems[:fit]):
2147
+ y = body.y + 6 + idx * LINE_H
2148
+ rect = pygame.Rect(body.x, y, body.w, LINE_H)
2149
+ if rect.collidepoint(mouse):
2150
+ pygame.draw.rect(s, C["sidebar_hover"], rect)
2151
+ txt = f"{name}:{row + 1} {msg}"
2152
+ s.blit(UI_SMALL.render(fit_text(UI_SMALL, txt, body.w - 32), True, C["error"]), (body.x + 16, y + 3))
2153
+ self.problem_rects.append((rect, idx))
2154
+ else:
2155
+ s.blit(UI_SMALL.render("No forwarded ports.", True, C["dim"]), (body.x + 16, body.y + 10))
2156
+ s.set_clip(clip_prev)
2157
+
2158
+ def draw_status(self, s, r):
2159
+ pygame.draw.rect(s, C["status"], r)
2160
+ cy = r.centery
2161
+ x = r.x + 10
2162
+ if self.git_ok and self.git_branch:
2163
+ s.blit(icon("git", C["status_text"], 14), (x, cy - 7))
2164
+ x += 18
2165
+ img = UI_SMALL.render(self.git_branch, True, C["status_text"])
2166
+ s.blit(img, (x, cy - img.get_height() // 2))
2167
+ x += img.get_width() + 14
2168
+ n = len(self.problems)
2169
+ left = f"{n} error{'s' if n != 1 else ''}, 0 warnings"
2170
+ img = UI_SMALL.render(left, True, C["status_text"])
2171
+ s.blit(img, (x, cy - img.get_height() // 2))
2172
+
2173
+ d = self.doc()
2174
+ items = []
2175
+ if d is not None:
2176
+ info = f"Ln {d.row + 1}, Col {d.col + 1}"
2177
+ if d.has_sel():
2178
+ info += f" ({len(d.selected_text())} selected)"
2179
+ items = [info, "Spaces: 4", "UTF-8", "LF", d.lang["name"]]
2180
+ bx = r.right - 24
2181
+ s.blit(icon("bell", C["status_text"], 14), (bx, cy - 7))
2182
+ x = bx - 14
2183
+ for text in reversed(items):
2184
+ img = UI_SMALL.render(text, True, C["status_text"])
2185
+ x -= img.get_width()
2186
+ s.blit(img, (x, cy - img.get_height() // 2))
2187
+ x -= 16
2188
+
2189
+ def on_click(self, pos, g):
2190
+ if self.open_menu is None:
2191
+ if self.run_rect.collidepoint(pos):
2192
+ self.do("run")
2193
+ return
2194
+ if self.sidebar_open and self.mode == "explorer" and self.newfile_rect.collidepoint(pos):
2195
+ self.do("newfile")
2196
+ return
2197
+ self._on_click_base(pos, g)
2198
+
2199
+ def draw_titlebar(self, s, w):
2200
+ self._draw_titlebar_base(s, w)
2201
+ self.run_rect = pygame.Rect(w - 250, 4, 64, TITLE_H - 8)
2202
+ pygame.draw.rect(s, C["btn"], self.run_rect, border_radius=4)
2203
+ s.blit(icon("play", C["btn_text"], 14), (self.run_rect.x + 8, self.run_rect.centery - 7))
2204
+ s.blit(UI_SMALL.render("Run", True, C["btn_text"]), (self.run_rect.x + 26, self.run_rect.centery - 7))
2205
+
2206
+ def draw_explorer(self, s, r):
2207
+ self._draw_explorer_base(s, r)
2208
+ self.newfile_rect = pygame.Rect(r.right - 30, r.y + 4, 22, 22)
2209
+ if self.newfile_rect.collidepoint(pygame.mouse.get_pos()):
2210
+ pygame.draw.rect(s, C["sidebar_hover"], self.newfile_rect, border_radius=3)
2211
+ plus = UI_BOLD.render("+", True, C["text"])
2212
+ s.blit(plus, plus.get_rect(center=self.newfile_rect.center))
2213
+ if not self.tree_rows:
2214
+ hints = ["Empty project.", "Click + to create a file,", "or Ctrl+O to open one."]
2215
+ for i, line in enumerate(hints):
2216
+ s.blit(UI_SMALL.render(line, True, C["dim"]), (r.x + 16, r.y + 70 + i * 18))
2217
+
2218
+ def feed_terminal(self, data):
2219
+ # apply shell output to the terminal's current line, like a simple terminal
2220
+ for m in TERM_TOKEN.finditer(data):
2221
+ tok = m.group()
2222
+ if m.group(3):
2223
+ params, final = m.group(1), m.group(3)
2224
+ n = int(params) if params.isdigit() else 1
2225
+ if final == "C":
2226
+ self.tcol += n
2227
+ elif final == "D":
2228
+ self.tcol = max(0, self.tcol - n)
2229
+ elif final == "G":
2230
+ self.tcol = max(0, n - 1)
2231
+ elif final == "K":
2232
+ self.term_partial = self.term_partial[:self.tcol]
2233
+ elif tok == "\n":
2234
+ self.term.append((self.term_partial, C["plain"]))
2235
+ self.term_partial, self.tcol = "", 0
2236
+ elif tok == "\r":
2237
+ self.tcol = 0
2238
+ elif tok in ("\b", "\x7f"):
2239
+ self.tcol = max(0, self.tcol - 1)
2240
+ elif tok.startswith("\x1b") or tok == "\x07":
2241
+ continue
2242
+ elif tok == "\t" or tok.isprintable():
2243
+ p = self.term_partial
2244
+ if self.tcol < len(p):
2245
+ self.term_partial = p[:self.tcol] + tok + p[self.tcol + 1:]
2246
+ else:
2247
+ self.term_partial = p + " " * (self.tcol - len(p)) + tok
2248
+ self.tcol += 1
2249
+ self.term = self.term[-2000:]
2250
+
2251
+ def draw_terminal(self, s, body, fit):
2252
+ rows = fit - 1
2253
+ y = body.y + 6
2254
+ if rows > 0:
2255
+ for text, color in self.term[-rows:]:
2256
+ s.blit(CODE_FONT.render(fit_text(CODE_FONT, text, body.w - 32), True, color), (body.x + 16, y))
2257
+ y += LINE_H
2258
+ s.blit(CODE_FONT.render(self.term_partial, True, C["plain"]), (body.x + 16, y))
2259
+ if self.focus == "terminal" and self.blink():
2260
+ cx = body.x + 16 + CODE_FONT.size(self.term_partial[:self.tcol])[0]
2261
+ pygame.draw.rect(s, C["caret"], (cx, y + 2, 8, LINE_H - 4))
2262
+
2263
+ def draw_prompt(self, s):
2264
+ if self.prompt is None:
2265
+ return
2266
+ w, h = s.get_size()
2267
+ box = pygame.Rect(w // 2 - 220, h // 2 - 50, 440, 100)
2268
+ pygame.draw.rect(s, C["menu_bg"], box, border_radius=6)
2269
+ pygame.draw.rect(s, C["accent"], box, 1, border_radius=6)
2270
+ s.blit(UI_SMALL.render(self.prompt["label"], True, C["dim"]), (box.x + 16, box.y + 12))
2271
+ field = pygame.Rect(box.x + 16, box.y + 38, box.w - 32, 28)
2272
+ pygame.draw.rect(s, C["input_bg"], field, border_radius=3)
2273
+ text = self.prompt["text"]
2274
+ s.blit(UI_FONT.render(text, True, C["text"]), (field.x + 8, field.y + 5))
2275
+ if self.blink():
2276
+ cx = field.x + 8 + UI_FONT.size(text)[0]
2277
+ pygame.draw.rect(s, C["caret"], (cx, field.y + 5, 2, 18))
2278
+ s.blit(UI_SMALL.render("Enter to confirm Esc to cancel", True, C["dim"]), (box.x + 16, box.y + 72))
2279
+
2280
+ def prompt_key(self, e):
2281
+ if e.key == pygame.K_ESCAPE:
2282
+ self.prompt = None
2283
+ elif e.key in (pygame.K_RETURN, pygame.K_KP_ENTER):
2284
+ self.prompt_submit()
2285
+ elif e.key == pygame.K_BACKSPACE:
2286
+ self.prompt["text"] = self.prompt["text"][:-1]
2287
+
2288
+ def prompt_submit(self):
2289
+ p, self.prompt = self.prompt, None
2290
+ text = p["text"].strip()
2291
+ if not text:
2292
+ return
2293
+ if p["action"] == "newfile":
2294
+ self.create_file(text)
2295
+ elif p["action"] == "newproject":
2296
+ self.set_project(os.path.join(PROJECTS_DIR, text))
2297
+ elif p["action"] == "openpath":
2298
+ path = os.path.expanduser(text)
2299
+ if os.path.isfile(path):
2300
+ self.open_file(path)
2301
+ else:
2302
+ self.notify(f"No such file: {path}", C["error"])
2303
+
2304
+ def create_file(self, name):
2305
+ full = os.path.join(self.root, name)
2306
+ if not os.path.exists(full):
2307
+ os.makedirs(os.path.dirname(full), exist_ok=True)
2308
+ open(full, "w", encoding="utf-8").close()
2309
+ self.tree_rows = list_tree(self.root, self.expanded)
2310
+ self.open_file(full)
2311
+
2312
+ def set_project(self, folder):
2313
+ os.makedirs(folder, exist_ok=True)
2314
+ self.root = folder
2315
+ self.root_name = os.path.basename(folder)
2316
+ self.expanded = {folder}
2317
+ self.tree_rows = list_tree(folder, self.expanded)
2318
+ self.expl_scroll = 0
2319
+ self.docs = []
2320
+ self.active = -1
2321
+ self.new_doc()
2322
+ self.svc.set_root(folder)
2323
+ self.svc.git_refresh()
2324
+ self.notify(f"Project: {folder}")
2325
+
2326
+
2327
+ # ======================================================================
2328
+ # Entry point
2329
+ # ======================================================================
2330
+ def main():
2331
+ arg = sys.argv[1] if len(sys.argv) > 1 else default_project()
2332
+ open_path = None
2333
+ if os.path.isfile(arg):
2334
+ open_path = os.path.abspath(arg)
2335
+ root = os.path.dirname(open_path)
2336
+ else:
2337
+ root = arg
2338
+
2339
+ screen = pygame.display.set_mode((WIN_W, WIN_H), pygame.RESIZABLE)
2340
+ pygame.display.set_caption(APP_NAME)
2341
+ pygame.display.set_icon(logo(32))
2342
+ try:
2343
+ pygame.scrap.init()
2344
+ except Exception:
2345
+ pass
2346
+ pygame.key.start_text_input()
2347
+ clock = pygame.time.Clock()
2348
+
2349
+ app = FlexCode(root)
2350
+ if open_path:
2351
+ app.open_file(open_path)
2352
+
2353
+ running = True
2354
+ while running and not app.quit:
2355
+ for e in pygame.event.get():
2356
+ if e.type == pygame.QUIT:
2357
+ running = False
2358
+ else:
2359
+ app.handle_event(e, *screen.get_size())
2360
+ app.draw(screen)
2361
+ pygame.display.flip()
2362
+ clock.tick(60)
2363
+ app.svc.kill()
2364
+ pygame.quit()
2365
+
2366
+
2367
+ if __name__ == "__main__":
2368
+ main()