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/collab/ot.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
"""Codis - Transformação Operacional (OT) para edição colaborativa.
|
|
2
|
+
|
|
3
|
+
Modelo
|
|
4
|
+
------
|
|
5
|
+
Um documento é uma string. Uma *operação* (:class:`TextOp`) é um ``insert``
|
|
6
|
+
ou ``delete`` de caracteres. Uma *mudança* é uma **lista** de operações
|
|
7
|
+
aplicáveis em sequência (cada uma sobre o resultado da anterior).
|
|
8
|
+
|
|
9
|
+
Convergência
|
|
10
|
+
------------
|
|
11
|
+
:func:`transform` implementa a propriedade TP1: dadas duas mudanças ``A`` e
|
|
12
|
+
``B`` feitas concorrentemente sobre o mesmo estado, ``A' = transform(A, B)``
|
|
13
|
+
aplicada depois de ``B`` produz o mesmo documento que ``B'`` aplicada depois
|
|
14
|
+
de ``A``. A única fonte de ambiguidade é o empate de inserções na mesma
|
|
15
|
+
posição, resolvido pelo parâmetro ``a_after`` (quem é ordenado depois).
|
|
16
|
+
Uma deleção que engloba uma inserção concorrente é *dividida em duas*, de
|
|
17
|
+
modo que o texto inserido por outro usuário nunca é apagado em silêncio.
|
|
18
|
+
|
|
19
|
+
:class:`ClientOT` é a máquina de estados do cliente (protocolo Jupiter):
|
|
20
|
+
no máximo uma mudança em voo (aguardando ACK) e as demais em buffer.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
|
|
27
|
+
MAX_OP_TEXT = 1_000_000
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class TextOp:
|
|
32
|
+
"""Operação atômica de texto."""
|
|
33
|
+
|
|
34
|
+
op: str
|
|
35
|
+
pos: int
|
|
36
|
+
text: str = ""
|
|
37
|
+
length: int = 0
|
|
38
|
+
|
|
39
|
+
def to_dict(self) -> dict:
|
|
40
|
+
"""Serializa para o formato do protocolo."""
|
|
41
|
+
return {"op": self.op, "pos": self.pos, "text": self.text, "len": self.length}
|
|
42
|
+
|
|
43
|
+
@staticmethod
|
|
44
|
+
def from_dict(d: dict) -> TextOp:
|
|
45
|
+
"""Cria uma operação a partir de dados recebidos da rede.
|
|
46
|
+
|
|
47
|
+
Raises:
|
|
48
|
+
ValueError: se a operação, a posição, o tamanho ou o texto forem inválidos.
|
|
49
|
+
"""
|
|
50
|
+
if not isinstance(d, dict):
|
|
51
|
+
raise ValueError("operação malformada")
|
|
52
|
+
kind, pos = d.get("op"), d.get("pos")
|
|
53
|
+
text, length = d.get("text", ""), d.get("len", 0)
|
|
54
|
+
if kind not in ("insert", "delete"):
|
|
55
|
+
raise ValueError(f"tipo de operação inválido: {kind!r}")
|
|
56
|
+
if not (isinstance(pos, int) and isinstance(length, int) and isinstance(text, str)):
|
|
57
|
+
raise ValueError("campos de operação com tipo inválido")
|
|
58
|
+
if isinstance(pos, bool) or isinstance(length, bool) or pos < 0 or length < 0:
|
|
59
|
+
raise ValueError("posição e tamanho não podem ser negativos")
|
|
60
|
+
if len(text) > MAX_OP_TEXT:
|
|
61
|
+
raise ValueError("texto da operação grande demais")
|
|
62
|
+
return TextOp(op=kind, pos=pos, text=text, length=length)
|
|
63
|
+
|
|
64
|
+
def size(self) -> int:
|
|
65
|
+
"""Número de caracteres afetados."""
|
|
66
|
+
return len(self.text) if self.op == "insert" else self.length
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def ops_from_dicts(items: list) -> list[TextOp]:
|
|
70
|
+
"""Converte uma lista de dicts em ``TextOp`` validando cada item."""
|
|
71
|
+
if not isinstance(items, list):
|
|
72
|
+
raise ValueError("ops deve ser uma lista")
|
|
73
|
+
return [TextOp.from_dict(o) for o in items]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def is_valid(text_len: int, op: TextOp) -> bool:
|
|
77
|
+
"""Se ``op`` cabe num documento de ``text_len`` caracteres (sem clamp)."""
|
|
78
|
+
if op.op == "insert":
|
|
79
|
+
return 0 <= op.pos <= text_len and bool(op.text)
|
|
80
|
+
return op.length > 0 and op.pos >= 0 and op.pos + op.length <= text_len
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def apply_op(text: str, op: TextOp) -> str:
|
|
84
|
+
"""Aplica uma operação. Posições fora do documento são limitadas (clamp)."""
|
|
85
|
+
pos = max(0, min(op.pos, len(text)))
|
|
86
|
+
if op.op == "insert":
|
|
87
|
+
return text[:pos] + op.text + text[pos:]
|
|
88
|
+
if op.op == "delete":
|
|
89
|
+
end = min(pos + op.length, len(text))
|
|
90
|
+
return text[:pos] + text[end:]
|
|
91
|
+
return text
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def apply_ops(text: str, ops: list[TextOp]) -> str:
|
|
95
|
+
"""Aplica uma mudança (lista de operações) em sequência."""
|
|
96
|
+
for op in ops:
|
|
97
|
+
text = apply_op(text, op)
|
|
98
|
+
return text
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def validate_change(text: str, ops: list[TextOp]) -> bool:
|
|
102
|
+
"""Valida, sem clamp, que a mudança é aplicável a ``text``."""
|
|
103
|
+
length = len(text)
|
|
104
|
+
for op in ops:
|
|
105
|
+
if not is_valid(length, op):
|
|
106
|
+
return False
|
|
107
|
+
length += len(op.text) if op.op == "insert" else -op.length
|
|
108
|
+
return True
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def diff_change(old: str, new: str) -> list[TextOp]:
|
|
112
|
+
"""Menor mudança contígua que leva ``old`` a ``new``.
|
|
113
|
+
|
|
114
|
+
Usa prefixo/sufixo comuns (O(n), sem difflib): para digitação, colar,
|
|
115
|
+
apagar e desfazer isso gera no máximo uma deleção e uma inserção.
|
|
116
|
+
"""
|
|
117
|
+
if old == new:
|
|
118
|
+
return []
|
|
119
|
+
limit = min(len(old), len(new))
|
|
120
|
+
start = 0
|
|
121
|
+
while start < limit and old[start] == new[start]:
|
|
122
|
+
start += 1
|
|
123
|
+
end = 0
|
|
124
|
+
while end < limit - start and old[-1 - end] == new[-1 - end]:
|
|
125
|
+
end += 1
|
|
126
|
+
removed = old[start:len(old) - end]
|
|
127
|
+
added = new[start:len(new) - end]
|
|
128
|
+
ops: list[TextOp] = []
|
|
129
|
+
if removed:
|
|
130
|
+
ops.append(TextOp("delete", start, length=len(removed)))
|
|
131
|
+
if added:
|
|
132
|
+
ops.append(TextOp("insert", start, text=added))
|
|
133
|
+
return ops
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def xform(a: TextOp, b: TextOp, a_after: bool) -> list[TextOp]:
|
|
137
|
+
"""Transforma ``a`` para valer *depois* de ``b`` (ambas do mesmo estado).
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
a_after: em empate de inserções na mesma posição, ``a`` é ordenada
|
|
141
|
+
depois de ``b`` (desloca) quando ``True``.
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
Lista de 0, 1 ou 2 operações (2 quando uma deleção é dividida).
|
|
145
|
+
"""
|
|
146
|
+
if a.op == "insert" and b.op == "insert":
|
|
147
|
+
pos = a.pos
|
|
148
|
+
if a.pos > b.pos or (a.pos == b.pos and a_after):
|
|
149
|
+
pos += len(b.text)
|
|
150
|
+
return [TextOp("insert", pos, text=a.text)]
|
|
151
|
+
|
|
152
|
+
if a.op == "insert":
|
|
153
|
+
b_start, b_end = b.pos, b.pos + b.length
|
|
154
|
+
if a.pos <= b_start:
|
|
155
|
+
pos = a.pos
|
|
156
|
+
elif a.pos >= b_end:
|
|
157
|
+
pos = a.pos - b.length
|
|
158
|
+
else:
|
|
159
|
+
pos = b_start
|
|
160
|
+
return [TextOp("insert", pos, text=a.text)]
|
|
161
|
+
|
|
162
|
+
if b.op == "insert":
|
|
163
|
+
a_start, a_end = a.pos, a.pos + a.length
|
|
164
|
+
blen = len(b.text)
|
|
165
|
+
if b.pos <= a_start:
|
|
166
|
+
return [TextOp("delete", a.pos + blen, length=a.length)]
|
|
167
|
+
if b.pos >= a_end:
|
|
168
|
+
return [TextOp("delete", a.pos, length=a.length)]
|
|
169
|
+
upper = TextOp("delete", b.pos + blen, length=a_end - b.pos)
|
|
170
|
+
lower = TextOp("delete", a_start, length=b.pos - a_start)
|
|
171
|
+
return [upper, lower]
|
|
172
|
+
|
|
173
|
+
a_start, a_end = a.pos, a.pos + a.length
|
|
174
|
+
b_start, b_end = b.pos, b.pos + b.length
|
|
175
|
+
overlap = max(0, min(a_end, b_end) - max(a_start, b_start))
|
|
176
|
+
length = a.length - overlap
|
|
177
|
+
if length <= 0:
|
|
178
|
+
return []
|
|
179
|
+
if a_start >= b_end:
|
|
180
|
+
pos = a_start - b.length
|
|
181
|
+
elif a_start >= b_start:
|
|
182
|
+
pos = b_start
|
|
183
|
+
else:
|
|
184
|
+
pos = a_start
|
|
185
|
+
return [TextOp("delete", pos, length=length)]
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def transform(
|
|
189
|
+
a_ops: list[TextOp], b_ops: list[TextOp], a_after: bool
|
|
190
|
+
) -> tuple[list[TextOp], list[TextOp]]:
|
|
191
|
+
"""Transforma duas mudanças concorrentes uma contra a outra.
|
|
192
|
+
|
|
193
|
+
Returns:
|
|
194
|
+
``(a', b')``: ``a'`` vale depois de ``b`` e ``b'`` vale depois de ``a``;
|
|
195
|
+
``apply(apply(s, a), b') == apply(apply(s, b), a')``.
|
|
196
|
+
"""
|
|
197
|
+
if not a_ops or not b_ops:
|
|
198
|
+
return list(a_ops), list(b_ops)
|
|
199
|
+
if len(a_ops) == 1 and len(b_ops) == 1:
|
|
200
|
+
a, b = a_ops[0], b_ops[0]
|
|
201
|
+
return xform(a, b, a_after), xform(b, a, not a_after)
|
|
202
|
+
if len(a_ops) > 1:
|
|
203
|
+
first, rest = a_ops[:1], a_ops[1:]
|
|
204
|
+
first_t, b_mid = transform(first, b_ops, a_after)
|
|
205
|
+
rest_t, b_out = transform(rest, b_mid, a_after)
|
|
206
|
+
return first_t + rest_t, b_out
|
|
207
|
+
b_first, b_rest = b_ops[:1], b_ops[1:]
|
|
208
|
+
a_mid, b_first_t = transform(a_ops, b_first, a_after)
|
|
209
|
+
a_out, b_rest_t = transform(a_mid, b_rest, a_after)
|
|
210
|
+
return a_out, b_first_t + b_rest_t
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class ResyncNeeded(Exception):
|
|
214
|
+
"""O cliente precisa receber o documento completo novamente."""
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class RoomDoc:
|
|
218
|
+
"""Documento autoritativo: uma revisão por mudança aceita."""
|
|
219
|
+
|
|
220
|
+
MAX_HISTORY = 5000
|
|
221
|
+
TRIM_TO = 2000
|
|
222
|
+
|
|
223
|
+
def __init__(self, content: str = "", max_chars: int = 20_000_000) -> None:
|
|
224
|
+
self.content = content
|
|
225
|
+
self.max_chars = max_chars
|
|
226
|
+
self.history: list[list[TextOp]] = []
|
|
227
|
+
self.offset = 0
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def rev(self) -> int:
|
|
231
|
+
"""Revisão atual (número de mudanças aceitas desde a criação)."""
|
|
232
|
+
return self.offset + len(self.history)
|
|
233
|
+
|
|
234
|
+
def receive(self, client_rev: int, ops: list[TextOp]) -> list[TextOp]:
|
|
235
|
+
"""Aceita uma mudança baseada na revisão ``client_rev``.
|
|
236
|
+
|
|
237
|
+
Returns:
|
|
238
|
+
A mudança já transformada, como foi aplicada ao documento.
|
|
239
|
+
|
|
240
|
+
Raises:
|
|
241
|
+
ResyncNeeded: revisão inválida/descartada ou mudança inaplicável.
|
|
242
|
+
"""
|
|
243
|
+
if client_rev > self.rev or client_rev < self.offset:
|
|
244
|
+
raise ResyncNeeded("revisão fora do histórico")
|
|
245
|
+
change = list(ops)
|
|
246
|
+
for past in self.history[client_rev - self.offset:]:
|
|
247
|
+
change, _ = transform(change, past, a_after=True)
|
|
248
|
+
if not validate_change(self.content, change):
|
|
249
|
+
raise ResyncNeeded("mudança inaplicável")
|
|
250
|
+
new_content = apply_ops(self.content, change)
|
|
251
|
+
if len(new_content) > self.max_chars:
|
|
252
|
+
raise ResyncNeeded("documento grande demais")
|
|
253
|
+
self.content = new_content
|
|
254
|
+
self.history.append(change)
|
|
255
|
+
if len(self.history) > self.MAX_HISTORY:
|
|
256
|
+
drop = len(self.history) - self.TRIM_TO
|
|
257
|
+
self.history = self.history[drop:]
|
|
258
|
+
self.offset += drop
|
|
259
|
+
return change
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class ClientOT:
|
|
263
|
+
"""Estado OT de um cliente: revisão, mudança em voo e buffer.
|
|
264
|
+
|
|
265
|
+
Todas as chamadas devem ocorrer numa única thread (a da interface).
|
|
266
|
+
"""
|
|
267
|
+
|
|
268
|
+
def __init__(self, rev: int = 0) -> None:
|
|
269
|
+
self.rev = rev
|
|
270
|
+
self.inflight: list[TextOp] | None = None
|
|
271
|
+
self.buffer: list[TextOp] = []
|
|
272
|
+
|
|
273
|
+
def reset(self, rev: int) -> None:
|
|
274
|
+
"""Descarta o estado pendente (usado ao receber um ``sync`` completo)."""
|
|
275
|
+
self.rev = rev
|
|
276
|
+
self.inflight = None
|
|
277
|
+
self.buffer = []
|
|
278
|
+
|
|
279
|
+
@property
|
|
280
|
+
def pending(self) -> bool:
|
|
281
|
+
"""Se há edições locais ainda não confirmadas pelo servidor."""
|
|
282
|
+
return self.inflight is not None
|
|
283
|
+
|
|
284
|
+
def local(self, ops: list[TextOp]) -> tuple[int, list[TextOp]] | None:
|
|
285
|
+
"""Registra uma edição local; devolve ``(rev, ops)`` se deve enviar já."""
|
|
286
|
+
if not ops:
|
|
287
|
+
return None
|
|
288
|
+
if self.inflight is None:
|
|
289
|
+
self.inflight = list(ops)
|
|
290
|
+
return self.rev, list(ops)
|
|
291
|
+
self.buffer.extend(ops)
|
|
292
|
+
return None
|
|
293
|
+
|
|
294
|
+
def remote(self, ops: list[TextOp], rev: int) -> list[TextOp]:
|
|
295
|
+
"""Integra uma mudança do servidor; devolve o que aplicar ao editor."""
|
|
296
|
+
incoming = list(ops)
|
|
297
|
+
if self.inflight is not None:
|
|
298
|
+
self.inflight, incoming = transform(self.inflight, incoming, a_after=True)
|
|
299
|
+
if self.buffer:
|
|
300
|
+
self.buffer, incoming = transform(self.buffer, incoming, a_after=True)
|
|
301
|
+
self.rev = rev
|
|
302
|
+
return incoming
|
|
303
|
+
|
|
304
|
+
def ack(self, rev: int) -> tuple[int, list[TextOp]] | None:
|
|
305
|
+
"""Servidor aceitou a mudança em voo; devolve a próxima a enviar."""
|
|
306
|
+
self.rev = rev
|
|
307
|
+
if self.buffer:
|
|
308
|
+
self.inflight, self.buffer = self.buffer, []
|
|
309
|
+
return self.rev, list(self.inflight)
|
|
310
|
+
self.inflight = None
|
|
311
|
+
return None
|
src/collab/session.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Codis - Sessão de colaboração (lógica de sincronização, sem Tk).
|
|
2
|
+
|
|
3
|
+
Liga um :class:`~src.collab.net.CollabClient` a um editor abstrato.
|
|
4
|
+
Tudo roda na thread de interface, em :meth:`CollabSession.tick`:
|
|
5
|
+
|
|
6
|
+
1. **Captura local primeiro:** compara o texto do editor com a última versão
|
|
7
|
+
conhecida e transforma a diferença em uma mudança OT. Assim nenhuma edição
|
|
8
|
+
digitada entre dois ticks é perdida quando chega uma operação remota.
|
|
9
|
+
2. **Depois** processa os eventos do servidor em ordem: ``ack`` libera a
|
|
10
|
+
próxima mudança, ``op`` é transformada contra o que está pendente e aplicada
|
|
11
|
+
de forma incremental (cursor, seleção e rolagem do usuário são preservados),
|
|
12
|
+
``sync`` substitui o documento por completo.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import contextlib
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
from typing import Protocol
|
|
20
|
+
|
|
21
|
+
from src.collab.net import CollabClient
|
|
22
|
+
from src.collab.ot import (
|
|
23
|
+
ClientOT,
|
|
24
|
+
TextOp,
|
|
25
|
+
apply_ops,
|
|
26
|
+
diff_change,
|
|
27
|
+
ops_from_dicts,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class EditorAdapter(Protocol):
|
|
32
|
+
"""Contrato mínimo do editor sincronizado."""
|
|
33
|
+
|
|
34
|
+
def get_text(self) -> str:
|
|
35
|
+
"""Texto completo atual."""
|
|
36
|
+
|
|
37
|
+
def apply_ops(self, ops: list[TextOp]) -> None:
|
|
38
|
+
"""Aplica uma mudança de forma incremental."""
|
|
39
|
+
|
|
40
|
+
def set_text(self, text: str) -> None:
|
|
41
|
+
"""Substitui todo o texto."""
|
|
42
|
+
|
|
43
|
+
def alive(self) -> bool:
|
|
44
|
+
"""Se o editor ainda existe (aba aberta)."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class CollabSession:
|
|
48
|
+
"""Sincroniza um editor com uma sala usando OT."""
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
client: CollabClient,
|
|
53
|
+
editor: EditorAdapter,
|
|
54
|
+
on_event: Callable[[dict], None],
|
|
55
|
+
) -> None:
|
|
56
|
+
self._client = client
|
|
57
|
+
self._editor = editor
|
|
58
|
+
self._on_event = on_event
|
|
59
|
+
self._ot = ClientOT(0)
|
|
60
|
+
self._baseline = ""
|
|
61
|
+
self._synced = False
|
|
62
|
+
self.resyncs = 0
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def synced(self) -> bool:
|
|
66
|
+
"""Se o documento inicial já foi recebido."""
|
|
67
|
+
return self._synced
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def idle(self) -> bool:
|
|
71
|
+
"""Sem edições locais pendentes nem eventos na fila."""
|
|
72
|
+
return not self._ot.pending and self._client.events.empty()
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def revision(self) -> int:
|
|
76
|
+
"""Última revisão do servidor integrada."""
|
|
77
|
+
return self._ot.rev
|
|
78
|
+
|
|
79
|
+
def tick(self) -> None:
|
|
80
|
+
"""Um ciclo: captura edições locais e processa eventos do servidor."""
|
|
81
|
+
if self._synced:
|
|
82
|
+
self._capture_local()
|
|
83
|
+
for event in self._client.drain():
|
|
84
|
+
self._handle(event)
|
|
85
|
+
|
|
86
|
+
def _capture_local(self) -> None:
|
|
87
|
+
if not self._editor.alive():
|
|
88
|
+
return
|
|
89
|
+
current = self._editor.get_text()
|
|
90
|
+
if current == self._baseline:
|
|
91
|
+
return
|
|
92
|
+
ops = diff_change(self._baseline, current)
|
|
93
|
+
self._baseline = current
|
|
94
|
+
to_send = self._ot.local(ops)
|
|
95
|
+
if to_send:
|
|
96
|
+
self._send(*to_send)
|
|
97
|
+
|
|
98
|
+
def _send(self, rev: int, ops: list[TextOp]) -> None:
|
|
99
|
+
self._client.send({"type": "op", "rev": rev, "ops": [o.to_dict() for o in ops]})
|
|
100
|
+
|
|
101
|
+
def _handle(self, event: dict) -> None:
|
|
102
|
+
kind = event.get("type")
|
|
103
|
+
if kind == "sync":
|
|
104
|
+
self._on_sync(event)
|
|
105
|
+
elif kind == "op" and self._synced:
|
|
106
|
+
self._on_remote(event)
|
|
107
|
+
elif kind == "ack" and self._synced:
|
|
108
|
+
nxt = self._ot.ack(int(event.get("rev", self._ot.rev)))
|
|
109
|
+
if nxt:
|
|
110
|
+
self._send(*nxt)
|
|
111
|
+
else:
|
|
112
|
+
self._on_event(event)
|
|
113
|
+
|
|
114
|
+
def _on_sync(self, event: dict) -> None:
|
|
115
|
+
content = str(event.get("content", ""))
|
|
116
|
+
had_pending = self._ot.pending
|
|
117
|
+
self._ot.reset(int(event.get("rev", 0)))
|
|
118
|
+
if self._editor.alive() and self._editor.get_text() != content:
|
|
119
|
+
self._editor.set_text(content)
|
|
120
|
+
self._baseline = content
|
|
121
|
+
if self._synced:
|
|
122
|
+
self.resyncs += 1
|
|
123
|
+
self._synced = True
|
|
124
|
+
self._on_event({"type": "synced", "rev": self._ot.rev, "resync": had_pending})
|
|
125
|
+
|
|
126
|
+
def _on_remote(self, event: dict) -> None:
|
|
127
|
+
try:
|
|
128
|
+
ops = ops_from_dicts(event.get("ops", []))
|
|
129
|
+
except ValueError:
|
|
130
|
+
return
|
|
131
|
+
to_apply = self._ot.remote(ops, int(event.get("rev", self._ot.rev)))
|
|
132
|
+
if self._editor.alive() and to_apply:
|
|
133
|
+
self._editor.apply_ops(to_apply)
|
|
134
|
+
self._baseline = apply_ops(self._baseline, to_apply)
|
|
135
|
+
self._on_event({"type": "remote_op", "user": str(event.get("user", "?")),
|
|
136
|
+
"count": len(to_apply)})
|
|
137
|
+
|
|
138
|
+
def close(self) -> None:
|
|
139
|
+
"""Encerra a conexão."""
|
|
140
|
+
with contextlib.suppress(Exception):
|
|
141
|
+
self._client.disconnect()
|
src/collab/tk_adapter.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Codis - Adaptador entre :class:`CollabSession` e um ``tk.Text``.
|
|
2
|
+
|
|
3
|
+
Aplica mudanças remotas de forma **incremental** (insert/delete pontuais),
|
|
4
|
+
de modo que cursor, seleção, rolagem e realce do usuário local são
|
|
5
|
+
preservados, em vez de reescrever o documento inteiro a cada tecla remota.
|
|
6
|
+
|
|
7
|
+
Cuidado com emoji: dependendo do build do Tcl/Tk (``TCL_UTF_MAX``), caracteres
|
|
8
|
+
fora do BMP (U+10000+) contam como *duas* unidades de coluna (Tk 8.6) ou como
|
|
9
|
+
uma, igual ao Python (Tk 9). Por isso os índices são calculados em linha/coluna
|
|
10
|
+
a partir do texto Python, somando o excedente medido no widget.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import re
|
|
17
|
+
import tkinter as tk
|
|
18
|
+
|
|
19
|
+
from src.collab.ot import TextOp, apply_op
|
|
20
|
+
|
|
21
|
+
_ASTRAL = re.compile("[\U00010000-\U0010ffff]")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def tk_index(text: str, pos: int, astral_width: int = 2) -> str:
|
|
25
|
+
"""Índice ``linha.coluna`` do Tk para a posição ``pos`` (em code points).
|
|
26
|
+
|
|
27
|
+
``astral_width`` é quantas colunas o Tk reserva a um caractere fora do BMP.
|
|
28
|
+
"""
|
|
29
|
+
pos = max(0, min(pos, len(text)))
|
|
30
|
+
line_start = text.rfind("\n", 0, pos) + 1
|
|
31
|
+
line = text.count("\n", 0, pos) + 1
|
|
32
|
+
segment = text[line_start:pos]
|
|
33
|
+
column = len(segment) + (astral_width - 1) * len(_ASTRAL.findall(segment))
|
|
34
|
+
return f"{line}.{column}"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _astral_width(widget: tk.Text) -> int:
|
|
38
|
+
"""Colunas que o Tk deste sistema usa para um emoji (medido, não presumido)."""
|
|
39
|
+
try:
|
|
40
|
+
probe = tk.Text(widget)
|
|
41
|
+
except tk.TclError:
|
|
42
|
+
return 2
|
|
43
|
+
try:
|
|
44
|
+
probe.insert("1.0", "\U0001f600")
|
|
45
|
+
return 1 if probe.index("1.end") == "1.1" else 2
|
|
46
|
+
except tk.TclError:
|
|
47
|
+
return 2
|
|
48
|
+
finally:
|
|
49
|
+
with contextlib.suppress(tk.TclError):
|
|
50
|
+
probe.destroy()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class TkTextAdapter:
|
|
54
|
+
"""Expõe um ``tk.Text`` como editor sincronizável."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, widget: tk.Text) -> None:
|
|
57
|
+
self._w = widget
|
|
58
|
+
self._astral = _astral_width(widget)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def widget(self) -> tk.Text:
|
|
62
|
+
"""O ``tk.Text`` subjacente."""
|
|
63
|
+
return self._w
|
|
64
|
+
|
|
65
|
+
def alive(self) -> bool:
|
|
66
|
+
"""Se o widget ainda existe."""
|
|
67
|
+
try:
|
|
68
|
+
return bool(self._w.winfo_exists())
|
|
69
|
+
except tk.TclError:
|
|
70
|
+
return False
|
|
71
|
+
|
|
72
|
+
def get_text(self) -> str:
|
|
73
|
+
"""Texto completo (sem o newline final que o Tk acrescenta)."""
|
|
74
|
+
try:
|
|
75
|
+
return self._w.get("1.0", "end-1c")
|
|
76
|
+
except tk.TclError:
|
|
77
|
+
return ""
|
|
78
|
+
|
|
79
|
+
def _writable(self):
|
|
80
|
+
"""Contexto que libera temporariamente um editor somente-leitura."""
|
|
81
|
+
return _Writable(self._w)
|
|
82
|
+
|
|
83
|
+
def apply_ops(self, ops: list[TextOp]) -> None:
|
|
84
|
+
"""Aplica ``ops`` em sequência, de forma incremental."""
|
|
85
|
+
with self._writable():
|
|
86
|
+
current = self.get_text()
|
|
87
|
+
for op in ops:
|
|
88
|
+
try:
|
|
89
|
+
if op.op == "insert":
|
|
90
|
+
self._w.insert(
|
|
91
|
+
tk_index(current, op.pos, self._astral), op.text)
|
|
92
|
+
else:
|
|
93
|
+
end = min(op.pos + op.length, len(current))
|
|
94
|
+
self._w.delete(
|
|
95
|
+
tk_index(current, op.pos, self._astral),
|
|
96
|
+
tk_index(current, end, self._astral),
|
|
97
|
+
)
|
|
98
|
+
except tk.TclError:
|
|
99
|
+
return
|
|
100
|
+
current = apply_op(current, op)
|
|
101
|
+
|
|
102
|
+
def set_text(self, text: str) -> None:
|
|
103
|
+
"""Substitui o texto inteiro, tentando manter cursor e rolagem."""
|
|
104
|
+
w = self._w
|
|
105
|
+
with self._writable():
|
|
106
|
+
try:
|
|
107
|
+
insert = w.index("insert")
|
|
108
|
+
first_view = w.yview()[0]
|
|
109
|
+
w.delete("1.0", "end")
|
|
110
|
+
w.insert("1.0", text)
|
|
111
|
+
with contextlib.suppress(tk.TclError):
|
|
112
|
+
w.mark_set("insert", insert)
|
|
113
|
+
w.yview_moveto(first_view)
|
|
114
|
+
except tk.TclError:
|
|
115
|
+
return
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class _Writable:
|
|
119
|
+
"""Habilita escrita num Text desabilitado e restaura o estado depois."""
|
|
120
|
+
|
|
121
|
+
def __init__(self, widget: tk.Text) -> None:
|
|
122
|
+
self._w = widget
|
|
123
|
+
self._state = "normal"
|
|
124
|
+
|
|
125
|
+
def __enter__(self) -> None:
|
|
126
|
+
with contextlib.suppress(tk.TclError):
|
|
127
|
+
self._state = str(self._w.cget("state"))
|
|
128
|
+
if self._state != "normal":
|
|
129
|
+
self._w.configure(state="normal")
|
|
130
|
+
|
|
131
|
+
def __exit__(self, *_exc: object) -> None:
|
|
132
|
+
with contextlib.suppress(tk.TclError):
|
|
133
|
+
if self._state != "normal":
|
|
134
|
+
self._w.configure(state=self._state)
|