codis 1.1.1__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.
- codis-1.1.1.dist-info/METADATA +194 -0
- codis-1.1.1.dist-info/RECORD +329 -0
- codis-1.1.1.dist-info/WHEEL +5 -0
- codis-1.1.1.dist-info/entry_points.txt +5 -0
- codis-1.1.1.dist-info/licenses/LICENSE +21 -0
- codis-1.1.1.dist-info/top_level.txt +2 -0
- run.py +190 -0
- src/__init__.py +1 -0
- src/__main__.py +81 -0
- src/_app_build.py +1507 -0
- src/_app_editor.py +1274 -0
- src/_app_kui.py +825 -0
- src/_app_lsp.py +625 -0
- src/_app_recovery.py +189 -0
- src/_app_settings.py +1385 -0
- src/_app_tools.py +2471 -0
- src/_app_webpreview.py +126 -0
- src/_font_safety.py +127 -0
- src/_shells.py +172 -0
- src/app.py +1488 -0
- src/chat/__init__.py +1 -0
- src/chat/adapters/__init__.py +33 -0
- src/chat/adapters/base.py +209 -0
- src/chat/adapters/discord.py +190 -0
- src/chat/adapters/http.py +78 -0
- src/chat/adapters/irc.py +360 -0
- src/chat/adapters/matrix.py +219 -0
- src/chat/adapters/mattermost.py +178 -0
- src/chat/adapters/mqtt.py +165 -0
- src/chat/adapters/slack.py +204 -0
- src/chat/adapters/telegram.py +117 -0
- src/chat/adapters/ws.py +154 -0
- src/chat/adapters/xmpp.py +337 -0
- src/chat/history.py +76 -0
- src/chat/models.py +207 -0
- src/chat/probe.py +79 -0
- src/chat/session.py +446 -0
- src/chat/util.py +125 -0
- src/collab/__init__.py +1 -0
- src/collab/net.py +411 -0
- src/collab/ot.py +311 -0
- src/collab/session.py +141 -0
- src/collab/tk_adapter.py +134 -0
- src/config.py +335 -0
- src/constants.py +2552 -0
- src/dep_catalog.py +446 -0
- src/diff/__init__.py +1 -0
- src/diff/engine.py +247 -0
- src/dpi.py +30 -0
- src/editor/__init__.py +1 -0
- src/editor/_pane_lsp.py +2937 -0
- src/editor/_pane_utils.py +171 -0
- src/editor/autocomplete.py +607 -0
- src/editor/code_folding.py +836 -0
- src/editor/color_preview.py +382 -0
- src/editor/complexity_lens.py +281 -0
- src/editor/diff_pane.py +623 -0
- src/editor/file_watcher.py +144 -0
- src/editor/focus_block.py +236 -0
- src/editor/heatmap.py +141 -0
- src/editor/inlay_hints.py +366 -0
- src/editor/inline_blame.py +429 -0
- src/editor/kdocs.py +3376 -0
- src/editor/large_file.py +488 -0
- src/editor/ligatures.py +180 -0
- src/editor/line_numbers.py +598 -0
- src/editor/minimap.py +691 -0
- src/editor/multi_cursor.py +269 -0
- src/editor/pane.py +2082 -0
- src/editor/rhythm.py +206 -0
- src/editor/save_hooks.py +43 -0
- src/editor/smart_selection.py +425 -0
- src/editor/smart_tips.py +719 -0
- src/editor/snippets.py +411 -0
- src/editor/sticky_note_gutter.py +410 -0
- src/editor/sticky_scroll.py +385 -0
- src/editor/suggest.py +464 -0
- src/editor/text_transforms.py +310 -0
- src/editor/vim_mode.py +1074 -0
- src/events/__init__.py +84 -0
- src/events/bus.py +427 -0
- src/events/correlator.py +244 -0
- src/events/kinds.py +125 -0
- src/events/pipeline.py +264 -0
- src/events/stream.py +416 -0
- src/events/window.py +204 -0
- src/extcompat/__init__.py +19 -0
- src/extcompat/code/__init__.py +13 -0
- src/extcompat/code/consent.py +162 -0
- src/extcompat/code/host.py +353 -0
- src/extcompat/code/hosts/py_host.py +763 -0
- src/extcompat/code/locate.py +105 -0
- src/extcompat/code/manager.py +325 -0
- src/extcompat/code/permissions.py +154 -0
- src/extcompat/code/sandbox.py +60 -0
- src/extcompat/colors.py +131 -0
- src/extcompat/common.py +184 -0
- src/extcompat/cson.py +269 -0
- src/extcompat/formats/__init__.py +22 -0
- src/extcompat/formats/_tm.py +189 -0
- src/extcompat/formats/_util.py +31 -0
- src/extcompat/formats/base16.py +66 -0
- src/extcompat/formats/brackets.py +172 -0
- src/extcompat/formats/eclipse.py +193 -0
- src/extcompat/formats/emacs.py +361 -0
- src/extcompat/formats/geany.py +147 -0
- src/extcompat/formats/generic.py +184 -0
- src/extcompat/formats/gtksource.py +117 -0
- src/extcompat/formats/helix.py +91 -0
- src/extcompat/formats/jetbrains.py +343 -0
- src/extcompat/formats/kate.py +130 -0
- src/extcompat/formats/micro.py +131 -0
- src/extcompat/formats/nano.py +111 -0
- src/extcompat/formats/notepadpp.py +140 -0
- src/extcompat/formats/pulsar.py +165 -0
- src/extcompat/formats/pyides.py +163 -0
- src/extcompat/formats/sublime.py +340 -0
- src/extcompat/jsonc.py +65 -0
- src/extcompat/lessish.py +128 -0
- src/extcompat/manager.py +122 -0
- src/extcompat/market/__init__.py +63 -0
- src/extcompat/market/sources.py +211 -0
- src/extcompat/model.py +88 -0
- src/extcompat/net.py +228 -0
- src/extcompat/openvsx.py +63 -0
- src/extcompat/readers.py +362 -0
- src/extcompat/registry.py +73 -0
- src/extcompat/safexml.py +63 -0
- src/extcompat/sexp.py +187 -0
- src/extcompat/sources.py +105 -0
- src/extcompat/store.py +276 -0
- src/extcompat/textmate.py +214 -0
- src/extcompat/themes.py +487 -0
- src/extcompat/yamlite.py +294 -0
- src/fileio.py +94 -0
- src/fs_ops.py +106 -0
- src/i18n.py +233 -0
- src/ia/__init__.py +1 -0
- src/ia/actions.py +295 -0
- src/ia/approval_gate.py +672 -0
- src/ia/checkpoints.py +308 -0
- src/ia/context_builder.py +921 -0
- src/ia/dialdiff.py +408 -0
- src/ia/iaspace.py +2078 -0
- src/ia/pair.py +296 -0
- src/ia/providers.py +954 -0
- src/ia/session.py +335 -0
- src/ia/toolbox.py +2524 -0
- src/launcher_actions.py +204 -0
- src/lint/__init__.py +1 -0
- src/lint/manager.py +1058 -0
- src/locales/.translate_manifest.json +64170 -0
- src/locales/de.json +4936 -0
- src/locales/en.json +4936 -0
- src/locales/es.json +4936 -0
- src/locales/fr.json +4936 -0
- src/locales/it.json +4936 -0
- src/locales/ja.json +4936 -0
- src/locales/ko.json +4936 -0
- src/locales/nl.json +4936 -0
- src/locales/pl.json +4936 -0
- src/locales/pt-BR.json +4936 -0
- src/locales/ru.json +4936 -0
- src/locales/tr.json +4936 -0
- src/locales/uk.json +4936 -0
- src/locales/zh-CN.json +4936 -0
- src/lsp/__init__.py +26 -0
- src/lsp/client.py +2300 -0
- src/lsp/dap_client.py +480 -0
- src/lsp/edits.py +84 -0
- src/lsp/framing.py +73 -0
- src/lsp/protocol.py +931 -0
- src/main.py +260 -0
- src/memtrim.py +91 -0
- src/plugins/__init__.py +1 -0
- src/plugins/api.py +1761 -0
- src/plugins/loader.py +571 -0
- src/plugins/process_runner.py +519 -0
- src/plugins/registry.py +342 -0
- src/plugins/safety.py +367 -0
- src/plugins/startup.py +195 -0
- src/plugins/store.py +1178 -0
- src/proc_registry.py +278 -0
- src/pyexec.py +394 -0
- src/recovery.py +259 -0
- src/stall_trace.py +92 -0
- src/standalone.py +1070 -0
- src/startup_profile.py +35 -0
- src/syntax/__init__.py +1 -0
- src/syntax/highlighter.py +776 -0
- src/syntax/patterns.py +584 -0
- src/system_profile.py +430 -0
- src/terminal/backends.py +658 -0
- src/terminal/internal.py +346 -0
- src/terminal/keys.py +138 -0
- src/terminal/palette.py +67 -0
- src/terminal/session.py +283 -0
- src/terminal/shells.py +79 -0
- src/terminal/view.py +489 -0
- src/terminal/vt.py +870 -0
- src/textfmt.py +22 -0
- src/theme/__init__.py +1 -0
- src/theme/base.py +1281 -0
- src/theme/colors.py +49 -0
- src/theme/manager.py +602 -0
- src/theme/utils.py +312 -0
- src/toolbox.py +329 -0
- src/trash_core.py +531 -0
- src/ui/__init__.py +1 -0
- src/ui/_perf_utils.py +285 -0
- src/ui/_persistence_utils.py +93 -0
- src/ui/accessibility.py +843 -0
- src/ui/activity_bar.py +860 -0
- src/ui/app_embed.py +434 -0
- src/ui/archive_panel.py +608 -0
- src/ui/bookmarks.py +314 -0
- src/ui/breadcrumb.py +383 -0
- src/ui/calculator_panel.py +982 -0
- src/ui/calendar_panel.py +1218 -0
- src/ui/chat_panel.py +1271 -0
- src/ui/chat_profile_dialog.py +278 -0
- src/ui/chat_render.py +128 -0
- src/ui/clock_panel.py +810 -0
- src/ui/code_outline.py +364 -0
- src/ui/code_runner.py +729 -0
- src/ui/code_stats.py +546 -0
- src/ui/collab_panel.py +1009 -0
- src/ui/color_picker.py +547 -0
- src/ui/command_palette.py +452 -0
- src/ui/cursor_manager.py +750 -0
- src/ui/custom_keywords_panel.py +413 -0
- src/ui/debug_panel.py +1037 -0
- src/ui/dependency_graph.py +692 -0
- src/ui/diff_panel.py +381 -0
- src/ui/docs_panel.py +514 -0
- src/ui/doom_embed.py +349 -0
- src/ui/dropdown.py +321 -0
- src/ui/easter_eggs.py +979 -0
- src/ui/env_manager.py +666 -0
- src/ui/extcode_bridge.py +215 -0
- src/ui/extcode_dialogs.py +412 -0
- src/ui/extcompat_dialog.py +583 -0
- src/ui/file_timeline.py +319 -0
- src/ui/file_tree.py +1208 -0
- src/ui/find_in_files.py +1355 -0
- src/ui/flowchart_panel.py +727 -0
- src/ui/formatter_panel.py +490 -0
- src/ui/git_auth.py +763 -0
- src/ui/git_clone_dialog.py +487 -0
- src/ui/git_panel.py +1483 -0
- src/ui/grab_safe.py +84 -0
- src/ui/internal_python_dialog.py +98 -0
- src/ui/k_ui/__init__.py +1305 -0
- src/ui/k_ui/_bgrenderer.py +317 -0
- src/ui/k_ui/_colors.py +213 -0
- src/ui/k_ui/_dock.py +545 -0
- src/ui/k_ui/_easter.py +290 -0
- src/ui/k_ui/_engine.py +5448 -0
- src/ui/k_ui/_perf.py +333 -0
- src/ui/k_ui/_tkutil.py +7 -0
- src/ui/k_ui/_tooltip.py +365 -0
- src/ui/k_ui/_widgets.py +1204 -0
- src/ui/k_ui/_world.py +837 -0
- src/ui/key_remapper.py +856 -0
- src/ui/launcher.py +1252 -0
- src/ui/lazy_panel.py +73 -0
- src/ui/macro_recorder.py +610 -0
- src/ui/menu_bar.py +898 -0
- src/ui/output_panel.py +321 -0
- src/ui/paint_canvas.py +1000 -0
- src/ui/paint_engine.py +535 -0
- src/ui/paint_panel.py +888 -0
- src/ui/panel_detach.py +112 -0
- src/ui/performance_panel.py +861 -0
- src/ui/pip_manager.py +1758 -0
- src/ui/plugin_panel.py +1586 -0
- src/ui/pomodoro_panel.py +447 -0
- src/ui/problems.py +566 -0
- src/ui/process_manager.py +1657 -0
- src/ui/project_templates.py +775 -0
- src/ui/recovery_dialog.py +122 -0
- src/ui/regex_playground.py +304 -0
- src/ui/remote_adapters.py +1398 -0
- src/ui/remote_browser.py +1224 -0
- src/ui/remote_profile_dialog.py +342 -0
- src/ui/render_panel.py +1293 -0
- src/ui/rest_client.py +549 -0
- src/ui/scratchpad.py +548 -0
- src/ui/search_bar.py +1274 -0
- src/ui/settings_editor.py +3349 -0
- src/ui/settings_window.py +1554 -0
- src/ui/snippets_panel.py +597 -0
- src/ui/sql_studio.py +1815 -0
- src/ui/status_bar.py +438 -0
- src/ui/tab_bar.py +654 -0
- src/ui/task_manager.py +1773 -0
- src/ui/terminal.py +525 -0
- src/ui/theme_preview_panel.py +851 -0
- src/ui/thread_safe_tk.py +152 -0
- src/ui/time_tracker.py +574 -0
- src/ui/tkbind.py +43 -0
- src/ui/todo_panel.py +358 -0
- src/ui/toolbox_panels.py +658 -0
- src/ui/trash_manager.py +657 -0
- src/ui/ui_scale.py +294 -0
- src/ui/ux_enhancements.py +41 -0
- src/ui/web_preview.py +397 -0
- src/ui/webdev.py +630 -0
- src/ui/welcome.py +567 -0
- src/ui/window_embed.py +1500 -0
- src/ui/wizard.py +1550 -0
- src/ui/workspace_switcher.py +418 -0
- src/ui/workspace_trust.py +370 -0
- src/ui/zen_audio.py +354 -0
- src/ui/zen_media.py +2271 -0
- src/ui/zen_media_client.py +303 -0
- src/ui/zen_media_host.py +329 -0
- src/ui/zen_player.py +907 -0
- src/ui/zen_player_widgets.py +700 -0
- src/updater/__init__.py +11 -0
- src/updater/assets.py +145 -0
- src/updater/backup.py +101 -0
- src/updater/channel.py +221 -0
- src/updater/dialog.py +492 -0
- src/updater/integrity.py +111 -0
- src/updater/manager.py +727 -0
- src/updater/result.py +114 -0
- src/venv_runtime.py +531 -0
- src/workspace_state.py +25 -0
src/editor/large_file.py
ADDED
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
"""Module: large_file - buffer virtual para abrir arquivos gigantes no editor.
|
|
2
|
+
|
|
3
|
+
O arquivo fica mapeado em memória (``mmap``) e o Tk só recebe a janela de linhas que está na tela:
|
|
4
|
+
|
|
5
|
+
Tier 1 (< GIANT_FILE_BYTES) - inserção em fatias, recursos pesados desligados.
|
|
6
|
+
Tier 2 (>= GIANT_FILE_BYTES) - janela virtual de ``VIEWPORT_LINES`` linhas sobre este buffer.
|
|
7
|
+
|
|
8
|
+
O índice guarda o deslocamento de uma linha a cada ``STRIDE``: 8 bytes por 64 linhas em vez de
|
|
9
|
+
dezenas de bytes por linha, então o custo de memória quase não cresce com o arquivo. O deslocamento
|
|
10
|
+
das demais linhas sai de uma busca curta a partir da marca anterior. Com o NumPy instalado a
|
|
11
|
+
varredura usa vetorização; sem ele, cai em ``bytes.find``.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import codecs
|
|
17
|
+
import contextlib
|
|
18
|
+
import difflib
|
|
19
|
+
import mmap
|
|
20
|
+
import threading
|
|
21
|
+
from array import array
|
|
22
|
+
from collections.abc import Callable
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from src.fileio import commit_temp, resolve_target, temp_path_for
|
|
27
|
+
|
|
28
|
+
STRIDE = 64
|
|
29
|
+
_SCAN_BLOCK = 16 * 1024 * 1024
|
|
30
|
+
_COPY_BLOCK = 64 * 1024 * 1024
|
|
31
|
+
_RUN_LINES = 20_000
|
|
32
|
+
|
|
33
|
+
_numpy: Any = False # False: ainda não tentou importar; None: indisponível
|
|
34
|
+
_USE_NUMPY = True # os testes desligam para exercitar a varredura sem NumPy
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _load_numpy() -> Any:
|
|
38
|
+
"""Importa o NumPy só quando um arquivo gigante precisa ser varrido (importá-lo custa na partida)."""
|
|
39
|
+
global _numpy
|
|
40
|
+
if _numpy is False:
|
|
41
|
+
try:
|
|
42
|
+
import numpy
|
|
43
|
+
|
|
44
|
+
_numpy = numpy
|
|
45
|
+
except ImportError:
|
|
46
|
+
_numpy = None
|
|
47
|
+
return _numpy
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _block_end(mm: mmap.mmap, pos: int, size: int, block: int) -> int:
|
|
51
|
+
"""Fim do bloco que começa em ``pos``, sempre logo depois de um ``\\n`` (ou no fim do arquivo)."""
|
|
52
|
+
end = min(pos + block, size)
|
|
53
|
+
if end >= size:
|
|
54
|
+
return size
|
|
55
|
+
cut = mm.rfind(b"\n", pos, end)
|
|
56
|
+
if cut < 0: # linha maior que o bloco: estende até o fim dela
|
|
57
|
+
cut = mm.find(b"\n", end)
|
|
58
|
+
return size if cut < 0 else cut + 1
|
|
59
|
+
return cut + 1
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class _Scan:
|
|
63
|
+
"""Resultado da varredura: marcas de linha e contagens para o tipo de quebra de linha."""
|
|
64
|
+
|
|
65
|
+
__slots__ = ("marks", "newlines", "crlf", "cr")
|
|
66
|
+
|
|
67
|
+
def __init__(self) -> None:
|
|
68
|
+
self.marks = array("Q", [0])
|
|
69
|
+
self.newlines = 0
|
|
70
|
+
self.crlf = 0
|
|
71
|
+
self.cr = 0
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _scan_block_numpy(np: Any, mm: mmap.mmap, pos: int, end: int, out: _Scan) -> None:
|
|
75
|
+
data = np.frombuffer(mm, dtype=np.uint8, count=end - pos, offset=pos)
|
|
76
|
+
try:
|
|
77
|
+
nl = np.flatnonzero(data == 10)
|
|
78
|
+
if nl.size:
|
|
79
|
+
first = (STRIDE - 1 - out.newlines) % STRIDE # próxima quebra que fecha um grupo de STRIDE linhas
|
|
80
|
+
out.marks.frombytes((nl[first::STRIDE] + (pos + 1)).astype(np.uint64).tobytes())
|
|
81
|
+
inner = nl[nl > 0]
|
|
82
|
+
out.crlf += int(np.count_nonzero(data[inner - 1] == 13))
|
|
83
|
+
out.cr += int(np.count_nonzero(data == 13))
|
|
84
|
+
out.newlines += int(nl.size)
|
|
85
|
+
finally:
|
|
86
|
+
del data
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _scan_block_python(block: bytes, pos: int, out: _Scan) -> None:
|
|
90
|
+
out.crlf += block.count(b"\r\n")
|
|
91
|
+
out.cr += block.count(b"\r")
|
|
92
|
+
count = out.newlines
|
|
93
|
+
find = block.find
|
|
94
|
+
i = find(b"\n")
|
|
95
|
+
while i >= 0:
|
|
96
|
+
count += 1
|
|
97
|
+
if count % STRIDE == 0:
|
|
98
|
+
out.marks.append(pos + i + 1)
|
|
99
|
+
i = find(b"\n", i + 1)
|
|
100
|
+
out.newlines = count
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def scan(mm: mmap.mmap, size: int, cancelled: Callable[[], bool] = lambda: False, use_numpy: bool = True) -> _Scan | None:
|
|
104
|
+
"""Varre o arquivo mapeado. Devolve ``None`` se ``cancelled()`` ficou verdadeiro no meio."""
|
|
105
|
+
out = _Scan()
|
|
106
|
+
np = _load_numpy() if use_numpy else None
|
|
107
|
+
pos = 0
|
|
108
|
+
while pos < size:
|
|
109
|
+
if cancelled():
|
|
110
|
+
return None
|
|
111
|
+
end = _block_end(mm, pos, size, _SCAN_BLOCK)
|
|
112
|
+
if np is not None:
|
|
113
|
+
_scan_block_numpy(np, mm, pos, end, out)
|
|
114
|
+
else:
|
|
115
|
+
_scan_block_python(mm[pos:end], pos, out)
|
|
116
|
+
pos = end
|
|
117
|
+
return out
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class _Piece:
|
|
121
|
+
"""Trecho contíguo do texto: ``count`` linhas do original a partir de ``start`` ou ``lines`` novas."""
|
|
122
|
+
|
|
123
|
+
__slots__ = ("start", "count", "lines")
|
|
124
|
+
|
|
125
|
+
def __init__(self, start: int, count: int, lines: list[str] | None = None) -> None:
|
|
126
|
+
self.start = start
|
|
127
|
+
self.count = count
|
|
128
|
+
self.lines = lines
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _same_codec(a: str, b: str) -> bool:
|
|
132
|
+
try:
|
|
133
|
+
return codecs.lookup(a).name == codecs.lookup(b).name
|
|
134
|
+
except LookupError:
|
|
135
|
+
return False
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class VirtualFileBuffer:
|
|
139
|
+
"""Arquivo mapeado em memória com índice esparso de linhas e um dicionário de linhas editadas.
|
|
140
|
+
|
|
141
|
+
- O índice é montado em uma thread; ``is_ready`` indica quando termina.
|
|
142
|
+
- O texto é uma lista de pedaços: trechos de linhas do arquivo original e trechos de linhas
|
|
143
|
+
novas (``_Piece``). Inserir ou apagar linhas só mexe nessa lista, então os números de linha
|
|
144
|
+
seguintes se ajustam sozinhos e ``total_lines`` acompanha as edições.
|
|
145
|
+
- O salvamento copia do mmap, em blocos, tudo o que não foi editado; só as linhas novas
|
|
146
|
+
e a última passam pelo Python. Depois de salvar o arquivo é reaberto e reindexado.
|
|
147
|
+
"""
|
|
148
|
+
|
|
149
|
+
def __init__(
|
|
150
|
+
self,
|
|
151
|
+
path: Path,
|
|
152
|
+
encoding: str,
|
|
153
|
+
eol: str,
|
|
154
|
+
on_ready: Callable[[int], None],
|
|
155
|
+
) -> None:
|
|
156
|
+
self._path = Path(path)
|
|
157
|
+
self._encoding = encoding
|
|
158
|
+
self._on_ready = on_ready
|
|
159
|
+
|
|
160
|
+
self._f: Any = None
|
|
161
|
+
self._mm: mmap.mmap | None = None
|
|
162
|
+
self._size = 0
|
|
163
|
+
self._marks = array("Q", [0])
|
|
164
|
+
self._pieces: list[_Piece] = []
|
|
165
|
+
self._orig_total = 0
|
|
166
|
+
self._final_nl = True # o arquivo original termina em quebra de linha
|
|
167
|
+
self._lock = threading.RLock()
|
|
168
|
+
|
|
169
|
+
self.is_ready = False
|
|
170
|
+
self.total_lines = 0 # linhas do texto atual (com as edições)
|
|
171
|
+
self.error: str | None = None
|
|
172
|
+
self.detected_eol = "" # "\n" ou "\r\n" quando o arquivo todo usa o mesmo; "" se misto ou indefinido
|
|
173
|
+
|
|
174
|
+
self._cancelled = False
|
|
175
|
+
self._thread = threading.Thread(target=self._build_index, daemon=True, name="vfb-index")
|
|
176
|
+
self._thread.start()
|
|
177
|
+
|
|
178
|
+
# --- índice ---------------------------------------------------------------------------
|
|
179
|
+
|
|
180
|
+
def _open(self) -> None:
|
|
181
|
+
self._f = open(self._path, "rb") # noqa: SIM115 - fica aberto enquanto o mmap existir
|
|
182
|
+
self._size = self._path.stat().st_size
|
|
183
|
+
self._mm = mmap.mmap(self._f.fileno(), 0, access=mmap.ACCESS_READ) if self._size else None
|
|
184
|
+
|
|
185
|
+
def _release(self) -> None:
|
|
186
|
+
with contextlib.suppress(OSError, ValueError, BufferError):
|
|
187
|
+
if self._mm is not None:
|
|
188
|
+
self._mm.close()
|
|
189
|
+
self._mm = None
|
|
190
|
+
with contextlib.suppress(OSError):
|
|
191
|
+
if self._f is not None:
|
|
192
|
+
self._f.close()
|
|
193
|
+
self._f = None
|
|
194
|
+
|
|
195
|
+
def _index(self) -> bool:
|
|
196
|
+
"""Abre o arquivo e monta o índice; ``False`` se foi cancelado."""
|
|
197
|
+
self._open()
|
|
198
|
+
if self._mm is None:
|
|
199
|
+
self._publish(array("Q", [0]), 1, "", True)
|
|
200
|
+
return True
|
|
201
|
+
found = scan(self._mm, self._size, lambda: self._cancelled, use_numpy=_USE_NUMPY)
|
|
202
|
+
if found is None:
|
|
203
|
+
return False
|
|
204
|
+
total = found.newlines + (0 if self._mm[self._size - 1 : self._size] == b"\n" else 1)
|
|
205
|
+
eol = ""
|
|
206
|
+
if found.newlines:
|
|
207
|
+
if found.crlf == found.newlines and found.cr == found.crlf:
|
|
208
|
+
eol = "\r\n"
|
|
209
|
+
elif found.crlf == 0 and found.cr == 0:
|
|
210
|
+
eol = "\n"
|
|
211
|
+
self._publish(found.marks, total, eol, self._mm[self._size - 1 : self._size] == b"\n")
|
|
212
|
+
return True
|
|
213
|
+
|
|
214
|
+
def _publish(self, marks: array, total: int, eol: str, final_nl: bool) -> None:
|
|
215
|
+
with self._lock:
|
|
216
|
+
self._marks = marks
|
|
217
|
+
self._orig_total = self.total_lines = total
|
|
218
|
+
self._pieces = [_Piece(0, total)]
|
|
219
|
+
self._final_nl = final_nl
|
|
220
|
+
self.detected_eol = eol
|
|
221
|
+
self.is_ready = True
|
|
222
|
+
|
|
223
|
+
def _build_index(self) -> None:
|
|
224
|
+
try:
|
|
225
|
+
if self._index():
|
|
226
|
+
self._on_ready(self.total_lines)
|
|
227
|
+
except (OSError, ValueError) as exc:
|
|
228
|
+
if not self._cancelled:
|
|
229
|
+
self.error = str(exc)
|
|
230
|
+
self._on_ready(0)
|
|
231
|
+
|
|
232
|
+
# --- leitura --------------------------------------------------------------------------
|
|
233
|
+
|
|
234
|
+
def _line_start(self, line: int) -> int:
|
|
235
|
+
"""Deslocamento em bytes do início de ``line`` (``total_lines`` devolve o fim do arquivo)."""
|
|
236
|
+
if line >= self._orig_total:
|
|
237
|
+
return self._size
|
|
238
|
+
group, rest = divmod(line, STRIDE)
|
|
239
|
+
pos = self._marks[group]
|
|
240
|
+
mm = self._mm
|
|
241
|
+
for _ in range(rest):
|
|
242
|
+
pos = mm.find(b"\n", pos) + 1
|
|
243
|
+
return pos
|
|
244
|
+
|
|
245
|
+
def _read_lines(self, start: int, end: int) -> list[str]:
|
|
246
|
+
"""Linhas do arquivo no disco (sem as edições), em uma única leitura e decodificação."""
|
|
247
|
+
end = min(end, self._orig_total)
|
|
248
|
+
if start >= end:
|
|
249
|
+
return []
|
|
250
|
+
if self._mm is None:
|
|
251
|
+
return [""]
|
|
252
|
+
text = self._mm[self._line_start(start) : self._line_start(end)].decode(self._encoding, errors="replace")
|
|
253
|
+
parts = text.split("\n")
|
|
254
|
+
tail = parts.pop() # vazio se o trecho termina em quebra; senão, a última linha sem terminador
|
|
255
|
+
lines = [p[:-1] if p.endswith("\r") else p for p in parts]
|
|
256
|
+
if tail:
|
|
257
|
+
lines.append(tail)
|
|
258
|
+
return lines
|
|
259
|
+
|
|
260
|
+
def get_lines(self, start: int, end: int) -> list[str]:
|
|
261
|
+
"""Linhas ``[start, end)`` (base 0) do texto atual, com as edições."""
|
|
262
|
+
if not self.is_ready:
|
|
263
|
+
return []
|
|
264
|
+
with self._lock:
|
|
265
|
+
return self._composed(start, end)
|
|
266
|
+
|
|
267
|
+
def _composed(self, start: int, end: int) -> list[str]:
|
|
268
|
+
out: list[str] = []
|
|
269
|
+
pos = 0
|
|
270
|
+
for piece in self._pieces:
|
|
271
|
+
nxt = pos + piece.count
|
|
272
|
+
if nxt > start and pos < end:
|
|
273
|
+
lo, hi = max(start, pos) - pos, min(end, nxt) - pos
|
|
274
|
+
if piece.lines is None:
|
|
275
|
+
out.extend(self._read_lines(piece.start + lo, piece.start + hi))
|
|
276
|
+
else:
|
|
277
|
+
out.extend(piece.lines[lo:hi])
|
|
278
|
+
pos = nxt
|
|
279
|
+
if pos >= end:
|
|
280
|
+
break
|
|
281
|
+
return out
|
|
282
|
+
|
|
283
|
+
def _split(self, pos: int) -> int:
|
|
284
|
+
"""Garante que há uma divisa de pedaço na linha ``pos`` e devolve o índice do pedaço que começa nela."""
|
|
285
|
+
at = 0
|
|
286
|
+
for i, piece in enumerate(self._pieces):
|
|
287
|
+
if at == pos:
|
|
288
|
+
return i
|
|
289
|
+
if at < pos < at + piece.count:
|
|
290
|
+
cut = pos - at
|
|
291
|
+
if piece.lines is None:
|
|
292
|
+
head, tail = _Piece(piece.start, cut), _Piece(piece.start + cut, piece.count - cut)
|
|
293
|
+
else:
|
|
294
|
+
head, tail = _Piece(0, cut, piece.lines[:cut]), _Piece(0, piece.count - cut, piece.lines[cut:])
|
|
295
|
+
self._pieces[i : i + 1] = [head, tail]
|
|
296
|
+
return i + 1
|
|
297
|
+
at += piece.count
|
|
298
|
+
return len(self._pieces)
|
|
299
|
+
|
|
300
|
+
def _coalesce(self) -> None:
|
|
301
|
+
merged: list[_Piece] = []
|
|
302
|
+
for piece in self._pieces:
|
|
303
|
+
if piece.count == 0:
|
|
304
|
+
continue
|
|
305
|
+
last = merged[-1] if merged else None
|
|
306
|
+
if last is not None and last.lines is None and piece.lines is None and last.start + last.count == piece.start:
|
|
307
|
+
last.count += piece.count
|
|
308
|
+
elif last is not None and last.lines is not None and piece.lines is not None:
|
|
309
|
+
last.lines = last.lines + piece.lines
|
|
310
|
+
last.count += piece.count
|
|
311
|
+
else:
|
|
312
|
+
merged.append(piece)
|
|
313
|
+
self._pieces = merged
|
|
314
|
+
|
|
315
|
+
def _replace(self, start: int, count: int, new: list[str]) -> None:
|
|
316
|
+
"""Troca as ``count`` linhas a partir de ``start`` por ``new`` (que pode ter outro tamanho)."""
|
|
317
|
+
first = self._split(start)
|
|
318
|
+
last = self._split(start + count)
|
|
319
|
+
self._pieces[first:last] = [_Piece(0, len(new), list(new))] if new else []
|
|
320
|
+
self.total_lines += len(new) - count
|
|
321
|
+
self._coalesce()
|
|
322
|
+
|
|
323
|
+
def flush_widget_edits(
|
|
324
|
+
self,
|
|
325
|
+
widget_lines: list[str],
|
|
326
|
+
viewport_start: int,
|
|
327
|
+
old_count: int | None = None,
|
|
328
|
+
display: Callable[[str], str] | None = None,
|
|
329
|
+
) -> None:
|
|
330
|
+
"""Incorpora ao texto o que mudou na janela do widget.
|
|
331
|
+
|
|
332
|
+
``old_count`` é quantas linhas a janela tinha quando foi carregada (o widget pode ter hoje
|
|
333
|
+
mais ou menos). ``display`` é a transformação que o editor aplica ao exibir (remover
|
|
334
|
+
caracteres invisíveis, truncar linhas enormes): uma linha que só difere por isso não conta
|
|
335
|
+
como edição e o texto original dela é mantido.
|
|
336
|
+
"""
|
|
337
|
+
if not self.is_ready:
|
|
338
|
+
return
|
|
339
|
+
with self._lock:
|
|
340
|
+
count = old_count if old_count is not None else min(len(widget_lines), self.total_lines - viewport_start)
|
|
341
|
+
current = self._composed(viewport_start, viewport_start + count)
|
|
342
|
+
shown = [display(ln) for ln in current] if display else current
|
|
343
|
+
if shown == widget_lines:
|
|
344
|
+
return
|
|
345
|
+
head = 0
|
|
346
|
+
limit = min(len(shown), len(widget_lines))
|
|
347
|
+
while head < limit and shown[head] == widget_lines[head]:
|
|
348
|
+
head += 1
|
|
349
|
+
tail = 0
|
|
350
|
+
while tail < limit - head and shown[-1 - tail] == widget_lines[-1 - tail]:
|
|
351
|
+
tail += 1
|
|
352
|
+
old_mid = shown[head : len(shown) - tail]
|
|
353
|
+
new_mid = widget_lines[head : len(widget_lines) - tail]
|
|
354
|
+
base = viewport_start + head
|
|
355
|
+
if len(old_mid) * len(new_mid) <= 400_000:
|
|
356
|
+
ops = difflib.SequenceMatcher(None, old_mid, new_mid, autojunk=False).get_opcodes()
|
|
357
|
+
else:
|
|
358
|
+
ops = [("replace", 0, len(old_mid), 0, len(new_mid))]
|
|
359
|
+
for tag, i1, i2, j1, j2 in reversed(ops):
|
|
360
|
+
if tag != "equal":
|
|
361
|
+
self._replace(base + i1, i2 - i1, new_mid[j1:j2])
|
|
362
|
+
|
|
363
|
+
def has_edits(self) -> bool:
|
|
364
|
+
"""``True`` se o texto atual passou por alguma edição em relação ao arquivo."""
|
|
365
|
+
return not (len(self._pieces) == 1 and self._pieces[0].lines is None)
|
|
366
|
+
|
|
367
|
+
def edit_count(self) -> int:
|
|
368
|
+
"""Quantidade de linhas que vieram de edições."""
|
|
369
|
+
return sum(p.count for p in self._pieces if p.lines is not None)
|
|
370
|
+
|
|
371
|
+
# --- salvamento -----------------------------------------------------------------------
|
|
372
|
+
|
|
373
|
+
def save_to_path(
|
|
374
|
+
self,
|
|
375
|
+
dest: Path,
|
|
376
|
+
eol: str,
|
|
377
|
+
encoding: str,
|
|
378
|
+
trim_trailing: bool = False,
|
|
379
|
+
insert_final_newline: bool = True,
|
|
380
|
+
) -> None:
|
|
381
|
+
"""Grava o arquivo completo, com as edições, em ``dest`` (escrita atômica).
|
|
382
|
+
|
|
383
|
+
Quando o arquivo inteiro já usa ``eol``, a codificação não muda e não há ``trim_trailing``,
|
|
384
|
+
os trechos sem edição são copiados do mmap sem decodificar. Nos demais casos eles são
|
|
385
|
+
convertidos em blocos de linhas. Em seguida o mmap é solto (o Windows não substitui um
|
|
386
|
+
arquivo mapeado) e o resultado é reaberto e reindexado.
|
|
387
|
+
|
|
388
|
+
Raises:
|
|
389
|
+
RuntimeError: Se o índice ainda não foi construído.
|
|
390
|
+
OSError: Erro de I/O ao escrever.
|
|
391
|
+
"""
|
|
392
|
+
if not self.is_ready:
|
|
393
|
+
raise RuntimeError("VirtualFileBuffer: índice ainda não pronto")
|
|
394
|
+
target = resolve_target(dest)
|
|
395
|
+
tmp = temp_path_for(target)
|
|
396
|
+
verbatim = self.detected_eol == eol and not trim_trailing and _same_codec(encoding, self._encoding)
|
|
397
|
+
with self._lock:
|
|
398
|
+
try:
|
|
399
|
+
with open(tmp, "wb") as out:
|
|
400
|
+
self._write_body(out, eol, encoding, trim_trailing, insert_final_newline, verbatim)
|
|
401
|
+
except OSError:
|
|
402
|
+
with contextlib.suppress(OSError):
|
|
403
|
+
tmp.unlink()
|
|
404
|
+
raise
|
|
405
|
+
self._release()
|
|
406
|
+
try:
|
|
407
|
+
commit_temp(tmp, target)
|
|
408
|
+
except OSError:
|
|
409
|
+
with contextlib.suppress(OSError):
|
|
410
|
+
tmp.unlink()
|
|
411
|
+
self._open() # as edições continuam valendo sobre o arquivo original
|
|
412
|
+
raise
|
|
413
|
+
self._reopen(target)
|
|
414
|
+
|
|
415
|
+
def _reopen(self, path: Path) -> None:
|
|
416
|
+
self._path = path
|
|
417
|
+
self.is_ready = False
|
|
418
|
+
try:
|
|
419
|
+
self._index()
|
|
420
|
+
except (OSError, ValueError) as exc:
|
|
421
|
+
self.error = str(exc)
|
|
422
|
+
|
|
423
|
+
def _write_body(
|
|
424
|
+
self, out: Any, eol: str, encoding: str, trim: bool, final_newline: bool, verbatim: bool
|
|
425
|
+
) -> None:
|
|
426
|
+
total = self.total_lines
|
|
427
|
+
pos = 0
|
|
428
|
+
|
|
429
|
+
def emit(text: str, add_eol: bool) -> None:
|
|
430
|
+
if trim:
|
|
431
|
+
text = text.rstrip()
|
|
432
|
+
out.write((text + (eol if add_eol else "")).encode(encoding, errors="replace"))
|
|
433
|
+
|
|
434
|
+
for piece in self._pieces:
|
|
435
|
+
pos += piece.count
|
|
436
|
+
is_last = pos == total
|
|
437
|
+
if piece.lines is None:
|
|
438
|
+
begin, end = piece.start, piece.start + piece.count
|
|
439
|
+
# a última linha do arquivo original pode não ter terminador: ela passa pelo Python
|
|
440
|
+
special = is_last or (end == self._orig_total and not self._final_nl)
|
|
441
|
+
body_end = end - 1 if special else end
|
|
442
|
+
if body_end > begin:
|
|
443
|
+
self._copy_run(out, begin, body_end, eol, encoding, trim, verbatim)
|
|
444
|
+
if special:
|
|
445
|
+
emit(self._read_lines(end - 1, end)[0], not is_last or final_newline)
|
|
446
|
+
else:
|
|
447
|
+
lines = piece.lines
|
|
448
|
+
body = lines[:-1] if is_last else lines
|
|
449
|
+
for first in range(0, len(body), _RUN_LINES):
|
|
450
|
+
chunk = body[first : first + _RUN_LINES]
|
|
451
|
+
if trim:
|
|
452
|
+
chunk = [ln.rstrip() for ln in chunk]
|
|
453
|
+
out.write((eol.join(chunk) + eol).encode(encoding, errors="replace"))
|
|
454
|
+
if is_last:
|
|
455
|
+
emit(lines[-1], final_newline)
|
|
456
|
+
|
|
457
|
+
def _copy_run(self, out: Any, start: int, end: int, eol: str, encoding: str, trim: bool, verbatim: bool) -> None:
|
|
458
|
+
"""Escreve as linhas ``[start, end)`` (sem edições), cada uma com seu terminador."""
|
|
459
|
+
if verbatim and self._mm is not None:
|
|
460
|
+
view = memoryview(self._mm)
|
|
461
|
+
try:
|
|
462
|
+
pos, stop = self._line_start(start), self._line_start(end)
|
|
463
|
+
while pos < stop:
|
|
464
|
+
nxt = min(pos + _COPY_BLOCK, stop)
|
|
465
|
+
out.write(view[pos:nxt])
|
|
466
|
+
pos = nxt
|
|
467
|
+
finally:
|
|
468
|
+
view.release()
|
|
469
|
+
return
|
|
470
|
+
for first in range(start, end, _RUN_LINES):
|
|
471
|
+
lines = self._read_lines(first, min(first + _RUN_LINES, end))
|
|
472
|
+
if trim:
|
|
473
|
+
lines = [ln.rstrip() for ln in lines]
|
|
474
|
+
out.write((eol.join(lines) + eol).encode(encoding, errors="replace"))
|
|
475
|
+
|
|
476
|
+
# --- ciclo de vida --------------------------------------------------------------------
|
|
477
|
+
|
|
478
|
+
def close(self) -> None:
|
|
479
|
+
"""Cancela a indexação em andamento e fecha o mmap e o arquivo."""
|
|
480
|
+
self._cancelled = True
|
|
481
|
+
if threading.current_thread() is not self._thread:
|
|
482
|
+
self._thread.join(2.0)
|
|
483
|
+
with self._lock:
|
|
484
|
+
self._release()
|
|
485
|
+
|
|
486
|
+
def __del__(self) -> None:
|
|
487
|
+
with contextlib.suppress(Exception):
|
|
488
|
+
self._release()
|
src/editor/ligatures.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Codis - Ligatures: motor de ligaturas pseudo via destaque visual.
|
|
2
|
+
|
|
3
|
+
Modo 'pseudo': detecta sequências ASCII comuns (ex: ->, !=, >=) nas linhas
|
|
4
|
+
visíveis e aplica uma tag de destaque colorido, sinalizando que a sequência
|
|
5
|
+
seria renderizada como ligatura em fontes compatíveis.
|
|
6
|
+
|
|
7
|
+
Modo 'native': delega ao sistema de fontes (Tk + HarfBuzz) - configurado em pane.py.
|
|
8
|
+
Modo 'both': aplica destaque pseudo APÓS ativar ligaturas nativas na fonte.
|
|
9
|
+
Modo 'off': nenhuma substituição.
|
|
10
|
+
|
|
11
|
+
O texto bruto (ASCII) é sempre preservado - salvo e copiado normalmente.
|
|
12
|
+
A engine opera apenas nas linhas visíveis para mínimo impacto na performance.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import contextlib
|
|
18
|
+
import tkinter as tk
|
|
19
|
+
|
|
20
|
+
LIGATURE_PAIRS: list[tuple[str, str]] = [
|
|
21
|
+
("==>", "⟹"),
|
|
22
|
+
("<=>", "⟺"),
|
|
23
|
+
("-->", "⟶"),
|
|
24
|
+
("<--", "⟵"),
|
|
25
|
+
("->>", "↠"),
|
|
26
|
+
("->", "->"),
|
|
27
|
+
("<-", "<-"),
|
|
28
|
+
("=>", "⇒"),
|
|
29
|
+
("!==", "≢"),
|
|
30
|
+
("===", "≡"),
|
|
31
|
+
("!=", "≠"),
|
|
32
|
+
(">=", "≥"),
|
|
33
|
+
("<=", "≤"),
|
|
34
|
+
("&&", "∧"),
|
|
35
|
+
("||", "∨"),
|
|
36
|
+
("...", "..."),
|
|
37
|
+
("::", "∷"),
|
|
38
|
+
("<>", "◇"),
|
|
39
|
+
]
|
|
40
|
+
"""Sequências ASCII reconhecidas e seus substitutos Unicode (tooltip/badge).
|
|
41
|
+
|
|
42
|
+
Ordenadas do padrão mais longo para o mais curto, garantindo que o match
|
|
43
|
+
guloso em :meth:`LigatureEngine._apply_line` priorize sempre a sequência
|
|
44
|
+
mais específica disponível em cada posição da linha.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
_TAG_PFX = "codis_lig_"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class LigatureEngine:
|
|
51
|
+
"""Motor de ligaturas pseudo para tk.Text.
|
|
52
|
+
|
|
53
|
+
Realça visualmente as sequências de ligatura nas linhas visíveis.
|
|
54
|
+
O texto fonte não é modificado.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
text: Widget tk.Text alvo.
|
|
58
|
+
accent_color: Cor de destaque para as sequências reconhecidas.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
def __init__(self, text: tk.Text, accent_color: str = "#cba6f7") -> None:
|
|
62
|
+
self._text = text
|
|
63
|
+
self._accent = accent_color
|
|
64
|
+
self._enabled = False
|
|
65
|
+
self._job: str | None = None
|
|
66
|
+
self._setup_tags()
|
|
67
|
+
|
|
68
|
+
def _for_each_tag(self, action) -> None:
|
|
69
|
+
"""Executa ``action(tag)`` para a tag de cada sequência de ligatura.
|
|
70
|
+
|
|
71
|
+
Centraliza a iteração sobre :data:`LIGATURE_PAIRS` e a supressão
|
|
72
|
+
de ``TclError``, usada de forma idêntica ao configurar, remover
|
|
73
|
+
ou recolorir as tags de destaque.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
action: Callable que recebe o nome da tag e aplica a operação
|
|
77
|
+
desejada no widget de texto.
|
|
78
|
+
"""
|
|
79
|
+
for seq, _ in LIGATURE_PAIRS:
|
|
80
|
+
tag = f"{_TAG_PFX}{seq}"
|
|
81
|
+
with contextlib.suppress(tk.TclError):
|
|
82
|
+
action(tag)
|
|
83
|
+
|
|
84
|
+
def _setup_tags(self) -> None:
|
|
85
|
+
"""Cria tags de highlight para cada sequência de ligatura."""
|
|
86
|
+
self._for_each_tag(
|
|
87
|
+
lambda tag: self._text.tag_configure(tag, foreground=self._accent)
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def set_enabled(self, enabled: bool) -> None:
|
|
91
|
+
"""Ativa ou desativa o motor."""
|
|
92
|
+
was = self._enabled
|
|
93
|
+
self._enabled = enabled
|
|
94
|
+
if not enabled and was:
|
|
95
|
+
self._clear_all()
|
|
96
|
+
elif enabled and not was:
|
|
97
|
+
self._schedule(0)
|
|
98
|
+
|
|
99
|
+
def schedule(self, delay_ms: int = 80) -> None:
|
|
100
|
+
"""Agenda reaplicação com debounce (chamado pelo editor ao modificar/rolar)."""
|
|
101
|
+
if self._enabled:
|
|
102
|
+
self._schedule(delay_ms)
|
|
103
|
+
|
|
104
|
+
def _schedule(self, delay_ms: int = 80) -> None:
|
|
105
|
+
"""Reagenda a próxima aplicação de ligaturas, cancelando a anterior."""
|
|
106
|
+
if self._job:
|
|
107
|
+
with contextlib.suppress(tk.TclError):
|
|
108
|
+
self._text.after_cancel(self._job)
|
|
109
|
+
self._job = self._text.after(delay_ms, self._apply_visible)
|
|
110
|
+
|
|
111
|
+
def _apply_visible(self) -> None:
|
|
112
|
+
"""Aplica ligaturas apenas nas linhas visíveis (performance)."""
|
|
113
|
+
self._job = None
|
|
114
|
+
if not self._enabled:
|
|
115
|
+
return
|
|
116
|
+
try:
|
|
117
|
+
height = self._text.winfo_height()
|
|
118
|
+
top = int(self._text.index("@0,0").split(".")[0])
|
|
119
|
+
bot = int(self._text.index(
|
|
120
|
+
f"@0,{max(height - 1, 1)}").split(".")[0])
|
|
121
|
+
except (tk.TclError, ValueError):
|
|
122
|
+
return
|
|
123
|
+
|
|
124
|
+
top = max(1, top - 3)
|
|
125
|
+
bot = bot + 3
|
|
126
|
+
|
|
127
|
+
self._clear_region(f"{top}.0", f"{bot}.end")
|
|
128
|
+
|
|
129
|
+
for ln in range(top, bot + 1):
|
|
130
|
+
try:
|
|
131
|
+
line_text = self._text.get(f"{ln}.0", f"{ln}.end")
|
|
132
|
+
except tk.TclError:
|
|
133
|
+
break
|
|
134
|
+
if not line_text:
|
|
135
|
+
continue
|
|
136
|
+
self._apply_line(ln, line_text)
|
|
137
|
+
|
|
138
|
+
def _apply_line(self, ln: int, line: str) -> None:
|
|
139
|
+
"""Aplica highlight de ligaturas em uma linha (match guloso)."""
|
|
140
|
+
occupied: set[int] = set()
|
|
141
|
+
|
|
142
|
+
for seq, _ in LIGATURE_PAIRS:
|
|
143
|
+
slen = len(seq)
|
|
144
|
+
pos = 0
|
|
145
|
+
while True:
|
|
146
|
+
idx = line.find(seq, pos)
|
|
147
|
+
if idx == -1:
|
|
148
|
+
break
|
|
149
|
+
region = set(range(idx, idx + slen))
|
|
150
|
+
if region & occupied:
|
|
151
|
+
pos = idx + 1
|
|
152
|
+
continue
|
|
153
|
+
occupied.update(region)
|
|
154
|
+
tag = f"{_TAG_PFX}{seq}"
|
|
155
|
+
with contextlib.suppress(tk.TclError):
|
|
156
|
+
self._text.tag_add(
|
|
157
|
+
tag, f"{ln}.{idx}", f"{ln}.{idx + slen}")
|
|
158
|
+
pos = idx + slen
|
|
159
|
+
|
|
160
|
+
def _clear_region(self, start: str, end: str) -> None:
|
|
161
|
+
"""Remove todas as tags de ligatura de uma região."""
|
|
162
|
+
self._for_each_tag(lambda tag: self._text.tag_remove(tag, start, end))
|
|
163
|
+
|
|
164
|
+
def _clear_all(self) -> None:
|
|
165
|
+
"""Remove todas as tags de ligatura do documento inteiro."""
|
|
166
|
+
self._clear_region("1.0", "end")
|
|
167
|
+
|
|
168
|
+
def update_accent(self, color: str) -> None:
|
|
169
|
+
"""Atualiza a cor de destaque (chamado ao trocar tema)."""
|
|
170
|
+
self._accent = color
|
|
171
|
+
self._for_each_tag(
|
|
172
|
+
lambda tag: self._text.tag_configure(tag, foreground=color))
|
|
173
|
+
|
|
174
|
+
def on_change(self) -> None:
|
|
175
|
+
"""Deve ser chamado pelo editor ao modificar o conteúdo."""
|
|
176
|
+
self.schedule(80)
|
|
177
|
+
|
|
178
|
+
def on_scroll(self) -> None:
|
|
179
|
+
"""Deve ser chamado pelo editor ao rolar o conteúdo."""
|
|
180
|
+
self.schedule(120)
|