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/chat_panel.py ADDED
@@ -0,0 +1,1271 @@
1
+ """Codis - Chat ao Vivo.
2
+
3
+ Interface Tkinter sobre o núcleo ``src/chat`` (adaptadores + sessão thread-safe):
4
+ barra lateral com servidores/canais, mensagens com recuo suspenso e renderização
5
+ incremental, composer multilinha com histórico/completar, busca (Ctrl+F),
6
+ alternador rápido (Ctrl+K), lista de membros e reconexão automática.
7
+
8
+ Assinatura: ``ChatPanel(parent, tmgr, cfg)``; perfis persistidos em
9
+ ``chat_profiles.json``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+ import logging
16
+ import time
17
+ import tkinter as tk
18
+ import tkinter.font as tkfont
19
+ import webbrowser
20
+ from collections.abc import Callable
21
+ from tkinter import messagebox, ttk
22
+ from typing import Any
23
+
24
+ from src.chat.adapters import SERVER_TAB
25
+ from src.chat.models import (
26
+ CHAT_PROFILES_FILE,
27
+ PROTO_BADGE,
28
+ PROTO_LABELS,
29
+ ChatProfile,
30
+ ChatProtocol,
31
+ )
32
+ from src.chat.session import ChatSession, Msg
33
+ from src.chat.util import nick_color
34
+ from src.constants import FONT_MONO, FONT_UI
35
+ from src.i18n import _t
36
+ from src.theme.colors import mix
37
+ from src.ui._persistence_utils import load_dataclass_list, save_dataclass_list
38
+ from src.ui.chat_profile_dialog import ChatProfileDialog
39
+ from src.ui.chat_render import (
40
+ day_label,
41
+ ellipsize,
42
+ ensure_contrast,
43
+ normalize_url,
44
+ same_day,
45
+ tokenize,
46
+ )
47
+ from src.ui.grab_safe import safe_grab_set
48
+
49
+ logger = logging.getLogger("Codis.Chat")
50
+
51
+ __all__ = ["ChatPanel", "ChatProfile", "ChatProtocol", "_load_chat_profiles", "_save_chat_profiles"]
52
+
53
+ TICK_MS = 80
54
+ GROUP_GAP_S = 180
55
+ RENDER_TAIL = 400
56
+ MAX_LINES = 2500
57
+ SIDEBAR_W = 230
58
+ MEMBERS_W = 170
59
+
60
+
61
+ def _load_chat_profiles() -> list[ChatProfile]:
62
+ return load_dataclass_list(CHAT_PROFILES_FILE, ChatProfile, logger=logger)
63
+
64
+
65
+ def _save_chat_profiles(profiles: list[ChatProfile]) -> None:
66
+ save_dataclass_list(CHAT_PROFILES_FILE, profiles, chmod_600=True)
67
+
68
+
69
+ def _round_rect(cv: tk.Canvas, x1: float, y1: float, x2: float, y2: float, r: float, **kw: Any) -> int:
70
+ pts = [x1 + r, y1, x2 - r, y1, x2, y1, x2, y1 + r, x2, y2 - r, x2, y2, x2 - r, y2,
71
+ x1 + r, y2, x1, y2, x1, y2 - r, x1, y1 + r, x1, y1]
72
+ return cv.create_polygon(pts, smooth=True, **kw)
73
+
74
+
75
+ class _Row:
76
+ __slots__ = ("kind", "sname", "name", "y0", "y1", "data")
77
+
78
+ def __init__(self, kind: str, sname: str, name: str, y0: int, y1: int, data: Any = None) -> None:
79
+ self.kind, self.sname, self.name, self.y0, self.y1, self.data = kind, sname, name, y0, y1, data
80
+
81
+
82
+ class ChatPanel(tk.Frame):
83
+ """Painel de chat universal do Codis."""
84
+
85
+ def __init__(self, parent: tk.Widget, tmgr: Any, cfg: Any = None, on_unread: Callable[[int, int], None] | None = None,
86
+ session_factory: Callable[..., ChatSession] = ChatSession) -> None:
87
+ super().__init__(parent, bg=tmgr.theme.sidebar_bg)
88
+ self._tmgr = tmgr
89
+ self._cfg = cfg
90
+ self._on_unread = on_unread
91
+ self._factory = session_factory
92
+ self._profiles: list[ChatProfile] = _load_chat_profiles()
93
+ self._sessions: dict[str, ChatSession] = {}
94
+ self._cur: tuple[str, str] | None = None
95
+ self._alive = True
96
+ self._collapsed: set[str] = set()
97
+ self._rows: list[_Row] = []
98
+ self._hover: int | None = None
99
+ self._side_sig: Any = None
100
+ self._members_sig: Any = None
101
+ self._header_sig: Any = None
102
+ self._seen: dict[str, int] = {}
103
+ self._view: dict[str, Any] = {}
104
+ self._new_while_up = 0
105
+ self._show_members = True
106
+ self._show_joins = bool(self._conf("chat_show_joins", True))
107
+ self._hist: list[str] = []
108
+ self._hist_i = -1
109
+ self._comp: tuple[str, list[str], int] | None = None
110
+ self._search_hits: list[str] = []
111
+ self._search_i = -1
112
+ self._last_unread = (-1, -1)
113
+ self._binds: list[tuple[str, str]] = []
114
+ self._after_id: str | None = None
115
+ self.bind("<Destroy>", self._on_destroy)
116
+ self._build()
117
+ with contextlib.suppress(Exception):
118
+ tmgr.on_change(self._on_theme)
119
+ for p in self._profiles:
120
+ if p.auto_connect:
121
+ self._ensure_session(p)
122
+ self._after_id = self.after(TICK_MS, self._tick)
123
+
124
+ def _conf(self, key: str, default: Any) -> Any:
125
+ try:
126
+ return self._cfg.get(key, default) if self._cfg is not None else default
127
+ except Exception:
128
+ return default
129
+
130
+ def shutdown(self) -> None:
131
+ """Desconecta tudo (chamado ao fechar a janela/serviço)."""
132
+ self._alive = False
133
+ for s in list(self._sessions.values()):
134
+ with contextlib.suppress(Exception):
135
+ s.disconnect()
136
+
137
+ def _on_destroy(self, event: tk.Event) -> None:
138
+ if event.widget is not self:
139
+ return
140
+ self.shutdown()
141
+ for seq, fid in self._binds:
142
+ with contextlib.suppress(tk.TclError):
143
+ self.winfo_toplevel().unbind(seq, fid)
144
+ self._sessions.clear()
145
+
146
+ def _on_theme(self, _theme: Any) -> None:
147
+ if not self._alive:
148
+ return
149
+ with contextlib.suppress(tk.TclError):
150
+ self.after(0, self.rebuild)
151
+
152
+ def rebuild(self) -> None:
153
+ """Reconstrói a interface (troca de tema) preservando as sessões."""
154
+ if not self._alive or not self.winfo_exists():
155
+ return
156
+ for w in self.winfo_children():
157
+ w.destroy()
158
+ self.config(bg=self._tmgr.theme.sidebar_bg)
159
+ self._view, self._side_sig, self._members_sig, self._header_sig = {}, None, None, None
160
+ self._seen.clear()
161
+ self._nick_tags().clear()
162
+ self._build()
163
+
164
+ @property
165
+ def _sess(self) -> ChatSession | None:
166
+ return self._sessions.get(self._cur[0]) if self._cur else None
167
+
168
+ def unread_summary(self) -> tuple[int, int]:
169
+ u = m = 0
170
+ for s in self._sessions.values():
171
+ a, b = s.unread_totals()
172
+ u, m = u + a, m + b
173
+ return u, m
174
+
175
+ def _build(self) -> None:
176
+ t = self._tmgr.theme
177
+ self._t = t
178
+ self._fui = (FONT_UI, 10)
179
+ f = tkfont.Font(font=self._fui)
180
+ self._x1 = f.measure("00:00") + 14 + f.measure("M" * 13)
181
+ self._x2 = self._x1 + 12
182
+
183
+ side = tk.Frame(self, bg=t.sidebar_bg, width=SIDEBAR_W)
184
+ side.pack(side="left", fill="y")
185
+ side.pack_propagate(False)
186
+ hdr = tk.Frame(side, bg=t.sidebar_bg)
187
+ hdr.pack(fill="x", padx=12, pady=(12, 6))
188
+ tk.Label(hdr, text=_t("chat.title", "Chat"), bg=t.sidebar_bg, fg=t.fg, font=(FONT_UI, 13, "bold")).pack(side="left")
189
+ add = tk.Label(hdr, text="+", bg=t.sidebar_bg, fg=t.accent, font=(FONT_UI, 16, "bold"), cursor="hand2")
190
+ add.pack(side="right")
191
+ add.bind("<Button-1>", lambda _e: self._on_add())
192
+ self._side = tk.Canvas(side, bg=t.sidebar_bg, highlightthickness=0, bd=0)
193
+ self._side.pack(fill="both", expand=True)
194
+ self._side.bind("<Motion>", self._side_motion)
195
+ self._side.bind("<Leave>", lambda _e: self._side_set_hover(None))
196
+ self._side.bind("<Button-1>", self._side_click)
197
+ self._side.bind("<Button-3>", self._side_ctx)
198
+ self._side.bind("<Configure>", lambda _e: self._draw_side(force=True))
199
+ self._side.bind("<MouseWheel>", lambda e: self._side.yview_scroll(-1 if e.delta > 0 else 1, "units"))
200
+ self._side.bind("<Button-4>", lambda _e: self._side.yview_scroll(-1, "units"))
201
+ self._side.bind("<Button-5>", lambda _e: self._side.yview_scroll(1, "units"))
202
+ tk.Frame(self, bg=t.border, width=1).pack(side="left", fill="y")
203
+
204
+ main = tk.Frame(self, bg=t.editor_bg)
205
+ main.pack(side="left", fill="both", expand=True)
206
+ self._main = main
207
+ head = tk.Frame(main, bg=t.panel_bg)
208
+ head.pack(fill="x")
209
+ left = tk.Frame(head, bg=t.panel_bg)
210
+ left.pack(side="left", fill="x", expand=True, padx=14, pady=8)
211
+ self._title = tk.Label(left, text="", bg=t.panel_bg, fg=t.fg, font=(FONT_UI, 12, "bold"), anchor="w")
212
+ self._title.pack(fill="x")
213
+ self._topic = tk.Label(left, text="", bg=t.panel_bg, fg=t.fg_muted, font=(FONT_UI, 9), anchor="w")
214
+ self._topic.pack(fill="x")
215
+ right = tk.Frame(head, bg=t.panel_bg)
216
+ right.pack(side="right", padx=10)
217
+ self._status_pill = tk.Label(right, text="", bg=t.panel_bg, fg=t.fg_muted, font=(FONT_UI, 9))
218
+ self._status_pill.pack(side="left", padx=(0, 8))
219
+ self._hbtn(right, _t("chat.search", "Buscar"), self._toggle_search)
220
+ self._hbtn(right, _t("chat.members", "Membros"), self._toggle_members)
221
+ self._conn_btn = self._hbtn(right, "", self._toggle_connection)
222
+ tk.Frame(main, bg=t.border, height=1).pack(fill="x")
223
+
224
+ self._search_bar = tk.Frame(main, bg=t.panel_bg)
225
+ self._search_var = tk.StringVar()
226
+ se = tk.Entry(self._search_bar, textvariable=self._search_var, bg=t.input_bg, fg=t.fg, insertbackground=t.cursor,
227
+ relief="flat", font=self._fui, highlightthickness=1, highlightbackground=t.border,
228
+ highlightcolor=t.accent)
229
+ se.pack(side="left", fill="x", expand=True, padx=(12, 6), pady=6, ipady=3)
230
+ self._search_entry = se
231
+ self._search_count = tk.Label(self._search_bar, text="", bg=t.panel_bg, fg=t.fg_muted, font=(FONT_UI, 9))
232
+ self._search_count.pack(side="left", padx=4)
233
+ self._hbtn(self._search_bar, "\u25B2", lambda: self._search_step(-1))
234
+ self._hbtn(self._search_bar, "\u25BC", lambda: self._search_step(1))
235
+ self._hbtn(self._search_bar, "\u2715", self._toggle_search)
236
+ self._search_var.trace_add("write", lambda *_: self._search_run())
237
+ se.bind("<Return>", lambda _e: self._search_step(1) or "break")
238
+ se.bind("<Shift-Return>", lambda _e: self._search_step(-1) or "break")
239
+ se.bind("<Escape>", lambda _e: self._toggle_search())
240
+
241
+ body = tk.Frame(main, bg=t.editor_bg)
242
+ body.pack(fill="both", expand=True)
243
+ self._body = body
244
+ self._members_frame = tk.Frame(body, bg=t.sidebar_bg, width=MEMBERS_W)
245
+ self._members_title = tk.Label(self._members_frame, text="", bg=t.sidebar_bg, fg=t.fg_muted,
246
+ font=(FONT_UI, 8, "bold"), anchor="w")
247
+ self._members_title.pack(fill="x", padx=10, pady=(10, 4))
248
+ self._members = tk.Listbox(self._members_frame, bg=t.sidebar_bg, fg=t.fg, font=(FONT_UI, 10), relief="flat",
249
+ highlightthickness=0, bd=0, activestyle="none", selectbackground=t.sel_bg,
250
+ selectforeground=t.fg, exportselection=False)
251
+ self._members.pack(fill="both", expand=True, padx=(6, 0), pady=(0, 6))
252
+ self._members.bind("<Double-Button-1>", self._member_dbl)
253
+ self._members.bind("<Button-3>", self._member_ctx)
254
+ tk.Frame(body, bg=t.border, width=1).pack(side="right", fill="y")
255
+ self._members_frame.pack(side="right", fill="y")
256
+ self._msg_wrap = tk.Frame(body, bg=t.editor_bg)
257
+ self._msg_wrap.pack(side="left", fill="both", expand=True)
258
+ self._build_text(t)
259
+
260
+ tk.Frame(main, bg=t.border, height=1).pack(fill="x")
261
+ comp = tk.Frame(main, bg=t.editor_bg)
262
+ comp.pack(fill="x", padx=12, pady=10)
263
+ box = tk.Frame(comp, bg=t.input_bg, highlightthickness=1, highlightbackground=t.border, highlightcolor=t.accent)
264
+ box.pack(side="left", fill="x", expand=True)
265
+ self._box = box
266
+ self._input = tk.Text(box, height=1, wrap="word", bg=t.input_bg, fg=t.fg, insertbackground=t.cursor, relief="flat",
267
+ font=self._fui, undo=True, padx=10, pady=8, bd=0, highlightthickness=0)
268
+ self._input.pack(fill="x", expand=True)
269
+ self._ph = tk.Label(box, text="", bg=t.input_bg, fg=t.fg_muted, font=self._fui, cursor="xterm")
270
+ self._ph.place(x=11, y=8)
271
+ self._ph.bind("<Button-1>", lambda _e: self._input.focus_set())
272
+ send = tk.Label(comp, text=_t("chat.send", "Enviar"), bg=t.btn_primary, fg=t.btn_primary_fg,
273
+ font=(FONT_UI, 10, "bold"), padx=16, pady=9, cursor="hand2")
274
+ send.pack(side="left", padx=(8, 0), anchor="s")
275
+ send.bind("<Button-1>", lambda _e: self._on_send())
276
+ inp = self._input
277
+ inp.bind("<Return>", lambda _e: self._on_send() or "break")
278
+ inp.bind("<Shift-Return>", lambda _e: None)
279
+ inp.bind("<Tab>", self._on_tab)
280
+ inp.bind("<ISO_Left_Tab>", lambda _e: "break")
281
+ inp.bind("<Up>", self._hist_up)
282
+ inp.bind("<Down>", self._hist_down)
283
+ inp.bind("<KeyRelease>", self._on_input_change)
284
+ inp.bind("<<Paste>>", lambda _e: self.after(10, self._on_input_change))
285
+ inp.bind("<FocusIn>", lambda _e: self._ph.place_forget())
286
+ inp.bind("<FocusOut>", lambda _e: self._on_input_change())
287
+ self._status = tk.Label(main, text="", bg=t.panel_bg, fg=t.fg_muted, font=(FONT_UI, 8), anchor="w")
288
+ self._status.pack(fill="x", ipady=3, padx=0)
289
+ self._build_empty(t)
290
+ self._bind_keys()
291
+ self._apply_members_visibility()
292
+ self._on_input_change()
293
+ self._draw_side(force=True)
294
+
295
+ def _hbtn(self, parent: tk.Widget, text: str, cmd: Callable[[], Any]) -> tk.Label:
296
+ t = self._t
297
+ b = tk.Label(parent, text=text, bg=t.panel_bg, fg=t.fg_muted, font=(FONT_UI, 9), padx=8, pady=3, cursor="hand2")
298
+ b.pack(side="left", padx=1)
299
+ b.bind("<Button-1>", lambda _e: cmd())
300
+ b.bind("<Enter>", lambda _e: b.config(fg=t.fg, bg=t.btn_bg))
301
+ b.bind("<Leave>", lambda _e: b.config(fg=t.fg_muted, bg=t.panel_bg))
302
+ return b
303
+
304
+ def _build_text(self, t: Any) -> None:
305
+ txt = tk.Text(self._msg_wrap, bg=t.editor_bg, fg=t.fg, font=self._fui, relief="flat", bd=0, highlightthickness=0,
306
+ wrap="word", state="disabled", cursor="arrow", padx=14, pady=10, spacing1=2, spacing3=2,
307
+ insertwidth=0, takefocus=0)
308
+ sb = ttk.Scrollbar(self._msg_wrap, orient="vertical", command=txt.yview, style=self._scroll_style())
309
+ txt.configure(yscrollcommand=lambda a, b: (sb.set(a, b), self._on_scroll()))
310
+ sb.pack(side="right", fill="y")
311
+ txt.pack(side="left", fill="both", expand=True)
312
+ self._text = txt
313
+ x1, x2 = self._x1, self._x2
314
+ mut = t.fg_muted
315
+ code_bg = mix(t.editor_bg, t.fg, 0.08)
316
+ txt.tag_configure("row", lmargin1=0, lmargin2=x2, tabs=(x1, "right", x2, "left"))
317
+ txt.tag_configure("cont", lmargin1=x2, lmargin2=x2)
318
+ txt.tag_configure("ts", foreground=mut, font=(FONT_UI, 8))
319
+ txt.tag_configure("body", foreground=t.fg)
320
+ txt.tag_configure("hist", foreground=mix(t.fg, t.editor_bg, 0.35))
321
+ txt.tag_configure("nickown", foreground=t.accent, font=(FONT_UI, 10, "bold"))
322
+ txt.tag_configure("action", foreground=t.t_keyword, font=(FONT_UI, 10, "italic"))
323
+ txt.tag_configure("notice", foreground=t.warn_fg)
324
+ txt.tag_configure("sys", foreground=mut, font=(FONT_UI, 9, "italic"))
325
+ txt.tag_configure("err", foreground=t.err_fg, font=(FONT_UI, 9))
326
+ txt.tag_configure("topic", foreground=t.t_func, font=(FONT_UI, 9, "italic"))
327
+ txt.tag_configure("bold", font=(FONT_UI, 10, "bold"))
328
+ txt.tag_configure("code", font=(FONT_MONO, 10), background=code_bg)
329
+ txt.tag_configure("codeblock", font=(FONT_MONO, 10), background=code_bg, lmargin1=x2 + 8, lmargin2=x2 + 8,
330
+ spacing1=0, spacing3=0)
331
+ txt.tag_configure("url", foreground=t.t_link or t.accent, underline=True)
332
+ txt.tag_configure("mrow", background=mix(t.editor_bg, t.accent, 0.16))
333
+ txt.tag_configure("day", foreground=mut, font=(FONT_UI, 9, "bold"), justify="center", spacing1=10, spacing3=6,
334
+ lmargin1=0, lmargin2=0)
335
+ txt.tag_configure("found", background=mix(t.editor_bg, t.warn_fg, 0.35))
336
+ txt.tag_configure("foundcur", background=mix(t.editor_bg, t.warn_fg, 0.75), foreground="#000000")
337
+ txt.tag_bind("url", "<Button-1>", self._on_url_click)
338
+ txt.tag_bind("url", "<Enter>", lambda _e: txt.config(cursor="hand2"))
339
+ txt.tag_bind("url", "<Leave>", lambda _e: txt.config(cursor="arrow"))
340
+ txt.tag_bind("nickclick", "<Button-1>", self._on_nick_click)
341
+ txt.tag_raise("sel")
342
+ txt.bind("<Button-1>", lambda _e: txt.focus_set(), add="+")
343
+ txt.bind("<Button-3>", self._text_ctx)
344
+ txt.bind("<Control-c>", lambda _e: self._copy_sel())
345
+ txt.bind("<Control-a>", lambda _e: (txt.tag_add("sel", "1.0", "end"), "break")[1])
346
+ self._jump = tk.Label(self._msg_wrap, text="", bg=t.accent, fg=t.btn_primary_fg, font=(FONT_UI, 9, "bold"),
347
+ padx=12, pady=4, cursor="hand2")
348
+ self._jump.bind("<Button-1>", lambda _e: self._scroll_end())
349
+
350
+ def _scroll_style(self) -> str:
351
+ """Barra de rolagem fina, sem setas, nas cores do tema."""
352
+ t = self._t
353
+ st = ttk.Style(self)
354
+ name = "CodisChat.Vertical.TScrollbar"
355
+ with contextlib.suppress(tk.TclError):
356
+ st.layout(name, [("Vertical.Scrollbar.trough", {"sticky": "ns", "children": [
357
+ ("Vertical.Scrollbar.thumb", {"expand": "1", "sticky": "nswe"})]})])
358
+ st.configure(name, troughcolor=t.editor_bg, background=mix(t.editor_bg, t.fg, 0.2), bordercolor=t.editor_bg,
359
+ lightcolor=mix(t.editor_bg, t.fg, 0.2), darkcolor=mix(t.editor_bg, t.fg, 0.2), relief="flat", width=9, borderwidth=0)
360
+ st.map(name, background=[("active", t.accent), ("pressed", t.accent)])
361
+ return name
362
+
363
+ def _build_empty(self, t: Any) -> None:
364
+ self._empty = tk.Frame(self._msg_wrap, bg=t.editor_bg)
365
+ box = tk.Frame(self._empty, bg=t.editor_bg)
366
+ box.place(relx=0.5, rely=0.45, anchor="center")
367
+ self._empty_title = tk.Label(box, text="", bg=t.editor_bg, fg=t.fg, font=(FONT_UI, 16, "bold"))
368
+ self._empty_title.pack()
369
+ self._empty_sub = tk.Label(box, text="", bg=t.editor_bg, fg=t.fg_muted, font=(FONT_UI, 10), justify="center")
370
+ self._empty_sub.pack(pady=(6, 14))
371
+ self._empty_chips = tk.Frame(box, bg=t.editor_bg)
372
+ self._empty_chips.pack()
373
+
374
+ def _bind_keys(self) -> None:
375
+ top = self.winfo_toplevel()
376
+ for seq, fn in (("<Control-f>", lambda _e: self._toggle_search(True)),
377
+ ("<Control-k>", lambda _e: self._quick_switch()),
378
+ ("<Alt-Up>", lambda _e: self._step_channel(-1)),
379
+ ("<Alt-Down>", lambda _e: self._step_channel(1))):
380
+ with contextlib.suppress(tk.TclError):
381
+ self._binds.append((seq, top.bind(seq, fn, add="+")))
382
+
383
+ def _tick(self) -> None:
384
+ self._after_id = None
385
+ if not self._alive:
386
+ return
387
+ try:
388
+ if not self.winfo_exists():
389
+ return
390
+ self._refresh()
391
+ except tk.TclError:
392
+ return
393
+ except Exception:
394
+ logger.exception("falha ao atualizar o chat")
395
+ self._after_id = self.after(TICK_MS, self._tick)
396
+
397
+ def _refresh(self) -> None:
398
+ changed = False
399
+ cs = self._sess
400
+ if cs and self._cur and cs.active != self._cur[1] and cs.active in cs.channels:
401
+ self._select(self._cur[0], cs.active)
402
+ for n, s in self._sessions.items():
403
+ if self._seen.get(n) != s.version:
404
+ self._seen[n] = s.version
405
+ changed = True
406
+ reconnecting = any(s.status == "reconnecting" for s in self._sessions.values())
407
+ if changed or reconnecting:
408
+ self._draw_side()
409
+ self._update_view()
410
+ self._update_header()
411
+ self._update_members()
412
+ self._notify_unread()
413
+ self._update_empty()
414
+
415
+ def _notify_unread(self) -> None:
416
+ cur = self.unread_summary()
417
+ if cur != self._last_unread:
418
+ if cur[1] > self._last_unread[1] >= 0 and self.focus_displayof() is None and self._conf("chat_bell", False):
419
+ with contextlib.suppress(tk.TclError):
420
+ self.bell()
421
+ self._last_unread = cur
422
+ if self._on_unread:
423
+ with contextlib.suppress(Exception):
424
+ self._on_unread(*cur)
425
+
426
+ def _status_color(self, st: str) -> str:
427
+ t = self._t
428
+ return {"online": t.ok_fg, "connecting": t.warn_fg, "reconnecting": t.warn_fg}.get(st, t.fg_muted)
429
+
430
+ def _build_rows(self) -> list[_Row]:
431
+ rows: list[_Row] = []
432
+ y = 4
433
+ for p in self._profiles:
434
+ s = self._sessions.get(p.name)
435
+ u, m = s.unread_totals() if s else (0, 0)
436
+ collapsed = p.name in self._collapsed
437
+ rows.append(_Row("server", p.name, p.name, y, y + 38, (p, s, u, m, collapsed)))
438
+ y += 38
439
+ if s and not collapsed:
440
+ with s.lock:
441
+ chans = list(s.channels.values())
442
+ order = {"server": 0, "channel": 1, "dm": 2}
443
+ for c in sorted(chans, key=lambda c: (order.get(c.kind, 3), c.name.casefold())):
444
+ rows.append(_Row("chan", p.name, c.name, y, y + 28, (c.kind, c.unread, c.mentions, c.joined)))
445
+ y += 28
446
+ y += 6
447
+ return rows
448
+
449
+ def _draw_side(self, force: bool = False) -> None:
450
+ if not self._alive:
451
+ return
452
+ rows = self._build_rows()
453
+
454
+ def _rsig(r: _Row) -> Any:
455
+ if r.kind == "chan":
456
+ return r.data
457
+ p, sess, u, m, coll = r.data
458
+ return (p.protocol, u, m, coll, sess.status if sess else None)
459
+ sig = (tuple((r.kind, r.sname, r.name, _rsig(r)) for r in rows), self._cur, self._hover, self._side.winfo_width())
460
+ if not force and sig == self._side_sig:
461
+ return
462
+ self._side_sig = sig
463
+ self._rows = rows
464
+ cv, t = self._side, self._t
465
+ w = max(cv.winfo_width(), SIDEBAR_W)
466
+ cv.delete("all")
467
+ if not rows:
468
+ cv.create_text(w // 2, 60, text=_t("chat.no_servers", "Nenhuma conexão ainda."), fill=t.fg_muted,
469
+ font=(FONT_UI, 10))
470
+ return
471
+ for i, r in enumerate(rows):
472
+ hov = i == self._hover
473
+ if r.kind == "server":
474
+ p, s, u, m, coll = r.data
475
+ st = s.status if s else "offline"
476
+ if hov:
477
+ _round_rect(cv, 6, r.y0 + 1, w - 6, r.y1 - 1, 8, fill=mix(t.sidebar_bg, t.fg, 0.07), outline="")
478
+ code, color = PROTO_BADGE.get(p.protocol, ("?", t.accent))
479
+ _round_rect(cv, 14, r.y0 + 6, 46, r.y1 - 6, 7, fill=color, outline="")
480
+ cv.create_text(30, (r.y0 + r.y1) // 2, text=code, fill="#FFFFFF", font=(FONT_UI, 8, "bold"))
481
+ cv.create_text(56, r.y0 + 14, text=ellipsize(p.name, 20), anchor="w", fill=t.fg, font=(FONT_UI, 10, "bold"))
482
+ label = {"online": _t("chat.st_online", "online"), "connecting": _t("chat.st_connecting", "conectando…"),
483
+ "reconnecting": _t("chat.st_reconnecting", "reconectando…")}.get(st, _t("chat.st_offline", "offline"))
484
+ cv.create_oval(56, r.y0 + 25, 63, r.y0 + 32, fill=self._status_color(st), outline="")
485
+ cv.create_text(68, r.y0 + 28, text=label, anchor="w", fill=t.fg_muted, font=(FONT_UI, 8))
486
+ if m or u:
487
+ self._badge(cv, w - 34, (r.y0 + r.y1) // 2, m or u, bool(m))
488
+ cv.create_text(w - 14, (r.y0 + r.y1) // 2, text="\u25B8" if coll else "\u25BE", fill=t.fg_muted,
489
+ font=(FONT_UI, 9), anchor="e")
490
+ else:
491
+ kind, unread, mentions, joined = r.data
492
+ active = self._cur == (r.sname, r.name)
493
+ if active:
494
+ _round_rect(cv, 10, r.y0 + 1, w - 8, r.y1 - 1, 7, fill=t.sel_bg, outline="")
495
+ elif hov:
496
+ _round_rect(cv, 10, r.y0 + 1, w - 8, r.y1 - 1, 7, fill=mix(t.sidebar_bg, t.fg, 0.06), outline="")
497
+ glyph = {"server": "\u2261", "dm": "@"}.get(kind, "#")
498
+ strong = (unread or mentions) and not active
499
+ fg = t.fg if (active or strong) else (t.fg_muted if joined else mix(t.fg_muted, t.sidebar_bg, 0.4))
500
+ name = _t("chat.server_tab", "Servidor") if r.name == SERVER_TAB else r.name.lstrip("#@")
501
+ cv.create_text(30, (r.y0 + r.y1) // 2, text=glyph, fill=t.fg_muted, font=(FONT_UI, 10, "bold"))
502
+ cv.create_text(44, (r.y0 + r.y1) // 2, text=ellipsize(name, 22), anchor="w", fill=fg,
503
+ font=(FONT_UI, 10, "bold" if strong else "normal"))
504
+ if (mentions or unread) and not active:
505
+ self._badge(cv, w - 24, (r.y0 + r.y1) // 2, mentions or unread, bool(mentions))
506
+ cv.configure(scrollregion=(0, 0, w, rows[-1].y1 + 10))
507
+
508
+ def _badge(self, cv: tk.Canvas, xr: int, cy: int, n: int, hot: bool) -> None:
509
+ t = self._t
510
+ txt = str(n) if n < 100 else "99+"
511
+ w = 10 + 6 * len(txt)
512
+ _round_rect(cv, xr - w, cy - 8, xr, cy + 8, 8, fill=t.err_fg if hot else t.accent, outline="")
513
+ cv.create_text(xr - w / 2, cy, text=txt, fill="#FFFFFF", font=(FONT_UI, 8, "bold"))
514
+
515
+ def _row_at(self, y: int) -> int | None:
516
+ yy = self._side.canvasy(y)
517
+ for i, r in enumerate(self._rows):
518
+ if r.y0 <= yy < r.y1:
519
+ return i
520
+ return None
521
+
522
+ def _side_motion(self, e: tk.Event) -> None:
523
+ self._side_set_hover(self._row_at(e.y))
524
+
525
+ def _side_set_hover(self, i: int | None) -> None:
526
+ if i != self._hover:
527
+ self._hover = i
528
+ self._side.config(cursor="hand2" if i is not None else "")
529
+ self._draw_side()
530
+
531
+ def _side_click(self, e: tk.Event) -> None:
532
+ i = self._row_at(e.y)
533
+ if i is None:
534
+ return
535
+ r = self._rows[i]
536
+ if r.kind == "server":
537
+ w = self._side.winfo_width()
538
+ if e.x > w - 30:
539
+ self._collapsed ^= {r.sname}
540
+ self._draw_side(force=True)
541
+ return
542
+ self._ensure_session(r.data[0])
543
+ s = self._sessions[r.sname]
544
+ self._select(r.sname, s.active if s.active in s.channels else SERVER_TAB)
545
+ else:
546
+ self._select(r.sname, r.name)
547
+
548
+ def _side_ctx(self, e: tk.Event) -> None:
549
+ i = self._row_at(e.y)
550
+ if i is None:
551
+ return
552
+ r = self._rows[i]
553
+ m = self._menu()
554
+ if r.kind == "server":
555
+ p, s = r.data[0], r.data[1]
556
+ on = s is not None and s.status in ("online", "connecting", "reconnecting")
557
+ m.add_command(label=_t("chat.reconnect", "Reconectar") if on else _t("chat.connect_server", "Conectar"),
558
+ command=lambda: self._reconnect(p))
559
+ if on:
560
+ m.add_command(label=_t("chat.disconnect_server", "Desconectar"), command=lambda: self._disconnect(p.name))
561
+ m.add_command(label=_t("chat.join_channel", "Entrar em canal…"), command=lambda: self._join_dialog(p.name))
562
+ m.add_separator()
563
+ m.add_command(label=_t("chat.edit_server", "Editar…"), command=lambda: self._edit(p))
564
+ m.add_command(label=_t("chat.delete_server", "Remover"), command=lambda: self._delete(p.name))
565
+ else:
566
+ s = self._sessions.get(r.sname)
567
+ name = r.name
568
+ if name != SERVER_TAB:
569
+ m.add_command(label=_t("chat.part_channel", "Sair / fechar"),
570
+ command=lambda: s and s.close_channel(name))
571
+ m.add_command(label=_t("chat.clear_ch", "Limpar mensagens"), command=lambda: s and s.clear_channel(name))
572
+ m.add_command(label=_t("chat.mark_read", "Marcar como lido"), command=lambda: s and s.select(name)
573
+ if self._cur != (r.sname, name) else None)
574
+ self._popup(m, e)
575
+
576
+ def _menu(self) -> tk.Menu:
577
+ t = self._t
578
+ return tk.Menu(self, tearoff=0, bg=t.panel_bg, fg=t.fg, activebackground=t.sel_bg, activeforeground=t.fg,
579
+ bd=0, relief="flat", font=(FONT_UI, 9))
580
+
581
+ def _popup(self, m: tk.Menu, e: tk.Event) -> None:
582
+ try:
583
+ m.tk_popup(e.x_root, e.y_root)
584
+ finally:
585
+ m.grab_release()
586
+
587
+ def _on_add(self, protocol: str | None = None) -> None:
588
+ dlg = ChatProfileDialog(self, self._tmgr, taken_names={p.name for p in self._profiles}, protocol=protocol)
589
+ self.wait_window(dlg)
590
+ if dlg.result:
591
+ self._profiles.append(dlg.result)
592
+ _save_chat_profiles(self._profiles)
593
+ self._ensure_session(dlg.result)
594
+ self._select(dlg.result.name, SERVER_TAB)
595
+ self._draw_side(force=True)
596
+
597
+ def _edit(self, p: ChatProfile) -> None:
598
+ dlg = ChatProfileDialog(self, self._tmgr, profile=p, taken_names={x.name for x in self._profiles})
599
+ self.wait_window(dlg)
600
+ if not dlg.result:
601
+ return
602
+ idx = self._profiles.index(p)
603
+ if p.name in self._sessions:
604
+ self._disconnect(p.name)
605
+ self._profiles[idx] = dlg.result
606
+ _save_chat_profiles(self._profiles)
607
+ self._draw_side(force=True)
608
+ if messagebox.askyesno(_t("chat.title", "Chat"), _t("chat.reconnect_now", "Conectar com as novas configurações agora?"),
609
+ parent=self):
610
+ self._ensure_session(dlg.result)
611
+
612
+ def _ensure_session(self, p: ChatProfile) -> ChatSession:
613
+ s = self._sessions.get(p.name)
614
+ if s is None:
615
+ s = self._factory(p)
616
+ self._sessions[p.name] = s
617
+ if s.status in ("offline",) and not (s.adapter and s.adapter._thread and s.adapter._thread.is_alive()):
618
+ s.adapter = None
619
+ s.connect()
620
+ return s
621
+
622
+ def _reconnect(self, p: ChatProfile) -> None:
623
+ s = self._sessions.get(p.name)
624
+ if s is None:
625
+ self._ensure_session(p)
626
+ else:
627
+ s.reconnect()
628
+
629
+ def _disconnect(self, name: str) -> None:
630
+ s = self._sessions.pop(name, None)
631
+ if s:
632
+ s.disconnect()
633
+ if self._cur and self._cur[0] == name:
634
+ self._cur = None
635
+ self._side_sig = None
636
+ self._seen.pop(name, None)
637
+
638
+ def _delete(self, name: str) -> None:
639
+ if not messagebox.askyesno(_t("chat.title", "Chat"), _t("chat.confirm_delete", "Remover a conexão '{n}'?", n=name),
640
+ parent=self):
641
+ return
642
+ self._disconnect(name)
643
+ self._profiles = [p for p in self._profiles if p.name != name]
644
+ _save_chat_profiles(self._profiles)
645
+ self._draw_side(force=True)
646
+
647
+ def _toggle_connection(self) -> None:
648
+ if not self._cur:
649
+ return
650
+ p = next((x for x in self._profiles if x.name == self._cur[0]), None)
651
+ s = self._sess
652
+ if not p:
653
+ return
654
+ if s and s.status in ("online", "connecting", "reconnecting"):
655
+ s.disconnect()
656
+ else:
657
+ self._reconnect(p)
658
+
659
+ def _ask(self, title: str, label: str) -> str | None:
660
+ t = self._t
661
+ dlg = tk.Toplevel(self)
662
+ dlg.title(title)
663
+ dlg.configure(bg=t.panel_bg)
664
+ dlg.transient(self.winfo_toplevel())
665
+ dlg.resizable(False, False)
666
+ tk.Label(dlg, text=label, bg=t.panel_bg, fg=t.fg, font=self._fui).pack(padx=18, pady=(16, 6), anchor="w")
667
+ var = tk.StringVar()
668
+ ent = tk.Entry(dlg, textvariable=var, width=38, bg=t.input_bg, fg=t.fg, insertbackground=t.cursor, relief="flat",
669
+ font=self._fui, highlightthickness=1, highlightbackground=t.border, highlightcolor=t.accent)
670
+ ent.pack(padx=18, ipady=5)
671
+ out: list[str | None] = [None]
672
+
673
+ def ok(_e: Any = None) -> None:
674
+ out[0] = var.get().strip() or None
675
+ dlg.destroy()
676
+ ent.bind("<Return>", ok)
677
+ dlg.bind("<Escape>", lambda _e: dlg.destroy())
678
+ bar = tk.Frame(dlg, bg=t.panel_bg)
679
+ bar.pack(fill="x", padx=18, pady=14)
680
+ b = tk.Label(bar, text="OK", bg=t.btn_primary, fg=t.btn_primary_fg, font=(FONT_UI, 10, "bold"), padx=18, pady=5,
681
+ cursor="hand2")
682
+ b.pack(side="right")
683
+ b.bind("<Button-1>", ok)
684
+ dlg.update_idletasks()
685
+ top = self.winfo_toplevel()
686
+ dlg.geometry(f"+{top.winfo_rootx() + (top.winfo_width() - dlg.winfo_reqwidth()) // 2}+{top.winfo_rooty() + 120}")
687
+ safe_grab_set(dlg)
688
+ ent.focus_set()
689
+ self.wait_window(dlg)
690
+ return out[0]
691
+
692
+ def _join_dialog(self, sname: str | None = None) -> None:
693
+ sname = sname or (self._cur[0] if self._cur else None)
694
+ s = self._sessions.get(sname or "")
695
+ if not s:
696
+ return
697
+ proto = s.profile.protocol
698
+ hint = {"irc": "#canal", "ircs": "#canal", "xmpp": "sala@conference.servidor", "xmpps": "sala@conference.servidor",
699
+ "matrix": "#alias:servidor ou !id", "mqtt": "topico/exemplo"}.get(proto, "canal")
700
+ name = self._ask(_t("chat.join_title", "Entrar em canal"), f"Canal ({hint}):")
701
+ if name:
702
+ s.join_channel(name)
703
+
704
+ def _select(self, sname: str, ch: str) -> None:
705
+ s = self._sessions.get(sname)
706
+ if not s:
707
+ return
708
+ self._cur = (sname, ch)
709
+ s.select(ch)
710
+ self._view = {}
711
+ self._header_sig = self._members_sig = None
712
+ self._side_sig = None
713
+ self._update_view()
714
+ self._update_header()
715
+ self._update_members()
716
+ self._draw_side(force=True)
717
+ self._on_input_change()
718
+ if self._search_bar.winfo_ismapped():
719
+ self._search_run()
720
+ self._input.focus_set()
721
+
722
+ def _all_targets(self) -> list[tuple[str, str]]:
723
+ out = []
724
+ for p in self._profiles:
725
+ s = self._sessions.get(p.name)
726
+ if not s:
727
+ continue
728
+ with s.lock:
729
+ out.append((p.name, SERVER_TAB))
730
+ out.extend((p.name, c.name) for c in sorted(s.channels.values(), key=lambda c: c.name.casefold())
731
+ if c.kind != "server")
732
+ return out
733
+
734
+ def _step_channel(self, d: int) -> str:
735
+ targets = self._all_targets()
736
+ if targets:
737
+ i = targets.index(self._cur) if self._cur in targets else -1
738
+ self._select(*targets[(i + d) % len(targets)])
739
+ return "break"
740
+
741
+ def _quick_switch(self) -> str:
742
+ targets = self._all_targets()
743
+ if not targets:
744
+ return "break"
745
+ t = self._t
746
+ dlg = tk.Toplevel(self)
747
+ dlg.overrideredirect(True)
748
+ dlg.configure(bg=t.border)
749
+ inner = tk.Frame(dlg, bg=t.panel_bg)
750
+ inner.pack(padx=1, pady=1)
751
+ var = tk.StringVar()
752
+ ent = tk.Entry(inner, textvariable=var, width=44, bg=t.input_bg, fg=t.fg, insertbackground=t.cursor, relief="flat",
753
+ font=(FONT_UI, 11))
754
+ ent.pack(fill="x", padx=10, pady=10, ipady=5)
755
+ lb = tk.Listbox(inner, height=9, bg=t.panel_bg, fg=t.fg, relief="flat", highlightthickness=0, activestyle="none",
756
+ selectbackground=t.sel_bg, selectforeground=t.fg, font=(FONT_UI, 10))
757
+ lb.pack(fill="both", padx=10, pady=(0, 10))
758
+ shown: list[tuple[str, str]] = []
759
+
760
+ def fill(*_a: Any) -> None:
761
+ q = var.get().casefold()
762
+ lb.delete(0, "end")
763
+ shown.clear()
764
+ for sn, ch in targets:
765
+ label = f"{ch if ch != SERVER_TAB else 'Servidor'} · {sn}"
766
+ if q in label.casefold():
767
+ shown.append((sn, ch))
768
+ lb.insert("end", label)
769
+ if shown:
770
+ lb.selection_set(0)
771
+
772
+ def go(_e: Any = None) -> str:
773
+ sel = lb.curselection()
774
+ dlg.destroy()
775
+ if sel:
776
+ self._select(*shown[sel[0]])
777
+ return "break"
778
+
779
+ def move(d: int) -> str:
780
+ sel = lb.curselection()
781
+ i = max(0, min(len(shown) - 1, (sel[0] if sel else -1) + d))
782
+ lb.selection_clear(0, "end")
783
+ lb.selection_set(i)
784
+ lb.see(i)
785
+ return "break"
786
+ var.trace_add("write", fill)
787
+ ent.bind("<Return>", go)
788
+ ent.bind("<Down>", lambda _e: move(1))
789
+ ent.bind("<Up>", lambda _e: move(-1))
790
+ ent.bind("<Escape>", lambda _e: dlg.destroy())
791
+ ent.bind("<FocusOut>", lambda _e: self.after(120, lambda: dlg.winfo_exists() and dlg.destroy()))
792
+ lb.bind("<Double-Button-1>", go)
793
+ fill()
794
+ dlg.update_idletasks()
795
+ top = self.winfo_toplevel()
796
+ dlg.geometry(f"+{top.winfo_rootx() + (top.winfo_width() - dlg.winfo_reqwidth()) // 2}+{top.winfo_rooty() + 90}")
797
+ ent.focus_force()
798
+ return "break"
799
+
800
+ def _update_header(self) -> None:
801
+ s = self._sess
802
+ sig = (self._cur, s.status if s else None, int(s.retry_at) if s and s.status == "reconnecting" else 0,
803
+ s.channels[self._cur[1]].topic if s and self._cur and self._cur[1] in s.channels else "",
804
+ s.status_detail if s else "")
805
+ if sig == self._header_sig:
806
+ return
807
+ self._header_sig = sig
808
+ if not s or not self._cur:
809
+ self._title.config(text=_t("chat.title", "Chat"))
810
+ self._topic.config(text="")
811
+ self._status_pill.config(text="")
812
+ self._conn_btn.config(text="")
813
+ return
814
+ sname, ch = self._cur
815
+ c = s.channels.get(ch)
816
+ self._title.config(text=(s.profile.name if ch == SERVER_TAB else ch))
817
+ topic = (c.topic if c else "") or (f"{PROTO_LABELS.get(s.profile.protocol, s.profile.protocol)} · "
818
+ f"{s.profile.host or s.profile.protocol}" if ch == SERVER_TAB else "")
819
+ self._topic.config(text=ellipsize(topic.replace("\n", " "), 160))
820
+ st = s.status
821
+ txt = {"online": _t("chat.online_long", "Conectado"), "connecting": _t("chat.connecting_long", "Conectando…"),
822
+ "offline": _t("chat.offline_long", "Desconectado")}.get(st, "")
823
+ if st == "reconnecting":
824
+ txt = _t("chat.reconnecting_in", "Reconectando em {n}s…", n=max(0, int(s.retry_at - time.time() + 0.5)))
825
+ dot = "\u25CF "
826
+ self._status_pill.config(text=dot + txt, fg=self._status_color(st))
827
+ self._conn_btn.config(text=_t("chat.disconnect_short", "Desconectar") if st != "offline"
828
+ else _t("chat.connect_short", "Conectar"))
829
+ self._status.config(text=f" {s.nick} · {s.profile.name}" + (f" · {s.status_detail}" if st != "online" and s.status_detail else ""))
830
+
831
+ def _flash(self, msg: str) -> None:
832
+ self._status.config(text=" " + msg)
833
+
834
+ def _update_empty(self) -> None:
835
+ need = None
836
+ if not self._profiles:
837
+ need = ("no_profiles", _t("chat.empty_title", "Converse sem sair do editor"),
838
+ _t("chat.empty_sub", "Conecte-se a IRC, Matrix, Discord, Slack, Telegram, XMPP, MQTT e mais.\nEscolha um serviço:"),
839
+ ["irc", "matrix", "discord", "slack", "telegram", "xmpp", "mattermost", "codis"])
840
+ elif not self._cur or not self._sess:
841
+ need = ("no_sel", _t("chat.pick_title", "Selecione uma conversa"),
842
+ _t("chat.pick_sub", "Clique em uma conexão na barra lateral para conectar.\nCtrl+K abre o alternador rápido."), [])
843
+ if need is None:
844
+ if self._empty.winfo_ismapped():
845
+ self._empty.place_forget()
846
+ return
847
+ if getattr(self, "_empty_key", None) != need[0]:
848
+ self._empty_key = need[0]
849
+ self._empty_title.config(text=need[1])
850
+ self._empty_sub.config(text=need[2])
851
+ for w in self._empty_chips.winfo_children():
852
+ w.destroy()
853
+ for pr in need[3]:
854
+ code, color = PROTO_BADGE[pr]
855
+ lb = tk.Label(self._empty_chips, text=PROTO_LABELS[pr].split(" (")[0], bg=color, fg="#FFFFFF",
856
+ font=(FONT_UI, 9, "bold"), padx=11, pady=5, cursor="hand2")
857
+ lb.pack(side="left", padx=3, pady=3)
858
+ lb.bind("<Button-1>", lambda _e, p=pr: self._on_add(p))
859
+ self._empty.place(relx=0, rely=0, relwidth=1, relheight=1)
860
+ self._empty.lift()
861
+
862
+ def _at_bottom(self) -> bool:
863
+ return self._text.yview()[1] >= 0.995
864
+
865
+ def _on_scroll(self) -> None:
866
+ if self._new_while_up and self._at_bottom():
867
+ self._new_while_up = 0
868
+ self._jump.place_forget()
869
+
870
+ def _scroll_end(self) -> None:
871
+ self._text.see("end")
872
+ self._new_while_up = 0
873
+ self._jump.place_forget()
874
+
875
+ def _update_view(self) -> None:
876
+ s = self._sess
877
+ if not s or not self._cur or self._cur[1] not in s.channels:
878
+ if self._view:
879
+ self._clear_text()
880
+ self._view = {}
881
+ return
882
+ key = self._cur
883
+ ch = s.channels[key[1]]
884
+ v = self._view
885
+ if v.get("key") != key or v.get("joins") != self._show_joins or ch.base > v.get("upto", 0):
886
+ self._clear_text()
887
+ start_abs = max(ch.base, ch.total - RENDER_TAIL)
888
+ self._view = v = {"key": key, "upto": start_abs, "last_nick": None, "last_ts": None, "last_hist": None,
889
+ "joins": self._show_joins}
890
+ reset = True
891
+ else:
892
+ reset = False
893
+ base, msgs = s.snapshot(key[1], v["upto"])
894
+ if not msgs:
895
+ return
896
+ self._append(msgs, reset)
897
+ v["upto"] = base + len(msgs)
898
+
899
+ def _clear_text(self) -> None:
900
+ self._text.config(state="normal")
901
+ self._text.delete("1.0", "end")
902
+ self._text.config(state="disabled")
903
+ self._new_while_up = 0
904
+ self._jump.place_forget()
905
+
906
+ def _append(self, msgs: list[Msg], reset: bool) -> None:
907
+ txt, v = self._text, self._view
908
+ stick = reset or self._at_bottom()
909
+ added = 0
910
+ txt.config(state="normal")
911
+ for m in msgs:
912
+ if m.kind in ("join", "part", "nick") and not self._show_joins:
913
+ continue
914
+ if v["last_ts"] is None or not same_day(v["last_ts"], m.ts):
915
+ txt.insert("end", day_label(m.ts) + "\n", ("day",))
916
+ v["last_nick"] = None
917
+ if v["last_hist"] and not m.history:
918
+ txt.insert("end", "\u2014 " + _t("chat.new_msgs", "novas mensagens") + " \u2014\n", ("day",))
919
+ v["last_hist"] = m.history
920
+ self._insert_one(m, v)
921
+ v["last_ts"] = m.ts
922
+ added += 1
923
+ lines = int(txt.index("end-1c").split(".")[0])
924
+ if lines > MAX_LINES:
925
+ txt.delete("1.0", f"{lines - MAX_LINES + 300}.0")
926
+ txt.config(state="disabled")
927
+ if stick:
928
+ txt.see("end")
929
+ elif added:
930
+ self._new_while_up += sum(1 for m in msgs if m.kind in ("msg", "action", "notice"))
931
+ if self._new_while_up:
932
+ self._jump.config(text=f"\u2193 {self._new_while_up} " + _t("chat.new_short", "novas"))
933
+ self._jump.place(relx=0.5, rely=1.0, y=-14, anchor="s")
934
+
935
+ def _insert_one(self, m: Msg, v: dict) -> None:
936
+ txt = self._text
937
+ ts = time.strftime("%H:%M", time.localtime(m.ts))
938
+ extra = ("mrow",) if m.mention else ()
939
+ hist = ("hist",) if m.history else ()
940
+ start = txt.index("end-1c")
941
+ if m.kind in ("sys", "err", "join", "part", "nick", "topic"):
942
+ sym = {"join": "\u2192", "part": "\u2190", "err": "!", "nick": "~", "topic": "#"}.get(m.kind, "\u2022")
943
+ who = f"{m.nick} " if m.nick and m.kind != "topic" else ""
944
+ txt.insert("end", ts, ("ts", "row", *extra))
945
+ txt.insert("end", f"\t{sym}\t", ("ts", "row"))
946
+ txt.insert("end", f"{who}{m.text}\n", (m.kind if m.kind in ("err", "topic") else "sys", "row"))
947
+ v["last_nick"] = None
948
+ else:
949
+ own = m.kind == "own"
950
+ group = (v["last_nick"] == (m.nick, own) and v["last_ts"] is not None and m.ts - v["last_ts"] < GROUP_GAP_S
951
+ and m.kind in ("msg", "own"))
952
+ row = ("row", *extra)
953
+ if group:
954
+ txt.insert("end", "\t\t", row)
955
+ else:
956
+ txt.insert("end", ts, ("ts", *row))
957
+ shown = "*" if m.kind == "action" else ellipsize(m.nick, 14)
958
+ ntags = ("nickown",) if own else (f"nk_{m.nick}",)
959
+ if not own:
960
+ if m.nick not in self._nick_tags():
961
+ self._text.tag_configure(f"nk_{m.nick}", foreground=self._nick_fg(m.nick), font=(FONT_UI, 10, "bold"))
962
+ self._nick_tags().add(m.nick)
963
+ ntags = (f"nk_{m.nick}", "nickclick")
964
+ if m.kind == "action":
965
+ ntags = ("action",)
966
+ txt.insert("end", "\t", row)
967
+ txt.insert("end", shown, (*ntags, *row))
968
+ txt.insert("end", "\t", row)
969
+ base = ("body", *hist, *row)
970
+ if m.kind == "action":
971
+ base = ("action", *row)
972
+ elif m.kind == "notice":
973
+ base = ("notice", *row)
974
+ body = f"{m.nick} {m.text}" if m.kind == "action" else m.text
975
+ for seg, tags in tokenize(body):
976
+ txt.insert("end", seg, (*base, *tags))
977
+ txt.insert("end", "\n", base)
978
+ v["last_nick"] = (m.nick, own) if m.kind in ("msg", "own") else None
979
+ l0, l1 = int(start.split(".")[0]), int(txt.index("end-1c").split(".")[0])
980
+ for ln in range(l0 + 1, l1):
981
+ txt.tag_add("cont", f"{ln}.0", f"{ln}.end+1c")
982
+ txt.tag_raise("cont", "row")
983
+ txt.tag_raise("codeblock")
984
+ txt.tag_raise("mrow", "row")
985
+ txt.tag_raise("found")
986
+ txt.tag_raise("foundcur")
987
+ txt.tag_raise("sel")
988
+
989
+ def _nick_fg(self, nick: str, bg: str | None = None) -> str:
990
+ return ensure_contrast(nick_color(nick), bg or self._t.editor_bg)
991
+
992
+ def _nick_tags(self) -> set[str]:
993
+ if not hasattr(self, "_nk"):
994
+ self._nk: set[str] = set()
995
+ return self._nk
996
+
997
+ def _on_url_click(self, e: tk.Event) -> None:
998
+ txt = self._text
999
+ rng = txt.tag_prevrange("url", f"@{e.x},{e.y}+1c")
1000
+ if not rng:
1001
+ return
1002
+ url = normalize_url(txt.get(*rng))
1003
+ if url:
1004
+ with contextlib.suppress(Exception):
1005
+ webbrowser.open(url)
1006
+
1007
+ def _on_nick_click(self, e: tk.Event) -> None:
1008
+ txt = self._text
1009
+ idx = txt.index(f"@{e.x},{e.y}")
1010
+ names = [t for t in txt.tag_names(idx) if t.startswith("nk_")]
1011
+ if names:
1012
+ self._insert_mention(names[0][3:])
1013
+
1014
+ def _insert_mention(self, nick: str) -> None:
1015
+ cur = self._input.get("1.0", "end-1c")
1016
+ self._input.insert("end", f"{nick}: " if not cur.strip() else f"{nick} ")
1017
+ self._input.focus_set()
1018
+ self._on_input_change()
1019
+
1020
+ def _copy_sel(self) -> str:
1021
+ with contextlib.suppress(tk.TclError):
1022
+ data = self._text.get("sel.first", "sel.last")
1023
+ self.clipboard_clear()
1024
+ self.clipboard_append(data)
1025
+ return "break"
1026
+
1027
+ def _text_ctx(self, e: tk.Event) -> None:
1028
+ m = self._menu()
1029
+ m.add_command(label=_t("chat.copy", "Copiar"), command=self._copy_sel)
1030
+ m.add_checkbutton(label=_t("chat.show_joins", "Mostrar entradas e saídas"), onvalue=True, offvalue=False,
1031
+ variable=tk.BooleanVar(value=self._show_joins), command=self._toggle_joins)
1032
+ m.add_command(label=_t("chat.clear_ch", "Limpar mensagens"),
1033
+ command=lambda: self._sess and self._cur and self._sess.clear_channel(self._cur[1]))
1034
+ self._popup(m, e)
1035
+
1036
+ def _toggle_joins(self) -> None:
1037
+ self._show_joins = not self._show_joins
1038
+ with contextlib.suppress(Exception):
1039
+ if self._cfg is not None:
1040
+ self._cfg.set("chat_show_joins", self._show_joins)
1041
+ self._update_view()
1042
+
1043
+ def _toggle_search(self, force_open: bool = False) -> str:
1044
+ if self._search_bar.winfo_ismapped() and not force_open:
1045
+ self._search_bar.pack_forget()
1046
+ self._text.tag_remove("found", "1.0", "end")
1047
+ self._text.tag_remove("foundcur", "1.0", "end")
1048
+ self._input.focus_set()
1049
+ else:
1050
+ self._search_bar.pack(fill="x", before=self._body)
1051
+ self._search_entry.focus_set()
1052
+ self._search_entry.select_range(0, "end")
1053
+ self._search_run()
1054
+ return "break"
1055
+
1056
+ def _search_run(self) -> None:
1057
+ txt = self._text
1058
+ txt.tag_remove("found", "1.0", "end")
1059
+ txt.tag_remove("foundcur", "1.0", "end")
1060
+ self._search_hits = []
1061
+ q = self._search_var.get()
1062
+ if not q:
1063
+ self._search_count.config(text="")
1064
+ return
1065
+ idx = "1.0"
1066
+ while len(self._search_hits) < 1000:
1067
+ pos = txt.search(q, idx, "end", nocase=True)
1068
+ if not pos:
1069
+ break
1070
+ end = f"{pos}+{len(q)}c"
1071
+ txt.tag_add("found", pos, end)
1072
+ self._search_hits.append(pos)
1073
+ idx = end
1074
+ self._search_i = len(self._search_hits)
1075
+ self._search_step(-1)
1076
+
1077
+ def _search_step(self, d: int) -> None:
1078
+ n = len(self._search_hits)
1079
+ if not n:
1080
+ self._search_count.config(text=_t("chat.no_results", "0 resultados") if self._search_var.get() else "")
1081
+ return
1082
+ self._search_i = (self._search_i + d) % n
1083
+ txt, q = self._text, self._search_var.get()
1084
+ txt.tag_remove("foundcur", "1.0", "end")
1085
+ pos = self._search_hits[self._search_i]
1086
+ txt.tag_add("foundcur", pos, f"{pos}+{len(q)}c")
1087
+ txt.see(pos)
1088
+ self._search_count.config(text=f"{self._search_i + 1}/{n}")
1089
+
1090
+ def _toggle_members(self) -> None:
1091
+ self._show_members = not self._show_members
1092
+ self._apply_members_visibility()
1093
+
1094
+ def _apply_members_visibility(self) -> None:
1095
+ if self._show_members:
1096
+ self._members_frame.pack(side="right", fill="y")
1097
+ else:
1098
+ self._members_frame.pack_forget()
1099
+
1100
+ def _update_members(self) -> None:
1101
+ s = self._sess
1102
+ if not s or not self._cur:
1103
+ return
1104
+ ch = s.channels.get(self._cur[1])
1105
+ items = s.members(self._cur[1]) if ch and ch.kind == "channel" else []
1106
+ if items == self._members_sig:
1107
+ return
1108
+ self._members_sig = items
1109
+ self._members.delete(0, "end")
1110
+ for i, (nick, pfx) in enumerate(items):
1111
+ mark = {"@": "\u25CF ", "~": "\u25CF ", "&": "\u25CF ", "%": "\u25CF ", "+": "\u25CB "}.get(pfx[:1], " ")
1112
+ self._members.insert("end", f"{mark}{nick}")
1113
+ self._members.itemconfig(i, fg=self._nick_fg(nick, self._t.sidebar_bg))
1114
+ self._members_title.config(text=(_t("chat.members_n", "MEMBROS - {n}", n=len(items)) if items else
1115
+ _t("chat.members_u", "MEMBROS")))
1116
+
1117
+ def _member_nick(self) -> str | None:
1118
+ sel = self._members.curselection()
1119
+ return self._members.get(sel[0]).strip().lstrip("\u25CF\u25CB ").strip() if sel else None
1120
+
1121
+ def _member_dbl(self, _e: tk.Event) -> None:
1122
+ nick = self._member_nick()
1123
+ if nick:
1124
+ self._insert_mention(nick)
1125
+
1126
+ def _member_ctx(self, e: tk.Event) -> None:
1127
+ i = self._members.nearest(e.y)
1128
+ self._members.selection_clear(0, "end")
1129
+ self._members.selection_set(i)
1130
+ nick = self._member_nick()
1131
+ s = self._sess
1132
+ if not nick or not s:
1133
+ return
1134
+ m = self._menu()
1135
+ m.add_command(label=_t("chat.mention", "Mencionar"), command=lambda: self._insert_mention(nick))
1136
+ if s.profile.protocol in ("irc", "ircs"):
1137
+ m.add_command(label=_t("chat.private", "Conversa privada"), command=lambda: self._select_query(nick))
1138
+ m.add_command(label="Whois", command=lambda: s.send(f"/whois {nick}"))
1139
+ m.add_command(label=_t("chat.ignore", "Ignorar"), command=lambda: s.send(f"/ignore {nick}"))
1140
+ m.add_command(label=_t("chat.copy_nick", "Copiar nick"),
1141
+ command=lambda: (self.clipboard_clear(), self.clipboard_append(nick)))
1142
+ self._popup(m, e)
1143
+
1144
+ def _select_query(self, nick: str) -> None:
1145
+ s = self._sess
1146
+ if s and self._cur:
1147
+ s.open_query(nick)
1148
+ self._select(self._cur[0], nick)
1149
+
1150
+ def _on_input_change(self, _e: tk.Event | None = None) -> None:
1151
+ txt = self._input
1152
+ empty = not txt.get("1.0", "end-1c")
1153
+ if empty and self.focus_get() is not txt:
1154
+ s = self._sess
1155
+ ch = self._cur[1] if self._cur else ""
1156
+ hint = (_t("chat.ph_channel", "Mensagem para {c} · / para comandos", c=ch if ch != SERVER_TAB else "…")
1157
+ if s and ch and ch != SERVER_TAB else _t("chat.ph_server", "Digite /help ou /join #canal"))
1158
+ self._ph.config(text=hint)
1159
+ self._ph.place(x=11, y=8)
1160
+ else:
1161
+ self._ph.place_forget()
1162
+ try:
1163
+ lines = txt.count("1.0", "end-1c", "displaylines")
1164
+ n = max(1, min(6, (lines[0] if lines else 0) + 1))
1165
+ except tk.TclError:
1166
+ n = 1
1167
+ if int(txt.cget("height")) != n:
1168
+ txt.config(height=n)
1169
+ val = txt.get("1.0", "end-1c")
1170
+ s = self._sess
1171
+ if val.startswith("/") and " " not in val and "\n" not in val and s:
1172
+ cmds = self._commands(s)
1173
+ m = [c for c in cmds if c.startswith(val[1:].lower())]
1174
+ if m and val != "/":
1175
+ self._flash(" ".join("/" + c for c in m[:12]))
1176
+ elif val == "/":
1177
+ self._flash(" ".join("/" + c for c in cmds[:14]) + " …")
1178
+
1179
+ def _commands(self, s: ChatSession) -> list[str]:
1180
+ base = ["help", "join", "part", "close", "query", "me", "clear", "ignore", "unignore", "reconnect",
1181
+ "disconnect", "clearhistory"]
1182
+ extra = s.adapter.commands() if s.adapter else []
1183
+ return sorted(set(base) | set(extra))
1184
+
1185
+ def _on_send(self) -> str:
1186
+ s = self._sess
1187
+ txt = self._input.get("1.0", "end-1c").rstrip()
1188
+ if not txt:
1189
+ return "break"
1190
+ if not s:
1191
+ self._flash(_t("chat.not_connected", "Selecione uma conexão primeiro."))
1192
+ return "break"
1193
+ n = txt.count("\n") + 1
1194
+ if n > 5 and not messagebox.askyesno(_t("chat.title", "Chat"),
1195
+ _t("chat.multi_confirm", "Enviar {n} linhas de uma vez?", n=n), parent=self):
1196
+ return "break"
1197
+ self._hist.append(txt)
1198
+ self._hist = self._hist[-100:]
1199
+ self._hist_i = -1
1200
+ self._input.delete("1.0", "end")
1201
+ self._comp = None
1202
+ ok = s.send(txt)
1203
+ if not ok and not txt.startswith("/"):
1204
+ pass
1205
+ self._update_view()
1206
+ self._scroll_end()
1207
+ self._on_input_change()
1208
+ return "break"
1209
+
1210
+ def _hist_up(self, _e: tk.Event) -> str | None:
1211
+ if self._input.compare("insert", ">", "1.end") and self._input.get("1.0", "end-1c"):
1212
+ return None
1213
+ if not self._hist:
1214
+ return "break"
1215
+ self._hist_i = len(self._hist) - 1 if self._hist_i < 0 else max(0, self._hist_i - 1)
1216
+ self._set_input(self._hist[self._hist_i])
1217
+ return "break"
1218
+
1219
+ def _hist_down(self, _e: tk.Event) -> str | None:
1220
+ if self._hist_i < 0:
1221
+ return None
1222
+ self._hist_i += 1
1223
+ self._set_input("" if self._hist_i >= len(self._hist) else self._hist[self._hist_i])
1224
+ if self._hist_i >= len(self._hist):
1225
+ self._hist_i = -1
1226
+ return "break"
1227
+
1228
+ def _set_input(self, text: str) -> None:
1229
+ self._input.delete("1.0", "end")
1230
+ self._input.insert("1.0", text)
1231
+ self._on_input_change()
1232
+
1233
+ def _on_tab(self, _e: tk.Event) -> str:
1234
+ s = self._sess
1235
+ if not s or not self._cur:
1236
+ return "break"
1237
+ text = self._input.get("1.0", "insert")
1238
+ if self._comp and text.endswith(self._comp[0] + self._comp[1][self._comp[2]] + self._comp_suffix):
1239
+ base, cands, i = self._comp
1240
+ i = (i + 1) % len(cands)
1241
+ cur = cands[self._comp[2]] + self._comp_suffix
1242
+ self._input.delete(f"insert-{len(cur)}c", "insert")
1243
+ else:
1244
+ word = text.split(" ")[-1].split("\n")[-1]
1245
+ at = word.startswith("@")
1246
+ prefix = word.lstrip("@")
1247
+ if text.startswith("/") and " " not in text:
1248
+ cands = ["/" + c for c in self._commands(s) if c.startswith(text[1:].lower())]
1249
+ prefix, base, self._comp_suffix = text, "", " "
1250
+ if not cands:
1251
+ return "break"
1252
+ self._input.delete("1.0", "insert")
1253
+ self._comp = ("", cands, 0)
1254
+ self._input.insert("1.0", cands[0] + " ")
1255
+ return "break"
1256
+ nicks = [n for n, _ in s.members(self._cur[1])]
1257
+ cands = [n for n in nicks if n.casefold().startswith(prefix.casefold())] if prefix else []
1258
+ if not cands:
1259
+ return "break"
1260
+ at_start = text.strip() == word
1261
+ self._comp_suffix = ": " if at_start and not at else " "
1262
+ base, i = ("@" if at else ""), 0
1263
+ self._input.delete(f"insert-{len(word)}c", "insert")
1264
+ self._comp = (base, cands, i)
1265
+ self._input.insert("insert", base + cands[i] + self._comp_suffix)
1266
+ return "break"
1267
+
1268
+ _comp_suffix = " "
1269
+
1270
+
1271
+ _ChatProfileDialog = ChatProfileDialog