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.
Files changed (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
src/ui/paint_engine.py ADDED
@@ -0,0 +1,535 @@
1
+ """Motor do Paint (sem Tk): tudo aqui é testável sem interface.
2
+
3
+ Princípios de desempenho:
4
+
5
+ * **Custo proporcional ao que mudou**, nunca à imagem inteira: traços, formas e
6
+ preenchimentos trabalham numa caixa (bbox) e o histórico guarda só os blocos
7
+ (tiles) alterados.
8
+ * **Pincel por máscara**: o traço é acumulado numa máscara 'L' (máximo entre
9
+ carimbos) e composto uma vez sobre o conteúdo *original* da área - antialiasing
10
+ real, opacidade que não acumula dentro do mesmo traço e sem camadas do
11
+ tamanho da imagem por pixel interpolado.
12
+ * **Balde por spans (scanline)**: o laço Python roda por trecho horizontal, não
13
+ por pixel; a comparação de cor com tolerância é feita em C pelo Pillow.
14
+ * **Renderização por retângulo**: só o pedaço visível/sujo é reescalado
15
+ (``resize(box=...)``); o xadrez vem de um ladrilho em cache e a grade de
16
+ pixels é desenhada no próprio bitmap - sem milhares de itens de canvas.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ import random
23
+ from collections import deque
24
+ from collections.abc import Sequence
25
+ from dataclasses import dataclass, field
26
+
27
+ from PIL import Image, ImageChops, ImageDraw
28
+
29
+ Box = tuple[int, int, int, int]
30
+
31
+ TILE = 256
32
+ SUPERSAMPLE = 4
33
+ DEFAULT_HISTORY_BYTES = 384 * 1024 * 1024
34
+ MAX_HISTORY_ENTRIES = 200
35
+ GRID_MIN_ZOOM = 8.0
36
+ _BOX = getattr(Image, "BOX", 4)
37
+ _NEAREST = getattr(Image, "NEAREST", 0)
38
+ _BILINEAR = getattr(Image, "BILINEAR", 2)
39
+
40
+
41
+ def clip_box(box: Box, w: int, h: int) -> Box | None:
42
+ x0, y0, x1, y1 = max(0, box[0]), max(0, box[1]), min(w, box[2]), min(h, box[3])
43
+ return (x0, y0, x1, y1) if x1 > x0 and y1 > y0 else None
44
+
45
+
46
+ def union_box(a: Box | None, b: Box | None) -> Box | None:
47
+ if a is None:
48
+ return b
49
+ if b is None:
50
+ return a
51
+ return (min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3]))
52
+
53
+
54
+ def changed_bbox(a: Image.Image, b: Image.Image) -> Box | None:
55
+ """Caixa dos pixels que diferem em QUALQUER canal (``getbbox`` de RGBA só olha o alfa)."""
56
+ diff = ImageChops.difference(a, b)
57
+ bands = diff.split()
58
+ m = bands[0]
59
+ for band in bands[1:]:
60
+ m = ImageChops.lighter(m, band)
61
+ return m.getbbox()
62
+
63
+
64
+ def _tile_boxes(box: Box, w: int, h: int):
65
+ x0, y0, x1, y1 = box
66
+ for ty in range(y0 // TILE, (y1 - 1) // TILE + 1):
67
+ for tx in range(x0 // TILE, (x1 - 1) // TILE + 1):
68
+ yield (tx, ty), (tx * TILE, ty * TILE, min(w, (tx + 1) * TILE), min(h, (ty + 1) * TILE))
69
+
70
+
71
+ @dataclass
72
+ class _Entry:
73
+ """Uma ação desfazível: blocos antes/depois, ou imagens inteiras (mudança de tamanho)."""
74
+
75
+ tiles: dict[tuple[int, int], list] = field(default_factory=dict)
76
+ full: tuple[Image.Image, Image.Image] | None = None
77
+ bbox: Box | None = None
78
+
79
+ @property
80
+ def nbytes(self) -> int:
81
+ if self.full is not None:
82
+ return (self.full[0].width * self.full[0].height + self.full[1].width * self.full[1].height) * 4
83
+ return sum((b.width * b.height + (a.width * a.height if a is not None else 0)) * 4
84
+ for b, a in self.tiles.values())
85
+
86
+
87
+ class Document:
88
+ """Imagem RGBA + histórico por diferença + acúmulo de região suja."""
89
+
90
+ def __init__(self, image: Image.Image, history_bytes: int = DEFAULT_HISTORY_BYTES) -> None:
91
+ self.image = image if image.mode == "RGBA" else image.convert("RGBA")
92
+ self.max_history_bytes = history_bytes
93
+ self.undo_stack: deque[_Entry] = deque()
94
+ self.redo_stack: list[_Entry] = []
95
+ self._journal: dict[tuple[int, int], Image.Image] | None = None
96
+ self.dirty: Box | None = None
97
+ self.dirty_all = False
98
+ self.revision = 0
99
+ self.saved_revision = 0
100
+ self.maybe_transparent = self._has_alpha()
101
+
102
+ @property
103
+ def size(self) -> tuple[int, int]:
104
+ return self.image.size
105
+
106
+ @property
107
+ def modified(self) -> bool:
108
+ return self.revision != self.saved_revision
109
+
110
+ def mark_saved(self) -> None:
111
+ self.saved_revision = self.revision
112
+
113
+ def _has_alpha(self) -> bool:
114
+ if "A" not in self.image.getbands():
115
+ return False
116
+ return self.image.getchannel("A").getextrema()[0] < 255
117
+
118
+ @property
119
+ def history_bytes(self) -> int:
120
+ return sum(e.nbytes for e in self.undo_stack) + sum(e.nbytes for e in self.redo_stack)
121
+
122
+ def mark(self, box: Box | None) -> None:
123
+ if box is not None:
124
+ self.dirty = union_box(self.dirty, box)
125
+
126
+ def take_dirty(self) -> tuple[Box | None, bool]:
127
+ d, a = self.dirty, self.dirty_all
128
+ self.dirty, self.dirty_all = None, False
129
+ return d, a
130
+
131
+ def begin(self) -> None:
132
+ """Abre uma operação; ``touch`` registra o que será alterado."""
133
+ if self._journal is not None:
134
+ self.commit()
135
+ self._journal = {}
136
+
137
+ def touch(self, box: Box) -> Box | None:
138
+ """Guarda o conteúdo original dos blocos que ``box`` cobre (uma vez por bloco)."""
139
+ w, h = self.image.size
140
+ box = clip_box(box, w, h)
141
+ if box is None:
142
+ return None
143
+ if self._journal is None:
144
+ self._journal = {}
145
+ for key, tb in _tile_boxes(box, w, h):
146
+ if key not in self._journal:
147
+ self._journal[key] = self.image.crop(tb)
148
+ return box
149
+
150
+ def original_crop(self, box: Box) -> Image.Image:
151
+ """Pixels de ``box`` como eram quando a operação começou."""
152
+ region = self.image.crop(box)
153
+ if self._journal:
154
+ for (tx, ty), before in self._journal.items():
155
+ tb = (tx * TILE, ty * TILE, tx * TILE + before.width, ty * TILE + before.height)
156
+ ix0, iy0 = max(tb[0], box[0]), max(tb[1], box[1])
157
+ ix1, iy1 = min(tb[2], box[2]), min(tb[3], box[3])
158
+ if ix1 > ix0 and iy1 > iy0:
159
+ piece = before.crop((ix0 - tb[0], iy0 - tb[1], ix1 - tb[0], iy1 - tb[1]))
160
+ region.paste(piece, (ix0 - box[0], iy0 - box[1]))
161
+ return region
162
+
163
+ def commit(self) -> bool:
164
+ """Fecha a operação e a registra no histórico (só blocos que mudaram)."""
165
+ j, self._journal = self._journal, None
166
+ if not j:
167
+ return False
168
+ entry = _Entry()
169
+ w, h = self.image.size
170
+ for (tx, ty), before in j.items():
171
+ tb = (tx * TILE, ty * TILE, min(w, (tx + 1) * TILE), min(h, (ty + 1) * TILE))
172
+ if changed_bbox(before, self.image.crop(tb)) is None:
173
+ continue
174
+ entry.tiles[(tx, ty)] = [before, None]
175
+ entry.bbox = union_box(entry.bbox, tb)
176
+ if not entry.tiles:
177
+ return False
178
+ self._push(entry)
179
+ return True
180
+
181
+ def rollback(self) -> None:
182
+ """Descarta a operação aberta restaurando o conteúdo original."""
183
+ j, self._journal = self._journal, None
184
+ if not j:
185
+ return
186
+ for (tx, ty), before in j.items():
187
+ self.image.paste(before, (tx * TILE, ty * TILE))
188
+ self.mark((tx * TILE, ty * TILE, tx * TILE + before.width, ty * TILE + before.height))
189
+
190
+ def _push(self, entry: _Entry) -> None:
191
+ self.undo_stack.append(entry)
192
+ self.redo_stack.clear()
193
+ self.revision += 1
194
+ total = self.history_bytes
195
+ while self.undo_stack and (total > self.max_history_bytes or len(self.undo_stack) > MAX_HISTORY_ENTRIES):
196
+ total -= self.undo_stack.popleft().nbytes
197
+
198
+ def replace_image(self, new: Image.Image, record: bool = True) -> None:
199
+ """Troca a imagem inteira (abrir, redimensionar). Desfazível se ``record``."""
200
+ if self._journal is not None:
201
+ self.commit()
202
+ new = new if new.mode == "RGBA" else new.convert("RGBA")
203
+ old = self.image
204
+ self.image = new
205
+ self.dirty_all = True
206
+ self.maybe_transparent = self._has_alpha()
207
+ if record:
208
+ self._push(_Entry(full=(old, new)))
209
+ else:
210
+ self.undo_stack.clear()
211
+ self.redo_stack.clear()
212
+ self.revision = self.saved_revision = 0
213
+
214
+ def undo(self) -> bool:
215
+ if self._journal:
216
+ self.commit()
217
+ if not self.undo_stack:
218
+ return False
219
+ e = self.undo_stack.pop()
220
+ self._apply(e, undo=True)
221
+ self.redo_stack.append(e)
222
+ self.revision -= 1
223
+ return True
224
+
225
+ def redo(self) -> bool:
226
+ if not self.redo_stack:
227
+ return False
228
+ e = self.redo_stack.pop()
229
+ self._apply(e, undo=False)
230
+ self.undo_stack.append(e)
231
+ self.revision += 1
232
+ return True
233
+
234
+ def _apply(self, e: _Entry, undo: bool) -> None:
235
+ if e.full is not None:
236
+ self.image = e.full[0] if undo else e.full[1]
237
+ self.dirty_all = True
238
+ self.maybe_transparent = self.maybe_transparent or self._has_alpha()
239
+ return
240
+ for (tx, ty), pair in e.tiles.items():
241
+ before, after = pair
242
+ if undo:
243
+ pair[1] = self.image.crop((tx * TILE, ty * TILE, tx * TILE + before.width, ty * TILE + before.height))
244
+ img = before if undo else after
245
+ self.image.paste(img, (tx * TILE, ty * TILE))
246
+ self.mark((tx * TILE, ty * TILE, tx * TILE + img.width, ty * TILE + img.height))
247
+
248
+
249
+ def _opacity_lut(opacity: int) -> list[int]:
250
+ return [v * opacity // 255 for v in range(256)]
251
+
252
+
253
+ def _is_binary(patch: Image.Image) -> bool:
254
+ """True se a máscara só tem 0 e 255 (checagem barata pelo histograma)."""
255
+ hist = patch.histogram()
256
+ return hist[0] + hist[255] == patch.width * patch.height
257
+
258
+
259
+ def composite_patch(doc: Document, patch: Image.Image, box: Box, rgb: tuple[int, int, int], opacity: int = 255) -> None:
260
+ """Compõe ``rgb`` através da máscara ``patch`` (tamanho de ``box``) sobre o conteúdo ORIGINAL de ``box``."""
261
+ if opacity >= 255 and _is_binary(patch):
262
+ doc.image.paste((*rgb, 255), (box[0], box[1], box[0] + patch.width, box[1] + patch.height), patch)
263
+ doc.mark(box)
264
+ return
265
+ if opacity < 255:
266
+ patch = patch.point(_opacity_lut(opacity))
267
+ base = doc.original_crop(box)
268
+ layer = Image.new("RGBA", patch.size, (*rgb, 0))
269
+ layer.putalpha(patch)
270
+ doc.image.paste(Image.alpha_composite(base, layer), (box[0], box[1]))
271
+ doc.mark(box)
272
+
273
+
274
+ def new_stroke_mask(doc: Document) -> Image.Image:
275
+ return Image.new("L", doc.image.size, 0)
276
+
277
+
278
+ def stamp_segment(mask: Image.Image, x0: float, y0: float, x1: float, y1: float, diameter: float,
279
+ aa: bool = True) -> Box | None:
280
+ """Acumula na máscara um segmento com pontas redondas; devolve a caixa alterada."""
281
+ w, h = mask.size
282
+ pad = int(math.ceil(diameter / 2)) + 2
283
+ box = clip_box((int(min(x0, x1)) - pad, int(min(y0, y1)) - pad, int(max(x0, x1)) + pad + 1,
284
+ int(max(y0, y1)) + pad + 1), w, h)
285
+ if box is None:
286
+ return None
287
+ ss = SUPERSAMPLE if aa else 1
288
+ pw, ph = box[2] - box[0], box[3] - box[1]
289
+ patch = Image.new("L", (pw * ss, ph * ss), 0)
290
+ d = ImageDraw.Draw(patch)
291
+ p0 = ((x0 - box[0] + 0.5) * ss, (y0 - box[1] + 0.5) * ss)
292
+ p1 = ((x1 - box[0] + 0.5) * ss, (y1 - box[1] + 0.5) * ss)
293
+ rr = max(0.5, diameter * ss / 2)
294
+ if (p0 != p1):
295
+ d.line([p0, p1], fill=255, width=max(1, int(round(diameter * ss))))
296
+ for p in (p0, p1):
297
+ d.ellipse([p[0] - rr, p[1] - rr, p[0] + rr - (0 if aa else 1), p[1] + rr - (0 if aa else 1)], fill=255)
298
+ if aa:
299
+ patch = patch.resize((pw, ph), _BOX)
300
+ mask.paste(ImageChops.lighter(mask.crop(box), patch), (box[0], box[1]))
301
+ return box
302
+
303
+
304
+ def apply_stroke_region(doc: Document, mask: Image.Image, box: Box, rgb: tuple[int, int, int], opacity: int) -> None:
305
+ """Compõe a região da máscara atualizada sobre o original (chame após ``stamp_segment``)."""
306
+ doc.touch(box)
307
+ composite_patch(doc, mask.crop(box), box, rgb, opacity)
308
+
309
+
310
+ def spray(doc: Document, x0: int, y0: int, x1: int, y1: int, rgb: tuple[int, int, int], opacity: int, size: int,
311
+ density: int, rng: random.Random | None = None) -> Box | None:
312
+ """Aerógrafo: pontos aleatórios com alpha decrescente do centro para a borda (acumulativo)."""
313
+ rng = rng or random
314
+ r = max(2, size * 2)
315
+ w, h = doc.image.size
316
+ box = clip_box((min(x0, x1) - r - 1, min(y0, y1) - r - 1, max(x0, x1) + r + 2, max(y0, y1) + r + 2), w, h)
317
+ if box is None:
318
+ return None
319
+ doc.touch(box)
320
+ overlay = Image.new("RGBA", (box[2] - box[0], box[3] - box[1]), (0, 0, 0, 0))
321
+ od = ImageDraw.Draw(overlay)
322
+ dist = max(1.0, math.hypot(x1 - x0, y1 - y0))
323
+ steps = max(1, int(dist // 2) + 1)
324
+ buckets: list[list[tuple[int, int]]] = [[], [], [], []]
325
+ for i in range(steps):
326
+ t = i / steps
327
+ cx, cy = x0 + t * (x1 - x0), y0 + t * (y1 - y0)
328
+ for _ in range(density):
329
+ ang = rng.uniform(0, math.tau)
330
+ rad = r * math.sqrt(rng.random())
331
+ px, py = int(cx + rad * math.cos(ang)) - box[0], int(cy + rad * math.sin(ang)) - box[1]
332
+ buckets[min(3, int(rad / r * 4))].append((px, py))
333
+ for level, pts in enumerate(buckets):
334
+ if pts:
335
+ a = int(opacity * (1 - (level + 0.5) / 4) * 0.6)
336
+ od.point(pts, fill=(*rgb, max(1, a)))
337
+ doc.image.paste(Image.alpha_composite(doc.image.crop(box), overlay), (box[0], box[1]))
338
+ doc.mark(box)
339
+ return box
340
+
341
+
342
+ def draw_shape(doc: Document, kind: str, pts: Sequence[tuple[int, int]], rgb: tuple[int, int, int], opacity: int,
343
+ width: int, fill: bool, aa: bool = True) -> Box | None:
344
+ """Linha / retângulo / elipse / polígono com antialiasing por supersampling."""
345
+ if not pts:
346
+ return None
347
+ w, h = doc.image.size
348
+ pad = width + 3
349
+ xs, ys = [p[0] for p in pts], [p[1] for p in pts]
350
+ box = clip_box((min(xs) - pad, min(ys) - pad, max(xs) + pad + 1, max(ys) + pad + 1), w, h)
351
+ if box is None:
352
+ return None
353
+ doc.touch(box)
354
+ ss = SUPERSAMPLE if aa else 1
355
+ pw, ph = box[2] - box[0], box[3] - box[1]
356
+ patch = Image.new("L", (pw * ss, ph * ss), 0)
357
+ d = ImageDraw.Draw(patch)
358
+ sp = [((x - box[0] + 0.5) * ss, (y - box[1] + 0.5) * ss) for x, y in pts]
359
+ lw = max(1, int(round(width * ss)))
360
+ if kind == "line" and len(sp) >= 2:
361
+ d.line(sp[:2], fill=255, width=lw)
362
+ rr = lw / 2
363
+ for p in sp[:2]:
364
+ d.ellipse([p[0] - rr, p[1] - rr, p[0] + rr, p[1] + rr], fill=255)
365
+ elif kind in ("rect", "ellipse") and len(sp) >= 2:
366
+ x0, x1 = sorted((sp[0][0], sp[1][0]))
367
+ y0, y1 = sorted((sp[0][1], sp[1][1]))
368
+ fn = d.rectangle if kind == "rect" else d.ellipse
369
+ fn([x0, y0, x1, y1], outline=255, fill=255 if fill else None, width=lw)
370
+ elif kind == "polygon" and len(sp) >= 3:
371
+ if fill:
372
+ d.polygon(sp, fill=255)
373
+ d.line([*sp, sp[0]], fill=255, width=lw, joint="curve")
374
+ else:
375
+ return None
376
+ if aa:
377
+ patch = patch.resize((pw, ph), _BOX)
378
+ composite_patch(doc, patch, box, rgb, opacity)
379
+ return box
380
+
381
+
382
+ def region_mask(img: Image.Image, x: int, y: int, tol: int, contiguous: bool = True) -> tuple[Image.Image, Box] | None:
383
+ """Máscara 'L' (255 = preencher) da região de cor parecida com a do pixel (x, y).
384
+
385
+ Distância = soma das diferenças RGBA <= ``tol`` (Pillow, em C); a conectividade
386
+ (4 vizinhos) é resolvida por spans horizontais em Python.
387
+ """
388
+ w, h = img.size
389
+ if not (0 <= x < w and 0 <= y < h):
390
+ return None
391
+ seed = img.getpixel((x, y))
392
+ total = None
393
+ for band, sv in zip(img.split(), seed, strict=False):
394
+ d = band.point([abs(v - sv) for v in range(256)])
395
+ total = d if total is None else ImageChops.add(total, d)
396
+ tol = max(0, min(255, int(tol)))
397
+ near = total.point([255 if v <= tol else 0 for v in range(256)])
398
+ if not contiguous:
399
+ bb = near.getbbox()
400
+ return (near, bb) if bb else None
401
+ data = near.tobytes()
402
+ rows = [bytearray(data[i * w:(i + 1) * w]) for i in range(h)]
403
+ out = bytearray(w * h)
404
+ stack = [(x, y)]
405
+ minx, miny, maxx, maxy = w, h, -1, -1
406
+ zero = b"\x00"
407
+ while stack:
408
+ sx, sy = stack.pop()
409
+ row = rows[sy]
410
+ if not row[sx]:
411
+ continue
412
+ left = row.rfind(zero, 0, sx) + 1
413
+ right = row.find(zero, sx)
414
+ if right < 0:
415
+ right = w
416
+ row[left:right] = bytes(right - left)
417
+ base = sy * w
418
+ out[base + left:base + right] = b"\xff" * (right - left)
419
+ minx, maxx = min(minx, left), max(maxx, right)
420
+ miny, maxy = min(miny, sy), max(maxy, sy + 1)
421
+ for ny in (sy - 1, sy + 1):
422
+ if 0 <= ny < h:
423
+ nrow = rows[ny]
424
+ pos = left
425
+ while True:
426
+ pos = nrow.find(b"\xff", pos, right)
427
+ if pos < 0:
428
+ break
429
+ stack.append((pos, ny))
430
+ end = nrow.find(zero, pos, right)
431
+ if end < 0:
432
+ break
433
+ pos = end
434
+ if maxx < 0:
435
+ return None
436
+ return Image.frombytes("L", (w, h), bytes(out)), (minx, miny, maxx, maxy)
437
+
438
+
439
+ def flood_fill(doc: Document, x: int, y: int, rgb: tuple[int, int, int], opacity: int, tol: int,
440
+ contiguous: bool = True) -> Box | None:
441
+ res = region_mask(doc.image, x, y, tol, contiguous)
442
+ if res is None:
443
+ return None
444
+ mask, box = res
445
+ box = doc.touch(box)
446
+ if box is None:
447
+ return None
448
+ composite_patch(doc, mask.crop(box), box, rgb, opacity)
449
+ return box
450
+
451
+
452
+ _checker_cache: dict[tuple[int, int, int], Image.Image] = {}
453
+
454
+
455
+ def _checker(sq: int, w: int, h: int, ox: int, oy: int) -> Image.Image:
456
+ """Xadrez ancorado na origem da imagem (``ox``, ``oy``) para o retângulo w×h."""
457
+ period = sq * 2
458
+ key = (sq, w, h)
459
+ big = _checker_cache.get(key)
460
+ if big is None:
461
+ if len(_checker_cache) > 8:
462
+ _checker_cache.clear()
463
+ tile = Image.new("RGB", (period, period), (153, 153, 153))
464
+ td = ImageDraw.Draw(tile)
465
+ td.rectangle([0, 0, sq - 1, sq - 1], fill=(192, 192, 192))
466
+ td.rectangle([sq, sq, period - 1, period - 1], fill=(192, 192, 192))
467
+ big = Image.new("RGB", (w + period, h + period))
468
+ for yy in range(0, h + period, period):
469
+ for xx in range(0, w + period, period):
470
+ big.paste(tile, (xx, yy))
471
+ _checker_cache[key] = big
472
+ sx, sy = ox % period, oy % period
473
+ return big.crop((sx, sy, sx + w, sy + h))
474
+
475
+
476
+ def render_rect(img: Image.Image, zoom: float, pan: tuple[int, int], rect: Box, bg: tuple[int, int, int],
477
+ transparent: bool, grid: bool = True) -> Image.Image:
478
+ """Renderiza o retângulo de TELA ``rect`` (x0, y0, x1, y1) como RGB.
479
+
480
+ O mapeamento é contínuo (pixel k da imagem ocupa [pan + k*zoom, pan + (k+1)*zoom)),
481
+ portanto renderizar em pedaços produz exatamente o mesmo que renderizar tudo.
482
+ """
483
+ sx0, sy0, sx1, sy1 = rect
484
+ out = Image.new("RGB", (max(1, sx1 - sx0), max(1, sy1 - sy0)), bg)
485
+ iw, ih = img.size
486
+ px, py = pan
487
+ ix0, iy0 = max(sx0, math.ceil(px)), max(sy0, math.ceil(py))
488
+ ix1, iy1 = min(sx1, math.floor(px + iw * zoom)), min(sy1, math.floor(py + ih * zoom))
489
+ if ix1 <= ix0 or iy1 <= iy0:
490
+ return out
491
+ eps = 1e-4
492
+ box = ((ix0 - px) / zoom + eps, (iy0 - py) / zoom + eps,
493
+ min(iw, (ix1 - px) / zoom + eps), min(ih, (iy1 - py) / zoom + eps))
494
+ size = (ix1 - ix0, iy1 - iy0)
495
+ if zoom >= 1.0:
496
+ part = img.resize(size, _NEAREST, box=box)
497
+ else:
498
+ part = img.resize(size, _BILINEAR, box=box, reducing_gap=2.0)
499
+ dest = (ix0 - sx0, iy0 - sy0)
500
+ if transparent:
501
+ sq = max(4, min(16, int(8 * min(zoom, 2.0))))
502
+ back = _checker(sq, size[0], size[1], ix0 - px, iy0 - py)
503
+ back.paste(part, (0, 0), part)
504
+ out.paste(back, dest)
505
+ else:
506
+ out.paste(part.convert("RGB"), dest)
507
+ if grid and zoom >= GRID_MIN_ZOOM:
508
+ d = ImageDraw.Draw(out)
509
+ gx0, gx1 = math.ceil((ix0 - px) / zoom), math.floor((ix1 - px) / zoom)
510
+ gy0, gy1 = math.ceil((iy0 - py) / zoom), math.floor((iy1 - py) / zoom)
511
+ for gx in range(gx0, gx1 + 1):
512
+ x = int(round(px + gx * zoom)) - sx0
513
+ d.line([(x, dest[1]), (x, dest[1] + size[1] - 1)], fill=(96, 96, 96))
514
+ for gy in range(gy0, gy1 + 1):
515
+ y = int(round(py + gy * zoom)) - sy0
516
+ d.line([(dest[0], y), (dest[0] + size[0] - 1, y)], fill=(96, 96, 96))
517
+ return out
518
+
519
+
520
+ def image_box_to_screen(box: Box, zoom: float, pan: tuple[int, int]) -> Box:
521
+ """Caixa em pixels da imagem -> retângulo de tela (arredondado para fora)."""
522
+ return (math.floor(pan[0] + box[0] * zoom), math.floor(pan[1] + box[1] * zoom),
523
+ math.ceil(pan[0] + box[2] * zoom), math.ceil(pan[1] + box[3] * zoom))
524
+
525
+
526
+ def flatten_for_save(img: Image.Image, fmt: str) -> Image.Image:
527
+ """JPEG/BMP não têm alpha: achata sobre branco."""
528
+ fmt = fmt.upper()
529
+ if fmt in ("JPEG", "JPG", "BMP"):
530
+ bg = Image.new("RGB", img.size, (255, 255, 255))
531
+ bg.paste(img, (0, 0), img)
532
+ return bg
533
+ if fmt == "GIF":
534
+ return img.convert("P", palette=getattr(Image, "ADAPTIVE", 1))
535
+ return img