codis 1.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codis-1.1.1.dist-info/METADATA +194 -0
- codis-1.1.1.dist-info/RECORD +329 -0
- codis-1.1.1.dist-info/WHEEL +5 -0
- codis-1.1.1.dist-info/entry_points.txt +5 -0
- codis-1.1.1.dist-info/licenses/LICENSE +21 -0
- codis-1.1.1.dist-info/top_level.txt +2 -0
- run.py +190 -0
- src/__init__.py +1 -0
- src/__main__.py +81 -0
- src/_app_build.py +1507 -0
- src/_app_editor.py +1274 -0
- src/_app_kui.py +825 -0
- src/_app_lsp.py +625 -0
- src/_app_recovery.py +189 -0
- src/_app_settings.py +1385 -0
- src/_app_tools.py +2471 -0
- src/_app_webpreview.py +126 -0
- src/_font_safety.py +127 -0
- src/_shells.py +172 -0
- src/app.py +1488 -0
- src/chat/__init__.py +1 -0
- src/chat/adapters/__init__.py +33 -0
- src/chat/adapters/base.py +209 -0
- src/chat/adapters/discord.py +190 -0
- src/chat/adapters/http.py +78 -0
- src/chat/adapters/irc.py +360 -0
- src/chat/adapters/matrix.py +219 -0
- src/chat/adapters/mattermost.py +178 -0
- src/chat/adapters/mqtt.py +165 -0
- src/chat/adapters/slack.py +204 -0
- src/chat/adapters/telegram.py +117 -0
- src/chat/adapters/ws.py +154 -0
- src/chat/adapters/xmpp.py +337 -0
- src/chat/history.py +76 -0
- src/chat/models.py +207 -0
- src/chat/probe.py +79 -0
- src/chat/session.py +446 -0
- src/chat/util.py +125 -0
- src/collab/__init__.py +1 -0
- src/collab/net.py +411 -0
- src/collab/ot.py +311 -0
- src/collab/session.py +141 -0
- src/collab/tk_adapter.py +134 -0
- src/config.py +335 -0
- src/constants.py +2552 -0
- src/dep_catalog.py +446 -0
- src/diff/__init__.py +1 -0
- src/diff/engine.py +247 -0
- src/dpi.py +30 -0
- src/editor/__init__.py +1 -0
- src/editor/_pane_lsp.py +2937 -0
- src/editor/_pane_utils.py +171 -0
- src/editor/autocomplete.py +607 -0
- src/editor/code_folding.py +836 -0
- src/editor/color_preview.py +382 -0
- src/editor/complexity_lens.py +281 -0
- src/editor/diff_pane.py +623 -0
- src/editor/file_watcher.py +144 -0
- src/editor/focus_block.py +236 -0
- src/editor/heatmap.py +141 -0
- src/editor/inlay_hints.py +366 -0
- src/editor/inline_blame.py +429 -0
- src/editor/kdocs.py +3376 -0
- src/editor/large_file.py +488 -0
- src/editor/ligatures.py +180 -0
- src/editor/line_numbers.py +598 -0
- src/editor/minimap.py +691 -0
- src/editor/multi_cursor.py +269 -0
- src/editor/pane.py +2082 -0
- src/editor/rhythm.py +206 -0
- src/editor/save_hooks.py +43 -0
- src/editor/smart_selection.py +425 -0
- src/editor/smart_tips.py +719 -0
- src/editor/snippets.py +411 -0
- src/editor/sticky_note_gutter.py +410 -0
- src/editor/sticky_scroll.py +385 -0
- src/editor/suggest.py +464 -0
- src/editor/text_transforms.py +310 -0
- src/editor/vim_mode.py +1074 -0
- src/events/__init__.py +84 -0
- src/events/bus.py +427 -0
- src/events/correlator.py +244 -0
- src/events/kinds.py +125 -0
- src/events/pipeline.py +264 -0
- src/events/stream.py +416 -0
- src/events/window.py +204 -0
- src/extcompat/__init__.py +19 -0
- src/extcompat/code/__init__.py +13 -0
- src/extcompat/code/consent.py +162 -0
- src/extcompat/code/host.py +353 -0
- src/extcompat/code/hosts/py_host.py +763 -0
- src/extcompat/code/locate.py +105 -0
- src/extcompat/code/manager.py +325 -0
- src/extcompat/code/permissions.py +154 -0
- src/extcompat/code/sandbox.py +60 -0
- src/extcompat/colors.py +131 -0
- src/extcompat/common.py +184 -0
- src/extcompat/cson.py +269 -0
- src/extcompat/formats/__init__.py +22 -0
- src/extcompat/formats/_tm.py +189 -0
- src/extcompat/formats/_util.py +31 -0
- src/extcompat/formats/base16.py +66 -0
- src/extcompat/formats/brackets.py +172 -0
- src/extcompat/formats/eclipse.py +193 -0
- src/extcompat/formats/emacs.py +361 -0
- src/extcompat/formats/geany.py +147 -0
- src/extcompat/formats/generic.py +184 -0
- src/extcompat/formats/gtksource.py +117 -0
- src/extcompat/formats/helix.py +91 -0
- src/extcompat/formats/jetbrains.py +343 -0
- src/extcompat/formats/kate.py +130 -0
- src/extcompat/formats/micro.py +131 -0
- src/extcompat/formats/nano.py +111 -0
- src/extcompat/formats/notepadpp.py +140 -0
- src/extcompat/formats/pulsar.py +165 -0
- src/extcompat/formats/pyides.py +163 -0
- src/extcompat/formats/sublime.py +340 -0
- src/extcompat/jsonc.py +65 -0
- src/extcompat/lessish.py +128 -0
- src/extcompat/manager.py +122 -0
- src/extcompat/market/__init__.py +63 -0
- src/extcompat/market/sources.py +211 -0
- src/extcompat/model.py +88 -0
- src/extcompat/net.py +228 -0
- src/extcompat/openvsx.py +63 -0
- src/extcompat/readers.py +362 -0
- src/extcompat/registry.py +73 -0
- src/extcompat/safexml.py +63 -0
- src/extcompat/sexp.py +187 -0
- src/extcompat/sources.py +105 -0
- src/extcompat/store.py +276 -0
- src/extcompat/textmate.py +214 -0
- src/extcompat/themes.py +487 -0
- src/extcompat/yamlite.py +294 -0
- src/fileio.py +94 -0
- src/fs_ops.py +106 -0
- src/i18n.py +233 -0
- src/ia/__init__.py +1 -0
- src/ia/actions.py +295 -0
- src/ia/approval_gate.py +672 -0
- src/ia/checkpoints.py +308 -0
- src/ia/context_builder.py +921 -0
- src/ia/dialdiff.py +408 -0
- src/ia/iaspace.py +2078 -0
- src/ia/pair.py +296 -0
- src/ia/providers.py +954 -0
- src/ia/session.py +335 -0
- src/ia/toolbox.py +2524 -0
- src/launcher_actions.py +204 -0
- src/lint/__init__.py +1 -0
- src/lint/manager.py +1058 -0
- src/locales/.translate_manifest.json +64170 -0
- src/locales/de.json +4936 -0
- src/locales/en.json +4936 -0
- src/locales/es.json +4936 -0
- src/locales/fr.json +4936 -0
- src/locales/it.json +4936 -0
- src/locales/ja.json +4936 -0
- src/locales/ko.json +4936 -0
- src/locales/nl.json +4936 -0
- src/locales/pl.json +4936 -0
- src/locales/pt-BR.json +4936 -0
- src/locales/ru.json +4936 -0
- src/locales/tr.json +4936 -0
- src/locales/uk.json +4936 -0
- src/locales/zh-CN.json +4936 -0
- src/lsp/__init__.py +26 -0
- src/lsp/client.py +2300 -0
- src/lsp/dap_client.py +480 -0
- src/lsp/edits.py +84 -0
- src/lsp/framing.py +73 -0
- src/lsp/protocol.py +931 -0
- src/main.py +260 -0
- src/memtrim.py +91 -0
- src/plugins/__init__.py +1 -0
- src/plugins/api.py +1761 -0
- src/plugins/loader.py +571 -0
- src/plugins/process_runner.py +519 -0
- src/plugins/registry.py +342 -0
- src/plugins/safety.py +367 -0
- src/plugins/startup.py +195 -0
- src/plugins/store.py +1178 -0
- src/proc_registry.py +278 -0
- src/pyexec.py +394 -0
- src/recovery.py +259 -0
- src/stall_trace.py +92 -0
- src/standalone.py +1070 -0
- src/startup_profile.py +35 -0
- src/syntax/__init__.py +1 -0
- src/syntax/highlighter.py +776 -0
- src/syntax/patterns.py +584 -0
- src/system_profile.py +430 -0
- src/terminal/backends.py +658 -0
- src/terminal/internal.py +346 -0
- src/terminal/keys.py +138 -0
- src/terminal/palette.py +67 -0
- src/terminal/session.py +283 -0
- src/terminal/shells.py +79 -0
- src/terminal/view.py +489 -0
- src/terminal/vt.py +870 -0
- src/textfmt.py +22 -0
- src/theme/__init__.py +1 -0
- src/theme/base.py +1281 -0
- src/theme/colors.py +49 -0
- src/theme/manager.py +602 -0
- src/theme/utils.py +312 -0
- src/toolbox.py +329 -0
- src/trash_core.py +531 -0
- src/ui/__init__.py +1 -0
- src/ui/_perf_utils.py +285 -0
- src/ui/_persistence_utils.py +93 -0
- src/ui/accessibility.py +843 -0
- src/ui/activity_bar.py +860 -0
- src/ui/app_embed.py +434 -0
- src/ui/archive_panel.py +608 -0
- src/ui/bookmarks.py +314 -0
- src/ui/breadcrumb.py +383 -0
- src/ui/calculator_panel.py +982 -0
- src/ui/calendar_panel.py +1218 -0
- src/ui/chat_panel.py +1271 -0
- src/ui/chat_profile_dialog.py +278 -0
- src/ui/chat_render.py +128 -0
- src/ui/clock_panel.py +810 -0
- src/ui/code_outline.py +364 -0
- src/ui/code_runner.py +729 -0
- src/ui/code_stats.py +546 -0
- src/ui/collab_panel.py +1009 -0
- src/ui/color_picker.py +547 -0
- src/ui/command_palette.py +452 -0
- src/ui/cursor_manager.py +750 -0
- src/ui/custom_keywords_panel.py +413 -0
- src/ui/debug_panel.py +1037 -0
- src/ui/dependency_graph.py +692 -0
- src/ui/diff_panel.py +381 -0
- src/ui/docs_panel.py +514 -0
- src/ui/doom_embed.py +349 -0
- src/ui/dropdown.py +321 -0
- src/ui/easter_eggs.py +979 -0
- src/ui/env_manager.py +666 -0
- src/ui/extcode_bridge.py +215 -0
- src/ui/extcode_dialogs.py +412 -0
- src/ui/extcompat_dialog.py +583 -0
- src/ui/file_timeline.py +319 -0
- src/ui/file_tree.py +1208 -0
- src/ui/find_in_files.py +1355 -0
- src/ui/flowchart_panel.py +727 -0
- src/ui/formatter_panel.py +490 -0
- src/ui/git_auth.py +763 -0
- src/ui/git_clone_dialog.py +487 -0
- src/ui/git_panel.py +1483 -0
- src/ui/grab_safe.py +84 -0
- src/ui/internal_python_dialog.py +98 -0
- src/ui/k_ui/__init__.py +1305 -0
- src/ui/k_ui/_bgrenderer.py +317 -0
- src/ui/k_ui/_colors.py +213 -0
- src/ui/k_ui/_dock.py +545 -0
- src/ui/k_ui/_easter.py +290 -0
- src/ui/k_ui/_engine.py +5448 -0
- src/ui/k_ui/_perf.py +333 -0
- src/ui/k_ui/_tkutil.py +7 -0
- src/ui/k_ui/_tooltip.py +365 -0
- src/ui/k_ui/_widgets.py +1204 -0
- src/ui/k_ui/_world.py +837 -0
- src/ui/key_remapper.py +856 -0
- src/ui/launcher.py +1252 -0
- src/ui/lazy_panel.py +73 -0
- src/ui/macro_recorder.py +610 -0
- src/ui/menu_bar.py +898 -0
- src/ui/output_panel.py +321 -0
- src/ui/paint_canvas.py +1000 -0
- src/ui/paint_engine.py +535 -0
- src/ui/paint_panel.py +888 -0
- src/ui/panel_detach.py +112 -0
- src/ui/performance_panel.py +861 -0
- src/ui/pip_manager.py +1758 -0
- src/ui/plugin_panel.py +1586 -0
- src/ui/pomodoro_panel.py +447 -0
- src/ui/problems.py +566 -0
- src/ui/process_manager.py +1657 -0
- src/ui/project_templates.py +775 -0
- src/ui/recovery_dialog.py +122 -0
- src/ui/regex_playground.py +304 -0
- src/ui/remote_adapters.py +1398 -0
- src/ui/remote_browser.py +1224 -0
- src/ui/remote_profile_dialog.py +342 -0
- src/ui/render_panel.py +1293 -0
- src/ui/rest_client.py +549 -0
- src/ui/scratchpad.py +548 -0
- src/ui/search_bar.py +1274 -0
- src/ui/settings_editor.py +3349 -0
- src/ui/settings_window.py +1554 -0
- src/ui/snippets_panel.py +597 -0
- src/ui/sql_studio.py +1815 -0
- src/ui/status_bar.py +438 -0
- src/ui/tab_bar.py +654 -0
- src/ui/task_manager.py +1773 -0
- src/ui/terminal.py +525 -0
- src/ui/theme_preview_panel.py +851 -0
- src/ui/thread_safe_tk.py +152 -0
- src/ui/time_tracker.py +574 -0
- src/ui/tkbind.py +43 -0
- src/ui/todo_panel.py +358 -0
- src/ui/toolbox_panels.py +658 -0
- src/ui/trash_manager.py +657 -0
- src/ui/ui_scale.py +294 -0
- src/ui/ux_enhancements.py +41 -0
- src/ui/web_preview.py +397 -0
- src/ui/webdev.py +630 -0
- src/ui/welcome.py +567 -0
- src/ui/window_embed.py +1500 -0
- src/ui/wizard.py +1550 -0
- src/ui/workspace_switcher.py +418 -0
- src/ui/workspace_trust.py +370 -0
- src/ui/zen_audio.py +354 -0
- src/ui/zen_media.py +2271 -0
- src/ui/zen_media_client.py +303 -0
- src/ui/zen_media_host.py +329 -0
- src/ui/zen_player.py +907 -0
- src/ui/zen_player_widgets.py +700 -0
- src/updater/__init__.py +11 -0
- src/updater/assets.py +145 -0
- src/updater/backup.py +101 -0
- src/updater/channel.py +221 -0
- src/updater/dialog.py +492 -0
- src/updater/integrity.py +111 -0
- src/updater/manager.py +727 -0
- src/updater/result.py +114 -0
- src/venv_runtime.py +531 -0
- src/workspace_state.py +25 -0
src/theme/utils.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Codis - Utilitários de tema reutilizáveis.
|
|
3
|
+
|
|
4
|
+
Centraliza helpers que antes eram copiados em cada componente:
|
|
5
|
+
|
|
6
|
+
- ``cfg`` : aplica um dict de opções tk a um widget com supressão de TclError
|
|
7
|
+
- ``cfg_many`` : aplica o mesmo dict a múltiplos widgets
|
|
8
|
+
- ``theme_map`` : retorna dict {opção: valor_do_tema} para uso com cfg/cfg_many
|
|
9
|
+
- ``recolor`` : aplica paleta de tema a um mapping widget -> {opção: attr_tema}
|
|
10
|
+
- ``lsp_loc`` : extrai (uri, linha) de um objeto/dict de localização LSP
|
|
11
|
+
|
|
12
|
+
Esses helpers eliminam repetição em apply_theme() e _cb() espalhados pelo codebase.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import contextlib
|
|
18
|
+
import tkinter as tk
|
|
19
|
+
from collections.abc import Callable
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from src.constants import FONT_UI
|
|
23
|
+
from src.theme.colors import hex_to_rgb
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def cfg(widget: tk.Widget, **options: Any) -> None:
|
|
27
|
+
"""Aplica opções a um widget suprimindo TclError (widget destruído).
|
|
28
|
+
|
|
29
|
+
Substitui o padrão:
|
|
30
|
+
with contextlib.suppress(tk.TclError):
|
|
31
|
+
w.config(bg=..., fg=...)
|
|
32
|
+
"""
|
|
33
|
+
with contextlib.suppress(tk.TclError, AttributeError):
|
|
34
|
+
widget.config(**options)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def cfg_many(widgets: list[tk.Widget], **options: Any) -> None:
|
|
38
|
+
"""Aplica as mesmas opções a vários widgets de uma vez."""
|
|
39
|
+
for w in widgets:
|
|
40
|
+
cfg(w, **options)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def recolor(mapping: dict[tk.Widget, dict[str, str]]) -> None:
|
|
44
|
+
"""Aplica paleta de cores a múltiplos widgets via um mapeamento.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
mapping: {widget: {opção_tk: valor_cor}}
|
|
48
|
+
|
|
49
|
+
Exemplo::
|
|
50
|
+
|
|
51
|
+
recolor({
|
|
52
|
+
self._frame: {"bg": t.bg},
|
|
53
|
+
self._label: {"bg": t.bg, "fg": t.fg},
|
|
54
|
+
self._entry: {"bg": t.input_bg, "fg": t.fg,
|
|
55
|
+
"insertbackground": t.fg},
|
|
56
|
+
})
|
|
57
|
+
"""
|
|
58
|
+
for widget, opts in mapping.items():
|
|
59
|
+
cfg(widget, **opts)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def make_toolbar_button(
|
|
63
|
+
parent: tk.Widget,
|
|
64
|
+
theme: Any,
|
|
65
|
+
label: str,
|
|
66
|
+
cmd: Callable[[], Any],
|
|
67
|
+
*,
|
|
68
|
+
accent: bool = False,
|
|
69
|
+
side: str = "left",
|
|
70
|
+
outer_padx: int = 2,
|
|
71
|
+
outer_pady: int = 4,
|
|
72
|
+
inner_padx: int = 8,
|
|
73
|
+
inner_pady: int = 4,
|
|
74
|
+
font_size: int = 8,
|
|
75
|
+
) -> tk.Label:
|
|
76
|
+
"""Cria um botão de toolbar (``tk.Label`` clicável, com hover) padronizado.
|
|
77
|
+
|
|
78
|
+
Usado pelos painéis ``sql_studio``, ``task_manager``, ``diff_panel``,
|
|
79
|
+
``formatter_panel``, ``env_manager`` e ``pip_manager``; garante hover
|
|
80
|
+
consistente (``<Enter>``/``<Leave>``) em todo botão de toolbar.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
parent: Widget-pai onde o botão será posicionado (``pack``).
|
|
84
|
+
theme: Objeto de tema atual (precisa de ``accent``, ``sidebar_bg``,
|
|
85
|
+
``fg``, ``btn_hover``).
|
|
86
|
+
label: Texto exibido no botão.
|
|
87
|
+
cmd: Callback sem argumentos, chamado no clique (``<Button-1>``).
|
|
88
|
+
accent: Se ``True``, usa a cor de destaque (``theme.accent``) como
|
|
89
|
+
fundo e texto branco, em vez do estilo neutro padrão.
|
|
90
|
+
side: Lado do ``pack()`` (``"left"`` ou ``"right"``).
|
|
91
|
+
outer_padx: Espaçamento externo horizontal do ``pack()``.
|
|
92
|
+
outer_pady: Espaçamento externo vertical do ``pack()``.
|
|
93
|
+
inner_padx: Espaçamento interno horizontal do próprio label.
|
|
94
|
+
inner_pady: Espaçamento interno vertical do próprio label.
|
|
95
|
+
font_size: Tamanho da fonte (``FONT_UI``).
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
O ``tk.Label`` criado (já posicionado e com binds aplicados).
|
|
99
|
+
"""
|
|
100
|
+
bg = theme.accent if accent else theme.sidebar_bg
|
|
101
|
+
fg = "#FFF" if accent else theme.fg
|
|
102
|
+
b = tk.Label(
|
|
103
|
+
parent,
|
|
104
|
+
text=label,
|
|
105
|
+
bg=bg,
|
|
106
|
+
fg=fg,
|
|
107
|
+
font=(FONT_UI, font_size),
|
|
108
|
+
padx=inner_padx,
|
|
109
|
+
pady=inner_pady,
|
|
110
|
+
cursor="hand2",
|
|
111
|
+
)
|
|
112
|
+
b.pack(side=side, padx=outer_padx, pady=outer_pady)
|
|
113
|
+
b.bind("<Button-1>", lambda _e: cmd())
|
|
114
|
+
b.bind("<Enter>", lambda _e: b.config(bg=theme.btn_hover))
|
|
115
|
+
b.bind("<Leave>", lambda _e: b.config(bg=bg))
|
|
116
|
+
return b
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def lsp_loc_uri(loc: Any) -> str:
|
|
120
|
+
"""Extrai a URI de um objeto/dict de localização LSP."""
|
|
121
|
+
if hasattr(loc, "uri"):
|
|
122
|
+
return loc.uri
|
|
123
|
+
return loc.get("uri", "") if isinstance(loc, dict) else ""
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def lsp_loc_line(loc: Any) -> int:
|
|
127
|
+
"""Extrai a linha (1-based) de um objeto/dict de localização LSP."""
|
|
128
|
+
if hasattr(loc, "range"):
|
|
129
|
+
start = loc.range.start
|
|
130
|
+
line = start.line if hasattr(start, "line") else 0
|
|
131
|
+
else:
|
|
132
|
+
start = loc.get("range", {}).get(
|
|
133
|
+
"start", {}) if isinstance(loc, dict) else {}
|
|
134
|
+
line = start.get("line", 0) if isinstance(start, dict) else 0
|
|
135
|
+
return line + 1
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def lsp_loc_pair(loc: Any) -> tuple[str, int]:
|
|
139
|
+
"""Retorna (uri, linha_1based) de uma localização LSP."""
|
|
140
|
+
return lsp_loc_uri(loc), lsp_loc_line(loc)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _hex_to_rgb01(h: str) -> tuple[float, float, float]:
|
|
144
|
+
"""Converte hex (#rgb ou #rrggbb) para RGB normalizado (0.0-1.0)."""
|
|
145
|
+
h = h.lstrip("#")
|
|
146
|
+
if len(h) == 3:
|
|
147
|
+
h = "".join(c * 2 for c in h)
|
|
148
|
+
r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
|
|
149
|
+
return r / 255.0, g / 255.0, b / 255.0
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _rgb01_to_hex(r: float, g: float, b: float) -> str:
|
|
153
|
+
"""Converte RGB normalizado (0.0-1.0, com clamp) para hex #rrggbb."""
|
|
154
|
+
ri = max(0, min(255, round(r * 255)))
|
|
155
|
+
gi = max(0, min(255, round(g * 255)))
|
|
156
|
+
bi = max(0, min(255, round(b * 255)))
|
|
157
|
+
return f"#{ri:02x}{gi:02x}{bi:02x}"
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def alpha_blend_hex(fg: str, bg: str, alpha: float) -> str:
|
|
161
|
+
"""Blenda ``fg`` sobre ``bg`` com opacidade ``alpha``; retorna hex #rrggbb.
|
|
162
|
+
|
|
163
|
+
Tkinter não aceita cores hex com canal alpha (#rrggbbaa) - esta função
|
|
164
|
+
simula o efeito calculando a cor resultante diretamente. Usado por
|
|
165
|
+
``minimap``, ``task_manager`` e ``zen_media``.
|
|
166
|
+
|
|
167
|
+
Em caso de hex inválido, retorna ``fg`` sem modificação (preserva o
|
|
168
|
+
comportamento original desses módulos).
|
|
169
|
+
"""
|
|
170
|
+
try:
|
|
171
|
+
fr, fg_g, fb = hex_to_rgb(fg)
|
|
172
|
+
br, bg_g, bb = hex_to_rgb(bg)
|
|
173
|
+
r = int(fr * alpha + br * (1 - alpha))
|
|
174
|
+
g = int(fg_g * alpha + bg_g * (1 - alpha))
|
|
175
|
+
b = int(fb * alpha + bb * (1 - alpha))
|
|
176
|
+
return f"#{r:02x}{g:02x}{b:02x}"
|
|
177
|
+
except (ValueError, IndexError):
|
|
178
|
+
return fg
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def hex_blend(base: str, overlay: str, alpha: float) -> str:
|
|
182
|
+
"""Mistura duas cores hex (#rrggbb) com alpha (0.0-1.0).
|
|
183
|
+
|
|
184
|
+
Usado por `src/editor/_pane_lsp.py`, `src/theme/manager.py` e
|
|
185
|
+
`src/ui/theme_preview_panel.py`. Usa ``_hex_to_rgb01`` para a
|
|
186
|
+
normalização hex 3↔6 dígitos - o ``round()`` no caminho de ida e volta (int 0-255 -> float 0.0-1.0
|
|
187
|
+
-> int 0-255) é seguro porque ``round(c / 255.0 * 255.0) == c`` para
|
|
188
|
+
todo ``c`` em 0-255.
|
|
189
|
+
|
|
190
|
+
Args:
|
|
191
|
+
base: Cor de fundo (#rgb ou #rrggbb).
|
|
192
|
+
overlay: Cor sobreposta (#rgb ou #rrggbb).
|
|
193
|
+
alpha: Opacidade da sobreposição (0 = base pura, 1 = overlay pura).
|
|
194
|
+
|
|
195
|
+
Returns:
|
|
196
|
+
Cor resultante em formato #rrggbb.
|
|
197
|
+
"""
|
|
198
|
+
try:
|
|
199
|
+
br, bg_, bb = (round(c * 255) for c in _hex_to_rgb01(base))
|
|
200
|
+
or_, og, ob = (round(c * 255) for c in _hex_to_rgb01(overlay))
|
|
201
|
+
r = min(255, int(br + (or_ - br) * alpha))
|
|
202
|
+
g = min(255, int(bg_ + (og - bg_) * alpha))
|
|
203
|
+
b = min(255, int(bb + (ob - bb) * alpha))
|
|
204
|
+
return f"#{r:02x}{g:02x}{b:02x}"
|
|
205
|
+
except (ValueError, IndexError):
|
|
206
|
+
return base
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _rgb_to_hsl(r: float, g: float, b: float) -> tuple[float, float, float]:
|
|
210
|
+
"""Converte RGB (0-1) para HSL (h em 0-1, s em 0-1, lightness em 0-1)."""
|
|
211
|
+
mx, mn = max(r, g, b), min(r, g, b)
|
|
212
|
+
lightness = (mx + mn) / 2.0
|
|
213
|
+
if mx == mn:
|
|
214
|
+
return 0.0, 0.0, lightness
|
|
215
|
+
d = mx - mn
|
|
216
|
+
s = d / (2.0 - mx - mn) if lightness > 0.5 else d / (mx + mn)
|
|
217
|
+
if mx == r:
|
|
218
|
+
h = (g - b) / d + (6.0 if g < b else 0.0)
|
|
219
|
+
elif mx == g:
|
|
220
|
+
h = (b - r) / d + 2.0
|
|
221
|
+
else:
|
|
222
|
+
h = (r - g) / d + 4.0
|
|
223
|
+
return h / 6.0, s, lightness
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _hue_to_rgb(p: float, q: float, t: float) -> float:
|
|
227
|
+
"""Calcula um canal RGB a partir do hue, usado por ``_hsl_to_rgb``.
|
|
228
|
+
|
|
229
|
+
Implementa a função auxiliar padrão de conversão HSL->RGB (mesma
|
|
230
|
+
usada pelo algoritmo de referência do W3C CSS Color), aplicada três
|
|
231
|
+
vezes por ``_hsl_to_rgb`` (uma para cada canal, deslocando ``t`` em
|
|
232
|
+
±1/3) para reconstruir r, g e b a partir de hue/saturação/luminosidade.
|
|
233
|
+
"""
|
|
234
|
+
if t < 0:
|
|
235
|
+
t += 1.0
|
|
236
|
+
if t > 1:
|
|
237
|
+
t -= 1.0
|
|
238
|
+
if t < 1.0 / 6.0:
|
|
239
|
+
return p + (q - p) * 6.0 * t
|
|
240
|
+
if t < 1.0 / 2.0:
|
|
241
|
+
return q
|
|
242
|
+
if t < 2.0 / 3.0:
|
|
243
|
+
return p + (q - p) * (2.0 / 3.0 - t) * 6.0
|
|
244
|
+
return p
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _hsl_to_rgb(h: float, s: float, lightness: float) -> tuple[float, float, float]:
|
|
248
|
+
"""Converte HSL (0-1 cada) para RGB (0-1)."""
|
|
249
|
+
if s == 0:
|
|
250
|
+
return lightness, lightness, lightness
|
|
251
|
+
q = lightness * (1 + s) if lightness < 0.5 else lightness + s - lightness * s
|
|
252
|
+
p = 2 * lightness - q
|
|
253
|
+
r = _hue_to_rgb(p, q, h + 1.0 / 3.0)
|
|
254
|
+
g = _hue_to_rgb(p, q, h)
|
|
255
|
+
b = _hue_to_rgb(p, q, h - 1.0 / 3.0)
|
|
256
|
+
return r, g, b
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def hex_vibrance(
|
|
260
|
+
hex_color: str, sat_boost: float = 0.0, light_boost: float = 0.0
|
|
261
|
+
) -> str:
|
|
262
|
+
"""Aumenta saturação e/ou luminosidade de uma cor preservando a matiz.
|
|
263
|
+
|
|
264
|
+
Usado pelo boost holográfico: intensifica cores sem trocar o "tom"
|
|
265
|
+
de cada tema, mantendo a identidade visual de cada paleta.
|
|
266
|
+
|
|
267
|
+
Cores acromáticas (preto, branco, cinza - saturação original 0) são
|
|
268
|
+
tratadas como caso especial: como a matiz (hue) é matematicamente
|
|
269
|
+
indefinida nesses casos, aplicar ``sat_boost`` é ignorado para evitar
|
|
270
|
+
"inventar" uma cor com tom diferente do original (ex.: cinza virando
|
|
271
|
+
vermelho). Apenas ``light_boost`` é aplicado a cores acromáticas.
|
|
272
|
+
|
|
273
|
+
Args:
|
|
274
|
+
hex_color: Cor de origem (#rgb ou #rrggbb).
|
|
275
|
+
sat_boost: Delta de saturação, somado ao valor atual (-1.0 a 1.0).
|
|
276
|
+
light_boost: Delta de luminosidade, somado ao valor atual (-1.0 a 1.0).
|
|
277
|
+
|
|
278
|
+
Returns:
|
|
279
|
+
Cor resultante em formato #rrggbb. Em caso de erro de parsing,
|
|
280
|
+
retorna a cor original sem modificação.
|
|
281
|
+
"""
|
|
282
|
+
try:
|
|
283
|
+
r, g, b = _hex_to_rgb01(hex_color)
|
|
284
|
+
h, s, lightness = _rgb_to_hsl(r, g, b)
|
|
285
|
+
if s <= 0.0:
|
|
286
|
+
lightness = max(0.0, min(1.0, lightness + light_boost))
|
|
287
|
+
return _rgb01_to_hex(lightness, lightness, lightness)
|
|
288
|
+
s = max(0.0, min(1.0, s + sat_boost))
|
|
289
|
+
lightness = max(0.0, min(1.0, lightness + light_boost))
|
|
290
|
+
r2, g2, b2 = _hsl_to_rgb(h, s, lightness)
|
|
291
|
+
return _rgb01_to_hex(r2, g2, b2)
|
|
292
|
+
except (ValueError, IndexError, ZeroDivisionError):
|
|
293
|
+
return hex_color
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def hex_glow(hex_color: str, intensity: float = 0.35) -> str:
|
|
297
|
+
"""Gera uma variante "glow" de uma cor de acento, mais clara e saturada.
|
|
298
|
+
|
|
299
|
+
Usado para bordas com brilho, indicadores de foco e realces
|
|
300
|
+
holográficos - clareia a cor mantendo o tom, simulando um brilho
|
|
301
|
+
neon sutil sem saturar para branco puro.
|
|
302
|
+
|
|
303
|
+
Args:
|
|
304
|
+
hex_color: Cor de acento de origem.
|
|
305
|
+
intensity: Quanto clarear/saturar (0.0-1.0). Padrão 0.35.
|
|
306
|
+
|
|
307
|
+
Returns:
|
|
308
|
+
Cor resultante em formato #rrggbb.
|
|
309
|
+
"""
|
|
310
|
+
return hex_vibrance(
|
|
311
|
+
hex_color, sat_boost=intensity * 0.4, light_boost=intensity * 0.25
|
|
312
|
+
)
|
src/toolbox.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Funções puras dos utilitários da tela inicial: codificadores, geradores e visualizador hex.
|
|
2
|
+
|
|
3
|
+
Nada aqui depende de Tkinter, para que a lógica seja testada sem interface.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import binascii
|
|
10
|
+
import datetime as dt
|
|
11
|
+
import hashlib
|
|
12
|
+
import html
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import secrets
|
|
17
|
+
import string
|
|
18
|
+
import time
|
|
19
|
+
import uuid
|
|
20
|
+
from collections.abc import Callable
|
|
21
|
+
from urllib.parse import quote, unquote
|
|
22
|
+
|
|
23
|
+
# Codificação
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ConversionError(ValueError):
|
|
27
|
+
"""Entrada que não pode ser convertida pela operação escolhida."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def b64_encode(text: str, *, urlsafe: bool = False) -> str:
|
|
31
|
+
"""Base64 de ``text`` (UTF-8)."""
|
|
32
|
+
raw = text.encode("utf-8")
|
|
33
|
+
return (base64.urlsafe_b64encode(raw) if urlsafe else base64.b64encode(raw)).decode("ascii")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def b64_decode(text: str, *, urlsafe: bool = False) -> str:
|
|
37
|
+
"""Decodifica Base64, tolerando espaços, quebras de linha e ``=`` faltando."""
|
|
38
|
+
cleaned = "".join(text.split())
|
|
39
|
+
alphabet = r"[A-Za-z0-9_-]*" if urlsafe else r"[A-Za-z0-9+/]*"
|
|
40
|
+
if not re.fullmatch(alphabet + "={0,2}", cleaned):
|
|
41
|
+
raise ConversionError("Base64 inválido")
|
|
42
|
+
cleaned += "=" * (-len(cleaned) % 4)
|
|
43
|
+
try:
|
|
44
|
+
raw = (base64.urlsafe_b64decode if urlsafe else base64.b64decode)(cleaned)
|
|
45
|
+
except (binascii.Error, ValueError) as exc:
|
|
46
|
+
raise ConversionError("Base64 inválido") from exc
|
|
47
|
+
return raw.decode("utf-8", errors="replace")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def url_encode(text: str) -> str:
|
|
51
|
+
"""Codifica ``text`` como componente de URL (tudo fora de ``A-Za-z0-9-._~`` vira ``%XX``)."""
|
|
52
|
+
return quote(text, safe="")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def url_decode(text: str) -> str:
|
|
56
|
+
"""Decodifica sequências ``%XX`` (``+`` é preservado)."""
|
|
57
|
+
return unquote(text)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def html_escape(text: str) -> str:
|
|
61
|
+
"""Escapa ``& < > " '`` para HTML."""
|
|
62
|
+
return html.escape(text, quote=True)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def html_unescape(text: str) -> str:
|
|
66
|
+
"""Converte entidades HTML (``&``, ``'``...) de volta em caracteres."""
|
|
67
|
+
return html.unescape(text)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def hex_encode(text: str) -> str:
|
|
71
|
+
"""Bytes UTF-8 de ``text`` em hexadecimal, separados por espaço."""
|
|
72
|
+
return " ".join(f"{b:02x}" for b in text.encode("utf-8"))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def hex_decode(text: str) -> str:
|
|
76
|
+
"""Texto UTF-8 a partir de pares hexadecimais (espaços e ``0x`` são ignorados)."""
|
|
77
|
+
cleaned = text.replace("0x", "").replace("0X", "")
|
|
78
|
+
cleaned = "".join(ch for ch in cleaned if ch not in " \t\r\n:,-")
|
|
79
|
+
if len(cleaned) % 2:
|
|
80
|
+
raise ConversionError("Número ímpar de dígitos hexadecimais")
|
|
81
|
+
try:
|
|
82
|
+
return bytes.fromhex(cleaned).decode("utf-8", errors="replace")
|
|
83
|
+
except ValueError as exc:
|
|
84
|
+
raise ConversionError("Hexadecimal inválido") from exc
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
HASH_ALGORITHMS: tuple[str, ...] = ("md5", "sha1", "sha256", "sha512", "sha3_256", "blake2b")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def hash_all(data: bytes) -> dict[str, str]:
|
|
91
|
+
"""Resumo de ``data`` em cada algoritmo de :data:`HASH_ALGORITHMS`."""
|
|
92
|
+
return {name: hashlib.new(name, data).hexdigest() for name in HASH_ALGORITHMS}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def hashes_text(text: str) -> str:
|
|
96
|
+
"""Versão em texto de :func:`hash_all`, uma linha por algoritmo."""
|
|
97
|
+
return "\n".join(f"{name:<9} {digest}" for name, digest in hash_all(text.encode("utf-8")).items())
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _b64url_json(part: str) -> dict:
|
|
101
|
+
padded = part + "=" * (-len(part) % 4)
|
|
102
|
+
try:
|
|
103
|
+
value = json.loads(base64.urlsafe_b64decode(padded))
|
|
104
|
+
except (binascii.Error, ValueError) as exc:
|
|
105
|
+
raise ConversionError("JWT inválido: parte não é Base64/JSON") from exc
|
|
106
|
+
if not isinstance(value, dict):
|
|
107
|
+
raise ConversionError("JWT inválido: parte não é um objeto JSON")
|
|
108
|
+
return value
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def jwt_decode(token: str) -> str:
|
|
112
|
+
"""Mostra cabeçalho e carga de um JWT. A assinatura **não** é verificada."""
|
|
113
|
+
parts = token.strip().split(".")
|
|
114
|
+
if len(parts) != 3:
|
|
115
|
+
raise ConversionError("Um JWT tem três partes separadas por ponto")
|
|
116
|
+
header, payload = _b64url_json(parts[0]), _b64url_json(parts[1])
|
|
117
|
+
lines = [
|
|
118
|
+
"Cabeçalho:",
|
|
119
|
+
json.dumps(header, indent=2, ensure_ascii=False),
|
|
120
|
+
"",
|
|
121
|
+
"Carga:",
|
|
122
|
+
json.dumps(payload, indent=2, ensure_ascii=False),
|
|
123
|
+
]
|
|
124
|
+
for claim, label in (("iat", "Emitido em"), ("nbf", "Válido a partir de"), ("exp", "Expira em")):
|
|
125
|
+
value = payload.get(claim)
|
|
126
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
127
|
+
lines.append(f"{label}: {timestamp_to_iso(value)}")
|
|
128
|
+
exp = payload.get("exp")
|
|
129
|
+
if isinstance(exp, (int, float)) and not isinstance(exp, bool):
|
|
130
|
+
lines.append("Situação: " + ("expirado" if exp < time.time() else "dentro da validade"))
|
|
131
|
+
lines += ["", "A assinatura não foi verificada."]
|
|
132
|
+
return "\n".join(lines)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
OPERATIONS: dict[str, Callable[[str], str]] = {
|
|
136
|
+
"Base64 - codificar": b64_encode,
|
|
137
|
+
"Base64 - decodificar": b64_decode,
|
|
138
|
+
"Base64 URL - codificar": lambda t: b64_encode(t, urlsafe=True),
|
|
139
|
+
"Base64 URL - decodificar": lambda t: b64_decode(t, urlsafe=True),
|
|
140
|
+
"URL - codificar": url_encode,
|
|
141
|
+
"URL - decodificar": url_decode,
|
|
142
|
+
"HTML - escapar": html_escape,
|
|
143
|
+
"HTML - desescapar": html_unescape,
|
|
144
|
+
"Hexadecimal - codificar": hex_encode,
|
|
145
|
+
"Hexadecimal - decodificar": hex_decode,
|
|
146
|
+
"Hashes (MD5, SHA, BLAKE2)": hashes_text,
|
|
147
|
+
"JWT - decodificar": jwt_decode,
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def convert(operation: str, text: str) -> str:
|
|
152
|
+
"""Aplica a operação de :data:`OPERATIONS` chamada ``operation``."""
|
|
153
|
+
try:
|
|
154
|
+
func = OPERATIONS[operation]
|
|
155
|
+
except KeyError as exc:
|
|
156
|
+
raise ConversionError(f"Operação desconhecida: {operation}") from exc
|
|
157
|
+
return func(text)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# Geradores
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def uuid4() -> str:
|
|
164
|
+
"""UUID versão 4 (aleatório)."""
|
|
165
|
+
return str(uuid.uuid4())
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def uuid7(now_ms: int | None = None) -> str:
|
|
169
|
+
"""UUID versão 7: 48 bits de milissegundos Unix seguidos de bits aleatórios (ordenável por tempo)."""
|
|
170
|
+
millis = int(time.time() * 1000) if now_ms is None else now_ms
|
|
171
|
+
rand = int.from_bytes(os.urandom(10), "big")
|
|
172
|
+
value = (millis & ((1 << 48) - 1)) << 80
|
|
173
|
+
value |= 0x7 << 76
|
|
174
|
+
value |= ((rand >> 62) & 0xFFF) << 64
|
|
175
|
+
value |= 0b10 << 62
|
|
176
|
+
value |= rand & ((1 << 62) - 1)
|
|
177
|
+
return str(uuid.UUID(int=value))
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def generate_password(
|
|
181
|
+
length: int = 20,
|
|
182
|
+
*,
|
|
183
|
+
lower: bool = True,
|
|
184
|
+
upper: bool = True,
|
|
185
|
+
digits: bool = True,
|
|
186
|
+
symbols: bool = True,
|
|
187
|
+
avoid_ambiguous: bool = True,
|
|
188
|
+
) -> str:
|
|
189
|
+
"""Senha aleatória com ``secrets``; garante ao menos um caractere de cada grupo marcado."""
|
|
190
|
+
ambiguous = set("Il1O0o")
|
|
191
|
+
groups = [
|
|
192
|
+
(lower, string.ascii_lowercase),
|
|
193
|
+
(upper, string.ascii_uppercase),
|
|
194
|
+
(digits, string.digits),
|
|
195
|
+
(symbols, "!@#$%^&*()-_=+[]{};:,.?"),
|
|
196
|
+
]
|
|
197
|
+
pools = [
|
|
198
|
+
"".join(c for c in chars if not (avoid_ambiguous and c in ambiguous))
|
|
199
|
+
for enabled, chars in groups
|
|
200
|
+
if enabled
|
|
201
|
+
]
|
|
202
|
+
if not pools:
|
|
203
|
+
raise ValueError("Marque ao menos um tipo de caractere")
|
|
204
|
+
if length < len(pools):
|
|
205
|
+
raise ValueError(f"O tamanho mínimo é {len(pools)}")
|
|
206
|
+
chars = [secrets.choice(pool) for pool in pools]
|
|
207
|
+
everything = "".join(pools)
|
|
208
|
+
chars += [secrets.choice(everything) for _ in range(length - len(chars))]
|
|
209
|
+
secrets.SystemRandom().shuffle(chars)
|
|
210
|
+
return "".join(chars)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def password_entropy_bits(password: str, pool_size: int) -> float:
|
|
214
|
+
"""Estimativa de entropia em bits para uma senha escolhida de um alfabeto de ``pool_size`` símbolos."""
|
|
215
|
+
import math
|
|
216
|
+
|
|
217
|
+
return len(password) * math.log2(pool_size) if pool_size > 1 else 0.0
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
_LOREM = (
|
|
221
|
+
"lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore "
|
|
222
|
+
"et dolore magna aliqua enim ad minim veniam quis nostrud exercitation ullamco laboris nisi aliquip "
|
|
223
|
+
"ex ea commodo consequat duis aute irure in reprehenderit voluptate velit esse cillum fugiat nulla "
|
|
224
|
+
"pariatur excepteur sint occaecat cupidatat non proident sunt culpa qui officia deserunt mollit anim id est laborum"
|
|
225
|
+
).split()
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def lorem_ipsum(paragraphs: int = 3, sentences: int = 4) -> str:
|
|
229
|
+
"""Texto de preenchimento. Determinístico: os mesmos parâmetros geram sempre o mesmo texto."""
|
|
230
|
+
out = []
|
|
231
|
+
index = 0
|
|
232
|
+
for p in range(max(1, paragraphs)):
|
|
233
|
+
built = []
|
|
234
|
+
for s in range(max(1, sentences)):
|
|
235
|
+
size = 7 + (p * 3 + s * 5) % 8
|
|
236
|
+
words = [_LOREM[(index + k) % len(_LOREM)] for k in range(size)]
|
|
237
|
+
index += size
|
|
238
|
+
built.append(" ".join(words).capitalize() + ".")
|
|
239
|
+
out.append(" ".join(built))
|
|
240
|
+
return "\n\n".join(out)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def timestamp_to_iso(value: float) -> str:
|
|
244
|
+
"""Data/hora UTC de um timestamp Unix em segundos, ou em milissegundos (valores acima de 1e11)."""
|
|
245
|
+
seconds = value / 1000 if abs(value) > 1e11 else value
|
|
246
|
+
try:
|
|
247
|
+
moment = dt.datetime.fromtimestamp(seconds, tz=dt.timezone.utc)
|
|
248
|
+
except (OverflowError, OSError, ValueError) as exc:
|
|
249
|
+
raise ConversionError("Timestamp fora do intervalo") from exc
|
|
250
|
+
return moment.strftime("%Y-%m-%d %H:%M:%S UTC")
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def parse_timestamp(text: str) -> float:
|
|
254
|
+
"""Timestamp Unix (segundos) a partir de um número ou de uma data ISO 8601 (``Z`` = UTC; sem fuso = UTC)."""
|
|
255
|
+
cleaned = text.strip()
|
|
256
|
+
if not cleaned:
|
|
257
|
+
raise ConversionError("Informe um timestamp ou uma data")
|
|
258
|
+
try:
|
|
259
|
+
return float(cleaned)
|
|
260
|
+
except ValueError:
|
|
261
|
+
pass
|
|
262
|
+
try:
|
|
263
|
+
moment = dt.datetime.fromisoformat(cleaned.replace("Z", "+00:00").replace(" UTC", "+00:00"))
|
|
264
|
+
except ValueError as exc:
|
|
265
|
+
raise ConversionError("Use um número ou uma data como 2026-11-23 14:30:00") from exc
|
|
266
|
+
if moment.tzinfo is None:
|
|
267
|
+
moment = moment.replace(tzinfo=dt.timezone.utc)
|
|
268
|
+
return moment.timestamp()
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def describe_timestamp(text: str) -> str:
|
|
272
|
+
"""Mostra um timestamp em segundos, milissegundos e datas UTC e local."""
|
|
273
|
+
seconds = parse_timestamp(text)
|
|
274
|
+
if abs(seconds) > 1e11:
|
|
275
|
+
seconds /= 1000
|
|
276
|
+
iso = timestamp_to_iso(seconds)
|
|
277
|
+
local = dt.datetime.fromtimestamp(seconds).astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")
|
|
278
|
+
return f"Segundos: {int(seconds)}\nMilissegundos: {int(seconds * 1000)}\nUTC: {iso}\nLocal: {local}"
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
# Hex
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def hexdump_lines(data: bytes, base: int = 0, width: int = 16) -> list[str]:
|
|
285
|
+
"""Linhas ``offset bytes ascii`` para ``data``, com offsets a partir de ``base``."""
|
|
286
|
+
lines = []
|
|
287
|
+
for i in range(0, len(data), width):
|
|
288
|
+
chunk = data[i : i + width]
|
|
289
|
+
hexes = " ".join(f"{b:02x}" for b in chunk).ljust(width * 3 - 1)
|
|
290
|
+
text = "".join(chr(b) if 32 <= b < 127 else "." for b in chunk)
|
|
291
|
+
lines.append(f"{base + i:08x} {hexes} |{text}|")
|
|
292
|
+
return lines
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def parse_search_bytes(query: str, *, as_hex: bool) -> bytes:
|
|
296
|
+
"""Bytes a procurar: texto UTF-8 ou pares hexadecimais (``de ad be ef``)."""
|
|
297
|
+
if not query:
|
|
298
|
+
raise ConversionError("Informe o que procurar")
|
|
299
|
+
if as_hex:
|
|
300
|
+
cleaned = "".join(ch for ch in query if ch not in " \t:,-")
|
|
301
|
+
try:
|
|
302
|
+
return bytes.fromhex(cleaned)
|
|
303
|
+
except ValueError as exc:
|
|
304
|
+
raise ConversionError("Hexadecimal inválido") from exc
|
|
305
|
+
return query.encode("utf-8")
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def find_bytes(path: str, needle: bytes, start: int = 0, chunk: int = 1 << 20) -> int:
|
|
309
|
+
"""Primeiro offset de ``needle`` em ``path`` a partir de ``start``; ``-1`` se não houver.
|
|
310
|
+
|
|
311
|
+
Lê o arquivo em blocos (sem carregá-lo inteiro), cobrindo padrões que cruzam o limite entre blocos.
|
|
312
|
+
"""
|
|
313
|
+
if not needle:
|
|
314
|
+
return -1
|
|
315
|
+
overlap = len(needle) - 1
|
|
316
|
+
with open(path, "rb") as handle:
|
|
317
|
+
handle.seek(start)
|
|
318
|
+
pos = start
|
|
319
|
+
tail = b""
|
|
320
|
+
while True:
|
|
321
|
+
block = handle.read(chunk)
|
|
322
|
+
if not block:
|
|
323
|
+
return -1
|
|
324
|
+
data = tail + block
|
|
325
|
+
hit = data.find(needle)
|
|
326
|
+
if hit >= 0:
|
|
327
|
+
return pos - len(tail) + hit
|
|
328
|
+
tail = data[-overlap:] if overlap else b""
|
|
329
|
+
pos += len(block)
|