"""Code view: tabbed multi-file editor with gutter + folding. Mirrors the C code view (src/codeview.cpp) and the Rust one (crates/lightgui-support/src/codeview.rs): line numbers and fold markers in a gutter, a dark Monokai-like theme, syntax highlighting, Ctrl+S save with dirty tracking. The Code window shows the generated code; hand edits are kept until the next Generate overwrites them (C behaviour: a dirty tab is never reloaded over). The gutter NEVER disappears on click (the C 2b0acc2 fix, built in from the start): the gutter DrawingArea is a direct child of the CodeView's horizontal box, BESIDE the ScrolledWindow that holds the TextView — never inside the horizontal scroller. Horizontal scrolling moves only the text; the gutter stays pinned at the left edge. The gutter draws line numbers from the TextView's own line positions (get_iter_location, shifted by the vertical adjustment), so numbers always line up with the text. No GtkSourceView is installed on the server, so highlighting is our own (Gtk.TextView + tags), driven by the pure function tokenize_python() — unit-testable without GTK. Folding is Python blocks: a line ending in ':' folds the more-indented lines below it. """ import re import gi gi.require_version("Gtk", "3.0") gi.require_version("Gdk", "3.0") gi.require_version("PangoCairo", "1.0") from gi.repository import Gdk, GLib, Gtk, Pango, PangoCairo # noqa: E402 # Built-in themes, copied from the C CodeTheme::builtin() values # (src/theme.cpp). Monokai is the default, matching the C code view. THEMES = { "Light": { "background": "#ffffff", "foreground": "#1a1a1a", "keyword": "#0000ff", "type": "#008080", "string": "#a31515", "comment": "#008000", "number": "#098658", "preprocessor": "#af00db", "current_line": "#e8f2ff", }, "Dark": { "background": "#1e1e1e", "foreground": "#d4d4d4", "keyword": "#569cd6", "type": "#4ec9b0", "string": "#ce9178", "comment": "#6a9955", "number": "#b5cea8", "preprocessor": "#c586c0", "current_line": "#2a2d2e", }, "Monokai": { "background": "#272822", "foreground": "#f8f8f2", "keyword": "#f92672", "type": "#66d9ef", "string": "#e6db74", "comment": "#75715e", "number": "#ae81ff", "preprocessor": "#fd971f", "current_line": "#3e3d32", }, "Solarized Dark": { "background": "#002b36", "foreground": "#839496", "keyword": "#859900", "type": "#2aa198", "string": "#b58900", "comment": "#586e75", "number": "#d33682", "preprocessor": "#cb4b16", "current_line": "#073642", }, "Dracula": { "background": "#282a36", "foreground": "#f8f8f2", "keyword": "#ff79c6", "type": "#8be9fd", "string": "#f1fa8c", "comment": "#6272a4", "number": "#bd93f9", "preprocessor": "#ffb86c", "current_line": "#44475a", }, } DEFAULT_THEME = "Monokai" PYTHON_KEYWORDS = frozenset(( "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield", )) PYTHON_BUILTINS = frozenset(( "True", "False", "None", "self", "cls", )) # Tag kind -> theme role. _TAG_ROLES = { "keyword": "keyword", "string": "string", "comment": "comment", "number": "number", "builtin": "type", "decorator": "preprocessor", } _IDENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") _NUMBER_RE = re.compile( r"(?:0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|" r"\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d[\d_]*)?)") def _hex_rgb(text): """#rrggbb -> (r, g, b) floats, or None.""" text = (text or "").strip() if len(text) == 7 and text.startswith("#"): try: return tuple(int(text[i:i + 2], 16) / 255.0 for i in (1, 3, 5)) except ValueError: return None return None # --- pure helpers (no GTK) -------------------------------------------------- def tokenize_python(text): """Highlight spans for Python *text*: [(start, end, kind)] with kind in keyword/string/comment/number/builtin/decorator. Non-overlapping, in order. Pure function of the text. """ spans = [] i = 0 n = len(text) while i < n: ch = text[i] if ch == "#": end = text.find("\n", i) end = n if end < 0 else end spans.append((i, end, "comment")) i = end continue if ch == "@" and (i == 0 or text[i - 1] in "\n\r"): match = _IDENT_RE.match(text, i + 1) if match: spans.append((i, match.end(), "decorator")) i = match.end() continue i += 1 continue # String literal, with optional r/b/f/u prefix. j = i while j < n and text[j] in "rRbBfFuU": j += 1 if j < n and text[j] in "\"'" and j > i: quote = text[j] triple = text[j:j + 3] in ("\"\"\"", "'''") end = _scan_string(text, j, quote, triple) spans.append((i, end, "string")) i = end continue if ch in "\"'": triple = text[i:i + 3] in ("\"\"\"", "'''") end = _scan_string(text, i, ch, triple) spans.append((i, end, "string")) i = end continue if ch.isdigit(): match = _NUMBER_RE.match(text, i) if match: spans.append((match.start(), match.end(), "number")) i = match.end() continue match = _IDENT_RE.match(text, i) if match: word = match.group(0) if word in PYTHON_KEYWORDS: spans.append((match.start(), match.end(), "keyword")) elif word in PYTHON_BUILTINS: spans.append((match.start(), match.end(), "builtin")) i = match.end() continue i += 1 return spans def _scan_string(text, start, quote, triple): """End offset (exclusive) of the string starting at *start*.""" n = len(text) if triple: close = quote * 3 i = start + 3 while i < n: if text[i] == "\\": i += 2 continue if text.startswith(close, i): return i + 3 i += 1 return n i = start + 1 while i < n: ch = text[i] if ch == "\\": i += 2 continue if ch == quote: return i + 1 if ch == "\n": return i i += 1 return n def compute_fold_regions(lines): """Foldable Python blocks: [(start, end)] 0-based, inclusive. A line ending in ':' (ignoring a trailing comment) folds the more-indented lines below it; blank lines inside a block belong to it, trailing blanks do not extend it. """ regions = [] count = len(lines) for i, line in enumerate(lines): stripped = line.strip() if not stripped or stripped.startswith("#"): continue code = line.split("#", 1)[0].rstrip() if not code.endswith(":"): continue indent = len(line) - len(line.lstrip()) last = i j = i + 1 while j < count: other = lines[j] if not other.strip(): j += 1 continue other_indent = len(other) - len(other.lstrip()) if other_indent > indent: last = j j += 1 else: break if last > i: regions.append((i, last)) return regions def hidden_lines(regions, folded_starts): """Line indices hidden by the folded regions in *folded_starts*.""" hidden = set() for start, end in regions: if start in folded_starts: hidden.update(range(start + 1, end + 1)) return hidden # --- one editor tab --------------------------------------------------------- class CodeView(Gtk.Box): """One code editor: gutter (line numbers + fold markers) beside a ScrolledWindow holding the TextView. The gutter is a direct child of this box — outside the scroller — so it can never scroll away. """ # Width of the fold-marker column, px. FOLD_COLUMN = 16 def __init__(self, theme=DEFAULT_THEME): super().__init__(orientation=Gtk.Orientation.HORIZONTAL, spacing=0) self.theme_name = theme if theme in THEMES else DEFAULT_THEME self.file_path = None self.tab_title = "Code" self._dirty = False self._syncing = False self._regions = [] self.folded = set() # 0-based region start lines self.on_dirty_change = None # called with the view on change self.on_save_request = None # called when Ctrl+S has no path self.buffer = Gtk.TextBuffer() self._make_tags() self.view = Gtk.TextView(buffer=self.buffer) self.view.set_monospace(True) self.view.set_editable(True) self.view.set_cursor_visible(True) self.view.set_wrap_mode(Gtk.WrapMode.NONE) self.view.set_left_margin(6) self.view.connect("key-press-event", self._on_key_press) # The gutter: a DrawingArea OUTSIDE the scrolled window. self.gutter = Gtk.DrawingArea() self.gutter.set_size_request(48, -1) self.gutter.add_events(Gdk.EventMask.BUTTON_PRESS_MASK) self.gutter.connect("draw", self._on_gutter_draw) self.gutter.connect("button-press-event", self._on_gutter_press) self.scrolled = Gtk.ScrolledWindow() self.scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.scrolled.add(self.view) self.scrolled.get_vadjustment().connect( "value-changed", lambda _adj: self.gutter.queue_draw()) # Pack order matters: gutter first, scroller second. The # gutter is NOT inside the scroller (2b0acc2 fix). self.pack_start(self.gutter, False, False, 0) self.pack_start(self.scrolled, True, True, 0) self.buffer.connect("changed", self._on_buffer_changed) self._apply_theme() self._update_gutter_width() # --- theme -------------------------------------------------------------- def _make_tags(self): theme = THEMES[self.theme_name] for kind, role in _TAG_ROLES.items(): self.buffer.create_tag("theme-" + kind, foreground=theme[role]) self.buffer.create_tag("fold-hidden", invisible=True) def _apply_theme(self): theme = THEMES[self.theme_name] for kind, role in _TAG_ROLES.items(): tag = self.buffer.get_tag_table().lookup("theme-" + kind) if tag is not None: tag.set_property("foreground", theme[role]) css = ("textview, textview text { background-color: %s; " "color: %s; }" % (theme["background"], theme["foreground"])) provider = Gtk.CssProvider() provider.load_from_data(css.encode("utf-8")) context = self.view.get_style_context() context.add_provider(provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) self._css_provider = provider self.gutter.queue_draw() def set_theme(self, name): if name not in THEMES: return False self.theme_name = name self._apply_theme() self.apply_highlighting() return True def theme(self): return THEMES[self.theme_name] # --- text / dirty --------------------------------------------------------- @property def is_dirty(self): return self._dirty def set_text(self, text, path=None): """Replace the buffer (e.g. with freshly generated code). Clears dirty + folds; does not mark dirty.""" self._syncing = True try: self.buffer.set_text(text or "") finally: self._syncing = False self.file_path = path self._dirty = False self.folded.clear() self.refresh_now() self._notify_dirty() def get_text(self): start, end = self.buffer.get_bounds() return self.buffer.get_text(start, end, True) def save(self): """Write the buffer to file_path. False when there is no path (the caller then asks for one); True on success.""" if not self.file_path: return False try: with open(self.file_path, "w", encoding="utf-8") as handle: handle.write(self.get_text()) except OSError: return False self._dirty = False self._notify_dirty() return True def save_as(self, path): self.file_path = path return self.save() def _notify_dirty(self): if self.on_dirty_change is not None: self.on_dirty_change(self) def _on_buffer_changed(self, _buffer): if self._syncing: return self._dirty = True self._notify_dirty() # Re-highlight / refold on idle so typing stays responsive. if getattr(self, "_refresh_idle", None) is None: self._refresh_idle = GLib.idle_add(self._on_refresh_idle) def _on_refresh_idle(self): self._refresh_idle = None self.refresh_now() return False def refresh_now(self): """Recompute folds + highlighting + gutter width now.""" lines = self.get_text().split("\n") self._regions = compute_fold_regions(lines) self.folded = {s for s in self.folded if any(s == start for start, _e in self._regions)} self.apply_folds() self.apply_highlighting() self._update_gutter_width() self.gutter.queue_draw() # --- folding -------------------------------------------------------------- def region_starts_at(self, line0): return any(start == line0 for start, _end in self._regions) def is_folded(self, line0): return line0 in self.folded def toggle_fold(self, line0): """Fold/unfold the region starting at *line0*. True when a region starts there.""" if not self.region_starts_at(line0): return False if line0 in self.folded: self.folded.discard(line0) else: self.folded.add(line0) self.apply_folds() self.gutter.queue_draw() return True def apply_folds(self): tag = self.buffer.get_tag_table().lookup("fold-hidden") if tag is None: return start, end = self.buffer.get_bounds() self.buffer.remove_tag(tag, start, end) for line in sorted(hidden_lines(self._regions, self.folded)): line_start = self.buffer.get_iter_at_line(line) line_end = self.buffer.get_iter_at_line(line) line_end.forward_to_line_end() self.buffer.apply_tag(tag, line_start, line_end) # --- highlighting ----------------------------------------------------------- def apply_highlighting(self): text = self.get_text() start, end = self.buffer.get_bounds() for kind in _TAG_ROLES: tag = self.buffer.get_tag_table().lookup("theme-" + kind) if tag is not None: self.buffer.remove_tag(tag, start, end) for span_start, span_end, kind in tokenize_python(text): tag = self.buffer.get_tag_table().lookup("theme-" + kind) if tag is None: continue it_start = self.buffer.get_iter_at_offset(span_start) it_end = self.buffer.get_iter_at_offset(span_end) self.buffer.apply_tag(tag, it_start, it_end) # --- gutter ------------------------------------------------------------------- def _update_gutter_width(self): digits = len(str(max(1, self.buffer.get_line_count()))) layout = self.gutter.create_pango_layout("9" * digits) width, _height = layout.get_pixel_size() self.gutter.set_size_request(width + self.FOLD_COLUMN + 10, -1) def line_at_y(self, y): """Buffer line (0-based) at gutter widget y *y*, or -1.""" vadj = self.scrolled.get_vadjustment().get_value() buf_y = y + vadj count = self.buffer.get_line_count() for line in range(count): rect = self.view.get_iter_location( self.buffer.get_iter_at_line(line)) if rect.y <= buf_y < rect.y + rect.height: return line return -1 def _on_gutter_press(self, _gutter, event): if event.button != 1: return False line = self.line_at_y(event.y) if line < 0: return False return self.toggle_fold(line) def _on_gutter_draw(self, gutter, cr): theme = THEMES[self.theme_name] alloc = gutter.get_allocation() bg = _hex_rgb(theme["background"]) or (0.15, 0.15, 0.13) fg = _hex_rgb(theme["comment"]) or (0.46, 0.44, 0.37) num_rgb = _hex_rgb(theme["foreground"]) or (0.97, 0.97, 0.95) cr.set_source_rgb(*bg) cr.rectangle(0, 0, alloc.width, alloc.height) cr.fill() vadj = self.scrolled.get_vadjustment().get_value() count = self.buffer.get_line_count() font = Pango.FontDescription.from_string("Monospace 10") for line in range(count): rect = self.view.get_iter_location( self.buffer.get_iter_at_line(line)) y = rect.y - vadj if y + rect.height < 0: continue if y > alloc.height: break # Fold marker in the left column. if self.region_starts_at(line): marker = "+" if line in self.folded else "-" layout = gutter.create_pango_layout(marker) layout.set_font_description(font) mw, mh = layout.get_pixel_size() cr.set_source_rgb(*fg) cr.move_to((self.FOLD_COLUMN - mw) / 2, y + (rect.height - mh) / 2) PangoCairo.show_layout(cr, layout) # Line number, right-aligned before the divider. text = str(line + 1) layout = gutter.create_pango_layout(text) layout.set_font_description(font) tw, th = layout.get_pixel_size() cr.set_source_rgb(*num_rgb) cr.move_to(alloc.width - 4 - tw, y + (rect.height - th) / 2) PangoCairo.show_layout(cr, layout) # Divider between gutter and code. cr.set_source_rgb(*fg) cr.set_line_width(1.0) cr.move_to(alloc.width - 0.5, 0) cr.line_to(alloc.width - 0.5, alloc.height) cr.stroke() return False # --- keys ----------------------------------------------------------------------- def _on_key_press(self, _view, event): if (event.state & Gdk.ModifierType.CONTROL_MASK and Gdk.keyval_name(event.keyval) in ("s", "S")): if self.save(): return True if self.on_save_request is not None: self.on_save_request(self) return True return True return False # --- the Code window ------------------------------------------------------------ class CodeWindow: """The separate top-level Code window (C open_code_view): the menu bar lives here, above a tabbed notebook of CodeViews. Closing the window hides it; Ctrl+E (or View -> Code View) brings it back. """ def __init__(self, on_status=None): self.on_status = on_status self.window = Gtk.Window(title="LightGUI \u2014 Code") self.window.set_default_size(1000, 700) self.window.connect("delete-event", self._on_delete) self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0) self.window.add(self.vbox) self._menubar = None self.notebook = Gtk.Notebook() self.notebook.set_scrollable(True) self.notebook.connect("switch-page", self._on_switch_page) self.vbox.pack_start(self.notebook, True, True, 0) self.generated_view = None self._active = None # --- window --------------------------------------------------------------- def _on_delete(self, _window, _event): self.hide() return True def show(self): self.window.show_all() self.window.present() def hide(self): self.window.hide() def toggle(self): if self.window.get_visible(): self.hide() else: self.show() def is_visible(self): return self.window.get_visible() def set_menubar(self, menubar): """Pack the app menu bar at the top (C: the menu bar lives in the Code window, not the main designer window).""" if self._menubar is not None: self.vbox.remove(self._menubar) self._menubar = menubar if menubar is not None: self.vbox.pack_start(menubar, False, False, 0) self.vbox.reorder_child(menubar, 0) menubar.show_all() def set_theme(self, name): for view in self.views(): view.set_theme(name) def _status(self, text): if self.on_status is not None: self.on_status(text) # --- tabs ------------------------------------------------------------------- def views(self): pages = [] for i in range(self.notebook.get_n_pages()): pages.append(self.notebook.get_nth_page(i)) return pages def current_view(self): page = self.notebook.get_current_page() if page < 0: return None return self.notebook.get_nth_page(page) def _on_switch_page(self, _notebook, page, _num): self._active = page def _tab_label_box(self, view, title): hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=4) label = Gtk.Label(label=title) hbox.pack_start(label, False, False, 0) close = Gtk.Button(label="\u00d7") close.set_relief(Gtk.ReliefStyle.NONE) close.set_tooltip_text("Close tab") close.connect("clicked", lambda _b, v=view: self.close_tab(v)) hbox.pack_start(close, False, False, 0) hbox.show_all() return hbox def _set_tab_label(self, view, title): # Not a page yet (new_tab sets the text before appending): # get_tab_label() would hit a GTK assertion, so check first. if self.notebook.page_num(view) < 0: return tab = self.notebook.get_tab_label(view) if tab is None: return for child in tab.get_children(): if isinstance(child, Gtk.Label): child.set_text(title) def _refresh_tab_label(self, view): title = view.tab_title if view.is_dirty: title = "*" + title self._set_tab_label(view, title) def _on_view_dirty(self, view): self._refresh_tab_label(view) def new_tab(self, title="Code", text="", path=None): view = CodeView() view.tab_title = title view.on_dirty_change = self._on_view_dirty view.on_save_request = self._on_view_save_request view.set_text(text, path) self.notebook.append_page(view, self._tab_label_box(view, title)) view.show_all() self.notebook.set_current_page(self.notebook.get_n_pages() - 1) return view def _on_view_save_request(self, view): # No path yet: ask for one (Save As) via a file dialog. dialog = Gtk.FileChooserDialog( title="Save Code As", parent=self.window, action=Gtk.FileChooserAction.SAVE, buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_SAVE, Gtk.ResponseType.ACCEPT)) dialog.set_do_overwrite_confirmation(True) if view.file_path: dialog.set_filename(view.file_path) else: dialog.set_current_name(view.tab_title) response = dialog.run() path = None if response == Gtk.ResponseType.ACCEPT: path = dialog.get_filename() dialog.destroy() if path: view.save_as(path) view.tab_title = path.rsplit("/", 1)[-1] self._refresh_tab_label(view) self._status("Code saved — %s" % path) def open_file(self, path): """Open *path* in a tab (switch to it when already open). Returns the view, or None when the file cannot be read. Never reloads a dirty tab.""" if not path: return None for view in self.views(): if view.file_path == path: page = self.notebook.page_num(view) self.notebook.set_current_page(page) return view try: with open(path, encoding="utf-8") as handle: text = handle.read() except OSError: return None title = path.rsplit("/", 1)[-1] return self.new_tab(title, text, path) def show_generated(self, text, path=None, title=None): """Show generated code in the generated tab. When that tab has unsaved hand edits, they are kept (C refresh_code_view) and this returns False; otherwise the tab is refreshed and this returns True.""" if title is None: title = path.rsplit("/", 1)[-1] if path else "Code" if self.generated_view is not None: if self.generated_view.is_dirty: self._status("Code view — %s (unsaved changes kept)" % (self.generated_view.file_path or "Code")) return False self.generated_view.set_text(text, path) self.generated_view.tab_title = title self._refresh_tab_label(self.generated_view) page = self.notebook.page_num(self.generated_view) if page >= 0: self.notebook.set_current_page(page) return True view = self.new_tab(title, text, path) self.generated_view = view return True def close_tab(self, view): if view.is_dirty: dialog = Gtk.MessageDialog( parent=self.window, flags=Gtk.DialogFlags.MODAL, type=Gtk.MessageType.QUESTION, buttons=Gtk.ButtonsType.YES_NO, message_format="Close %s without saving? Unsaved " "changes will be lost." % view.tab_title) response = dialog.run() dialog.destroy() if response != Gtk.ResponseType.YES: return False pages = self.notebook.get_n_pages() if pages <= 1: # Keep at least one tab: clear it to an empty view. view.set_text("", None) view.tab_title = "Code" self._refresh_tab_label(view) self.generated_view = view return True if view is self.generated_view: self.generated_view = None self.notebook.remove_page(self.notebook.page_num(view)) return True