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
@@ -0,0 +1,982 @@
1
+ """Codis - Calculadora Integrada.
2
+
3
+ Funcionalidades:
4
+ - Calculadora básica e científica com histórico de expressão e resultado
5
+ - Histórico persistente de cálculos
6
+ - Anotações livres por cálculo
7
+ - Conversão de unidades (comprimento, peso, temperatura)
8
+ - Expressões Python completas no campo de entrada
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import ast
14
+ import contextlib
15
+ import json
16
+ import logging
17
+ import math
18
+ import operator
19
+ import tkinter as tk
20
+ from tkinter import ttk
21
+ from typing import Any
22
+
23
+ from src.constants import CONFIG_DIR, FONT_MONO, FONT_UI
24
+ from src.i18n import _t
25
+
26
+ logger = logging.getLogger("Codis.Calculator")
27
+
28
+ _HISTORY_FILE = CONFIG_DIR / "calc_history.json"
29
+ _MAX_HISTORY = 200
30
+
31
+
32
+ def _load_history() -> list[dict]:
33
+ if not _HISTORY_FILE.exists():
34
+ return []
35
+ try:
36
+ return json.loads(_HISTORY_FILE.read_text(encoding="utf-8"))
37
+ except Exception:
38
+ return []
39
+
40
+
41
+ def _save_history(items: list[dict]) -> None:
42
+ _HISTORY_FILE.parent.mkdir(parents=True, exist_ok=True)
43
+ _HISTORY_FILE.write_text(
44
+ json.dumps(items[-_MAX_HISTORY:], indent=2, ensure_ascii=False),
45
+ encoding="utf-8",
46
+ )
47
+
48
+
49
+ _BIN_OPS = {
50
+ ast.Add: operator.add,
51
+ ast.Sub: operator.sub,
52
+ ast.Mult: operator.mul,
53
+ ast.Div: operator.truediv,
54
+ ast.FloorDiv: operator.floordiv,
55
+ ast.Mod: operator.mod,
56
+ ast.Pow: operator.pow,
57
+ ast.BitAnd: operator.and_,
58
+ ast.BitOr: operator.or_,
59
+ ast.BitXor: operator.xor,
60
+ ast.LShift: operator.lshift,
61
+ ast.RShift: operator.rshift,
62
+ }
63
+ _UNARY_OPS = {ast.UAdd: operator.pos, ast.USub: operator.neg, ast.Invert: operator.invert}
64
+ _MAX_EXPONENT_BITS = 100_000
65
+ _MAX_FACTORIAL = 5_000
66
+
67
+
68
+ def _check_size(op: type, left: Any, right: Any) -> None:
69
+ """Recusa operações inteiras cujo resultado levaria tempo ou memória excessivos."""
70
+ if not (isinstance(left, int) and isinstance(right, int)):
71
+ return
72
+ if op is ast.Pow and right > 0:
73
+ if abs(left).bit_length() * right > _MAX_EXPONENT_BITS:
74
+ raise OverflowError("expoente muito grande")
75
+ elif op is ast.LShift and right > _MAX_EXPONENT_BITS:
76
+ raise OverflowError("deslocamento muito grande")
77
+
78
+
79
+ def _safe_eval(expression: str, names: dict[str, Any]) -> Any:
80
+ """Avalia uma expressão aritmética sem executar código arbitrário.
81
+
82
+ Só aceita números, operadores aritméticos e bit a bit, nomes presentes em
83
+ ``names`` e chamadas posicionais a funções desse mesmo dicionário.
84
+
85
+ Raises:
86
+ ValueError: para qualquer construção não permitida.
87
+ OverflowError: se uma operação inteira for grande demais.
88
+ """
89
+
90
+ def walk(node: ast.AST) -> Any:
91
+ if isinstance(node, ast.Expression):
92
+ return walk(node.body)
93
+ if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
94
+ return node.value
95
+ if isinstance(node, ast.Name) and node.id in names:
96
+ return names[node.id]
97
+ if isinstance(node, ast.BinOp) and type(node.op) in _BIN_OPS:
98
+ left, right = walk(node.left), walk(node.right)
99
+ _check_size(type(node.op), left, right)
100
+ return _BIN_OPS[type(node.op)](left, right)
101
+ if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY_OPS:
102
+ return _UNARY_OPS[type(node.op)](walk(node.operand))
103
+ if (
104
+ isinstance(node, ast.Call)
105
+ and isinstance(node.func, ast.Name)
106
+ and callable(names.get(node.func.id))
107
+ and not node.keywords
108
+ ):
109
+ args = [walk(arg) for arg in node.args]
110
+ if node.func.id == "factorial" and args and args[0] > _MAX_FACTORIAL:
111
+ raise OverflowError("fatorial muito grande")
112
+ if node.func.id == "pow" and len(args) == 2:
113
+ _check_size(ast.Pow, *args)
114
+ return names[node.func.id](*args)
115
+ raise ValueError(f"construção não permitida: {type(node).__name__}")
116
+
117
+ return walk(ast.parse(expression, mode="eval"))
118
+
119
+
120
+ def _decimal_commas_to_points(expression: str) -> str:
121
+ """Converte vírgula decimal em ponto, preservando vírgulas de argumentos.
122
+
123
+ Só vírgulas fora de parênteses e entre dígitos são convertidas, então
124
+ ``3,5 + 2`` vira ``3.5 + 2`` e ``max(1,2)`` permanece intacto.
125
+ """
126
+ out: list[str] = []
127
+ depth = 0
128
+ for index, char in enumerate(expression):
129
+ if char == "(":
130
+ depth += 1
131
+ elif char == ")":
132
+ depth = max(0, depth - 1)
133
+ is_decimal = (
134
+ char == ","
135
+ and depth == 0
136
+ and 0 < index < len(expression) - 1
137
+ and expression[index - 1].isdigit()
138
+ and expression[index + 1].isdigit()
139
+ )
140
+ out.append("." if is_decimal else char)
141
+ return "".join(out)
142
+
143
+
144
+ def _btn(
145
+ parent: tk.Widget,
146
+ text: str,
147
+ cmd: Any,
148
+ bg: str,
149
+ fg: str,
150
+ font: tuple,
151
+ active_bg: str = "",
152
+ active_fg: str = "",
153
+ ) -> tk.Label:
154
+ """Label estilizado como botão com hover."""
155
+ lbl = tk.Label(
156
+ parent, text=text, bg=bg, fg=fg, font=font, cursor="hand2", relief="flat"
157
+ )
158
+ lbl.bind("<Button-1>", lambda _: cmd())
159
+ if active_bg:
160
+ lbl.bind("<Enter>", lambda _: lbl.config(
161
+ bg=active_bg, fg=active_fg or fg))
162
+ lbl.bind("<Leave>", lambda _: lbl.config(bg=bg, fg=fg))
163
+ return lbl
164
+
165
+
166
+ class CalculatorPanel(tk.Frame):
167
+ """Calculadora integrada ao Codis com histórico e anotações."""
168
+
169
+ _SAFE_BUILTINS = {
170
+ "abs": abs,
171
+ "round": round,
172
+ "min": min,
173
+ "max": max,
174
+ "sum": sum,
175
+ "pow": pow,
176
+ "int": int,
177
+ "float": float,
178
+ "hex": hex,
179
+ "oct": oct,
180
+ "bin": bin,
181
+ "pi": math.pi,
182
+ "e": math.e,
183
+ "tau": math.tau,
184
+ "sqrt": math.sqrt,
185
+ "cbrt": lambda x: x ** (1 / 3),
186
+ "sin": math.sin,
187
+ "cos": math.cos,
188
+ "tan": math.tan,
189
+ "asin": math.asin,
190
+ "acos": math.acos,
191
+ "atan": math.atan,
192
+ "atan2": math.atan2,
193
+ "sinh": math.sinh,
194
+ "cosh": math.cosh,
195
+ "tanh": math.tanh,
196
+ "log": math.log,
197
+ "log2": math.log2,
198
+ "log10": math.log10,
199
+ "exp": math.exp,
200
+ "ceil": math.ceil,
201
+ "floor": math.floor,
202
+ "factorial": math.factorial,
203
+ "gcd": math.gcd,
204
+ "lcm": getattr(math, "lcm", None),
205
+ "degrees": math.degrees,
206
+ "radians": math.radians,
207
+ "inf": math.inf,
208
+ "nan": math.nan,
209
+ }
210
+
211
+ def __init__(self, parent: tk.Widget, tmgr: Any, cfg: Any) -> None:
212
+ t = tmgr.theme
213
+ super().__init__(parent, bg=t.panel_bg)
214
+ self._tmgr = tmgr
215
+ self._cfg = cfg
216
+ self._history: list[dict] = _load_history()
217
+ self._memory: float = 0.0
218
+ self._last_result: float | None = None
219
+ self._history_idx = -1
220
+ self._mode = tk.StringVar(value="basic")
221
+ self._build(t)
222
+
223
+ def _build(self, t: Any) -> None:
224
+ hdr = tk.Frame(self, bg=t.activity_bg, height=48)
225
+ hdr.pack(fill="x")
226
+ hdr.pack_propagate(False)
227
+
228
+ tk.Label(
229
+ hdr, text="🔢", bg=t.activity_bg, fg=t.accent, font=(FONT_UI, 16)
230
+ ).pack(side="left", padx=(14, 4), pady=8)
231
+ tk.Label(
232
+ hdr,
233
+ text=_t("calc.title", "Calculadora"),
234
+ bg=t.activity_bg,
235
+ fg=t.fg,
236
+ font=(FONT_UI, 13, "bold"),
237
+ ).pack(side="left", pady=8)
238
+
239
+ tab_fr = tk.Frame(hdr, bg=t.activity_bg)
240
+ tab_fr.pack(side="right", padx=10)
241
+ self._mode_btns: dict[str, tk.Label] = {}
242
+ for key, val in [
243
+ ("calc.mode_basic", "basic"),
244
+ ("calc.mode_sci", "sci"),
245
+ ("calc.mode_conv", "conv"),
246
+ ]:
247
+ b = tk.Label(
248
+ tab_fr,
249
+ text=_t(key),
250
+ bg=t.activity_bg,
251
+ fg=t.fg_muted,
252
+ font=(FONT_UI, 8),
253
+ cursor="hand2",
254
+ padx=8,
255
+ pady=4,
256
+ )
257
+ b.pack(side="left")
258
+ b.bind("<Button-1>", lambda _, v=val: self._switch_mode(v))
259
+ self._mode_btns[val] = b
260
+
261
+ tk.Frame(self, bg=t.border, height=1).pack(fill="x")
262
+
263
+ body = tk.Frame(self, bg=t.panel_bg)
264
+ body.pack(fill="both", expand=True)
265
+
266
+ self._left = tk.Frame(body, bg=t.panel_bg, width=260)
267
+ self._left.pack(side="left", fill="y")
268
+ self._left.pack_propagate(False)
269
+
270
+ tk.Frame(body, bg=t.border, width=1).pack(side="left", fill="y")
271
+
272
+ right = tk.Frame(body, bg=t.panel_bg)
273
+ right.pack(side="left", fill="both", expand=True)
274
+
275
+ self._build_display(self._left, t)
276
+ self._build_basic_buttons(self._left, t)
277
+ self._build_history(right, t)
278
+
279
+ self._sci_frame = tk.Frame(self._left, bg=t.panel_bg)
280
+ self._conv_frame = tk.Frame(self._left, bg=t.panel_bg)
281
+ self._build_sci_buttons(self._sci_frame, t)
282
+ self._build_conv(self._conv_frame, t)
283
+
284
+ def _build_display(self, parent: tk.Widget, t: Any) -> None:
285
+ """Display com expressão + resultado + memória."""
286
+ disp = tk.Frame(
287
+ parent, bg=t.editor_bg, highlightthickness=1, highlightbackground=t.border
288
+ )
289
+ disp.pack(fill="x", padx=10, pady=(10, 4))
290
+
291
+ top_row = tk.Frame(disp, bg=t.editor_bg)
292
+ top_row.pack(fill="x", padx=8, pady=(6, 0))
293
+ self._memory_lbl = tk.Label(
294
+ top_row,
295
+ text="M: 0",
296
+ bg=t.editor_bg,
297
+ fg=t.fg_muted,
298
+ font=(FONT_UI, 7),
299
+ anchor="w",
300
+ )
301
+ self._memory_lbl.pack(side="left")
302
+ self._mode_badge = tk.Label(
303
+ top_row,
304
+ text="RAD",
305
+ bg=t.accent,
306
+ fg=t.btn_primary_fg,
307
+ font=(FONT_UI, 7),
308
+ padx=4,
309
+ pady=1,
310
+ )
311
+ self._mode_badge.pack(side="right")
312
+ self._mode_badge.pack_forget()
313
+
314
+ self._expr_var = tk.StringVar()
315
+ self._expr_entry = tk.Entry(
316
+ disp,
317
+ textvariable=self._expr_var,
318
+ bg=t.editor_bg,
319
+ fg=t.fg_muted,
320
+ font=(FONT_MONO, 12),
321
+ insertbackground=t.cursor,
322
+ relief="flat",
323
+ bd=0,
324
+ justify="right",
325
+ )
326
+ self._expr_entry.pack(fill="x", padx=8, pady=(2, 0))
327
+ self._expr_entry.bind("<Return>", lambda _: self._evaluate())
328
+ self._expr_entry.bind("<Up>", self._history_up)
329
+ self._expr_entry.bind("<Down>", self._history_down)
330
+ self._expr_entry.bind("<Escape>", lambda _: self._btn_action("c"))
331
+ self._expr_entry.focus_set()
332
+
333
+ self._result_var = tk.StringVar(value="0")
334
+ tk.Label(
335
+ disp,
336
+ textvariable=self._result_var,
337
+ bg=t.editor_bg,
338
+ fg=t.accent,
339
+ font=(FONT_MONO, 28, "bold"),
340
+ anchor="e",
341
+ ).pack(fill="x", padx=8, pady=(2, 8))
342
+
343
+ mem_row = tk.Frame(parent, bg=t.panel_bg)
344
+ mem_row.pack(fill="x", padx=10, pady=(0, 2))
345
+ for lbl, cmd in [
346
+ ("MC", self._mem_clear),
347
+ ("MR", self._mem_recall),
348
+ ("M+", self._mem_add),
349
+ ("M−", self._mem_sub),
350
+ ("MS", self._mem_store),
351
+ ]:
352
+ b = tk.Label(
353
+ mem_row,
354
+ text=lbl,
355
+ bg=t.btn_bg,
356
+ fg=t.fg_muted,
357
+ font=(FONT_UI, 8),
358
+ cursor="hand2",
359
+ padx=6,
360
+ pady=3,
361
+ relief="flat",
362
+ )
363
+ b.pack(side="left", fill="x", expand=True, padx=1)
364
+ b.bind("<Button-1>", lambda _, c=cmd: c())
365
+ b.bind("<Enter>", lambda e, w=b: w.config(bg=t.btn_hover))
366
+ b.bind("<Leave>", lambda e, w=b, bg=t.btn_bg: w.config(bg=bg))
367
+
368
+ def _build_basic_buttons(self, parent: tk.Widget, t: Any) -> None:
369
+ """Grade de botões principais 4×5 usando grid."""
370
+ self._btn_frame = tk.Frame(parent, bg=t.panel_bg)
371
+ self._btn_frame.pack(fill="both", expand=True, padx=10, pady=(0, 10))
372
+
373
+ layout = [
374
+ ("CE", "ce", "clear"),
375
+ ("C", "c", "clear"),
376
+ ("⌫", "bs", "clear"),
377
+ ("÷", "/", "op"),
378
+ ("7", "7", None),
379
+ ("8", "8", None),
380
+ ("9", "9", None),
381
+ ("×", "*", "op"),
382
+ ("4", "4", None),
383
+ ("5", "5", None),
384
+ ("6", "6", None),
385
+ ("−", "-", "op"),
386
+ ("1", "1", None),
387
+ ("2", "2", None),
388
+ ("3", "3", None),
389
+ ("+", "+", "op"),
390
+ ("±", "neg", None),
391
+ ("0", "0", None),
392
+ (".", ".", None),
393
+ ("=", "=", "eq"),
394
+ ]
395
+
396
+ col_count = 4
397
+ for i, (text, action, kind) in enumerate(layout):
398
+ row_i, col_i = divmod(i, col_count)
399
+ if kind == "clear":
400
+ bg = t.border
401
+ fg = t.fg
402
+ elif kind == "op":
403
+ bg = t.btn_hover
404
+ fg = t.t_func
405
+ elif kind == "eq":
406
+ bg = t.accent
407
+ fg = t.btn_primary_fg
408
+ else:
409
+ bg = t.btn_bg
410
+ fg = t.fg
411
+
412
+ lbl = tk.Label(
413
+ self._btn_frame,
414
+ text=text,
415
+ bg=bg,
416
+ fg=fg,
417
+ font=(FONT_UI, 14, "bold" if kind == "eq" else "normal"),
418
+ cursor="hand2",
419
+ relief="flat",
420
+ pady=9,
421
+ )
422
+ lbl.grid(row=row_i, column=col_i, sticky="nsew", padx=1, pady=1)
423
+ lbl.bind("<Button-1>", lambda _, a=action: self._btn_action(a))
424
+ hover = t.sel_bg
425
+ lbl.bind("<Enter>", lambda e, w=lbl, h=hover: w.config(bg=h))
426
+ lbl.bind("<Leave>", lambda e, w=lbl, b=bg: w.config(bg=b))
427
+
428
+ for c in range(col_count):
429
+ self._btn_frame.columnconfigure(c, weight=1)
430
+ for r in range(5):
431
+ self._btn_frame.rowconfigure(r, weight=1)
432
+
433
+ def _build_sci_buttons(self, parent: tk.Widget, t: Any) -> None:
434
+ """Botões científicos extras."""
435
+ sci_fns = [
436
+ ("sin", "sin("),
437
+ ("cos", "cos("),
438
+ ("tan", "tan("),
439
+ ("π", "pi"),
440
+ ("asin", "asin("),
441
+ ("acos", "acos("),
442
+ ("atan", "atan("),
443
+ ("e", "e"),
444
+ ("√", "sqrt("),
445
+ ("x²", "**2"),
446
+ ("x³", "**3"),
447
+ ("^", "**"),
448
+ ("log", "log("),
449
+ ("ln", "log("),
450
+ ("(", "("),
451
+ (")", ")"),
452
+ ("1/x", "1/("),
453
+ ("n!", "factorial("),
454
+ ("ceil", "ceil("),
455
+ ("floor", "floor("),
456
+ ]
457
+ for i, (lbl, snippet) in enumerate(sci_fns):
458
+ r, c = divmod(i, 4)
459
+ b = tk.Label(
460
+ parent,
461
+ text=lbl,
462
+ bg=t.sidebar_bg,
463
+ fg=t.t_func,
464
+ font=(FONT_UI, 9),
465
+ cursor="hand2",
466
+ relief="flat",
467
+ pady=7,
468
+ padx=4,
469
+ )
470
+ b.grid(row=r, column=c, sticky="nsew", padx=1, pady=1)
471
+ b.bind("<Button-1>", lambda _, s=snippet: self._insert_snippet(s))
472
+ b.bind("<Enter>", lambda e, w=b: w.config(bg=t.btn_hover))
473
+ b.bind("<Leave>", lambda e, w=b: w.config(bg=t.sidebar_bg))
474
+ for c in range(4):
475
+ parent.columnconfigure(c, weight=1)
476
+
477
+ def _build_conv(self, parent: tk.Widget, t: Any) -> None:
478
+ """Painel de conversão de unidades."""
479
+ tk.Label(
480
+ parent,
481
+ text=_t("calc.conv_title", "Converter"),
482
+ bg=t.panel_bg,
483
+ fg=t.fg_muted,
484
+ font=(FONT_UI, 9, "bold"),
485
+ ).pack(anchor="w", padx=8, pady=(8, 2))
486
+
487
+ self._conv_val = tk.StringVar(value="1")
488
+ self._conv_from = tk.StringVar(value="m")
489
+ self._conv_to = tk.StringVar(value="cm")
490
+ self._conv_res = tk.StringVar(value="")
491
+
492
+ val_f = tk.Frame(parent, bg=t.panel_bg)
493
+ val_f.pack(fill="x", padx=8, pady=2)
494
+ tk.Label(
495
+ val_f,
496
+ text=_t("calc.conv_value", "Valor"),
497
+ bg=t.panel_bg,
498
+ fg=t.fg_muted,
499
+ font=(FONT_UI, 8),
500
+ width=6,
501
+ anchor="w",
502
+ ).pack(side="left")
503
+ tk.Entry(
504
+ val_f,
505
+ textvariable=self._conv_val,
506
+ bg=t.input_bg,
507
+ fg=t.fg,
508
+ insertbackground=t.cursor,
509
+ relief="flat",
510
+ bd=0,
511
+ highlightthickness=1,
512
+ highlightbackground=t.border,
513
+ font=(FONT_MONO, 10),
514
+ width=14,
515
+ ).pack(side="left", padx=4)
516
+
517
+ from_f = tk.Frame(parent, bg=t.panel_bg)
518
+ from_f.pack(fill="x", padx=8, pady=2)
519
+ tk.Label(
520
+ from_f,
521
+ text=_t("calc.conv_from", "De"),
522
+ bg=t.panel_bg,
523
+ fg=t.fg_muted,
524
+ font=(FONT_UI, 8),
525
+ width=6,
526
+ anchor="w",
527
+ ).pack(side="left")
528
+ tk.Entry(
529
+ from_f,
530
+ textvariable=self._conv_from,
531
+ bg=t.input_bg,
532
+ fg=t.fg,
533
+ insertbackground=t.cursor,
534
+ relief="flat",
535
+ bd=0,
536
+ highlightthickness=1,
537
+ highlightbackground=t.border,
538
+ font=(FONT_MONO, 10),
539
+ width=8,
540
+ ).pack(side="left", padx=4)
541
+
542
+ to_f = tk.Frame(parent, bg=t.panel_bg)
543
+ to_f.pack(fill="x", padx=8, pady=2)
544
+ tk.Label(
545
+ to_f,
546
+ text=_t("calc.conv_to", "Para"),
547
+ bg=t.panel_bg,
548
+ fg=t.fg_muted,
549
+ font=(FONT_UI, 8),
550
+ width=6,
551
+ anchor="w",
552
+ ).pack(side="left")
553
+ tk.Entry(
554
+ to_f,
555
+ textvariable=self._conv_to,
556
+ bg=t.input_bg,
557
+ fg=t.fg,
558
+ insertbackground=t.cursor,
559
+ relief="flat",
560
+ bd=0,
561
+ highlightthickness=1,
562
+ highlightbackground=t.border,
563
+ font=(FONT_MONO, 10),
564
+ width=8,
565
+ ).pack(side="left", padx=4)
566
+
567
+ conv_btn = tk.Label(
568
+ parent,
569
+ text=_t("calc.conv_btn", "Converter →"),
570
+ bg=t.accent,
571
+ fg=t.btn_primary_fg,
572
+ font=(FONT_UI, 10),
573
+ cursor="hand2",
574
+ pady=8,
575
+ )
576
+ conv_btn.pack(fill="x", padx=8, pady=6)
577
+ conv_btn.bind("<Button-1>", lambda _: self._do_convert())
578
+
579
+ tk.Label(
580
+ parent,
581
+ textvariable=self._conv_res,
582
+ bg=t.editor_bg,
583
+ fg=t.accent,
584
+ font=(FONT_MONO, 14, "bold"),
585
+ anchor="center",
586
+ pady=10,
587
+ ).pack(fill="x", padx=8, pady=2)
588
+
589
+ tk.Label(
590
+ parent,
591
+ text=_t("calc.shortcuts", "Atalhos"),
592
+ bg=t.panel_bg,
593
+ fg=t.fg_muted,
594
+ font=(FONT_UI, 8, "bold"),
595
+ ).pack(anchor="w", padx=8, pady=(8, 2))
596
+ shortcuts = [
597
+ ("°C → °F", "°C", "°F"),
598
+ ("°F → °C", "°F", "°C"),
599
+ ("km → mi", "km", "mi"),
600
+ ("mi → km", "mi", "km"),
601
+ ("kg → lb", "kg", "lb"),
602
+ ("lb → kg", "lb", "kg"),
603
+ ]
604
+ sc_f = tk.Frame(parent, bg=t.panel_bg)
605
+ sc_f.pack(fill="x", padx=8)
606
+ for i, (label, frm, to) in enumerate(shortcuts):
607
+ r, c = divmod(i, 3)
608
+ b = tk.Label(
609
+ sc_f,
610
+ text=label,
611
+ bg=t.btn_bg,
612
+ fg=t.fg_muted,
613
+ font=(FONT_UI, 7),
614
+ cursor="hand2",
615
+ pady=4,
616
+ padx=3,
617
+ )
618
+ b.grid(row=r, column=c, sticky="nsew", padx=1, pady=1)
619
+ b.bind(
620
+ "<Button-1>",
621
+ lambda _, f=frm, to_=to: (
622
+ self._conv_from.set(f),
623
+ self._conv_to.set(to_),
624
+ ),
625
+ )
626
+ b.bind("<Enter>", lambda e, w=b: w.config(bg=t.btn_hover))
627
+ b.bind("<Leave>", lambda e, w=b: w.config(bg=t.btn_bg))
628
+ for c in range(3):
629
+ sc_f.columnconfigure(c, weight=1)
630
+
631
+ def _do_convert(self) -> None:
632
+ """Realiza conversão entre unidades."""
633
+ try:
634
+ val = float(self._conv_val.get().replace(",", "."))
635
+ frm = self._conv_from.get().strip().lower()
636
+ to = self._conv_to.get().strip().lower()
637
+
638
+ to_base: dict[str, float] = {
639
+ "km": 1000,
640
+ "m": 1,
641
+ "cm": 0.01,
642
+ "mm": 0.001,
643
+ "mi": 1609.34,
644
+ "ft": 0.3048,
645
+ "in": 0.0254,
646
+ "yd": 0.9144,
647
+ "kg": 1,
648
+ "g": 0.001,
649
+ "lb": 0.453592,
650
+ "oz": 0.0283495,
651
+ "t": 1000,
652
+ "mg": 0.000001,
653
+ }
654
+
655
+ def to_celsius(v: float, unit: str) -> float:
656
+ if unit in ("°c", "c", "celsius"):
657
+ return v
658
+ if unit in ("°f", "f", "fahrenheit"):
659
+ return (v - 32) * 5 / 9
660
+ if unit in ("k", "kelvin"):
661
+ return v - 273.15
662
+ raise ValueError(f"Unidade desconhecida: {unit}")
663
+
664
+ def from_celsius(v: float, unit: str) -> float:
665
+ if unit in ("°c", "c", "celsius"):
666
+ return v
667
+ if unit in ("°f", "f", "fahrenheit"):
668
+ return v * 9 / 5 + 32
669
+ if unit in ("k", "kelvin"):
670
+ return v + 273.15
671
+ raise ValueError(f"Unidade desconhecida: {unit}")
672
+
673
+ temp_units = {"°c", "c", "°f", "f", "k",
674
+ "celsius", "fahrenheit", "kelvin"}
675
+ if frm in temp_units or to in temp_units:
676
+ celsius = to_celsius(val, frm)
677
+ result = from_celsius(celsius, to)
678
+ elif frm in to_base and to in to_base:
679
+ result = val * to_base[frm] / to_base[to]
680
+ else:
681
+ self._conv_res.set(
682
+ _t("calc.conv_unknown", "Unidade não reconhecida"))
683
+ return
684
+
685
+ if result == int(result):
686
+ self._conv_res.set(f"{int(result)} {self._conv_to.get()}")
687
+ else:
688
+ self._conv_res.set(f"{result:.6g} {self._conv_to.get()}")
689
+ except Exception as exc:
690
+ self._conv_res.set(f"Erro: {exc}")
691
+
692
+ def _build_history(self, parent: tk.Widget, t: Any) -> None:
693
+ """Painel de histórico de cálculos."""
694
+ hdr = tk.Frame(parent, bg=t.panel_bg)
695
+ hdr.pack(fill="x", padx=10, pady=(10, 0))
696
+
697
+ tk.Label(
698
+ hdr,
699
+ text=_t("calc.history", "Histórico"),
700
+ bg=t.panel_bg,
701
+ fg=t.fg,
702
+ font=(FONT_UI, 10, "bold"),
703
+ ).pack(side="left")
704
+
705
+ clear_lbl = tk.Label(
706
+ hdr,
707
+ text=_t("calc.clear_hist", "Limpar"),
708
+ bg=t.panel_bg,
709
+ fg=t.t_link,
710
+ font=(FONT_UI, 8),
711
+ cursor="hand2",
712
+ )
713
+ clear_lbl.pack(side="right")
714
+ clear_lbl.bind("<Button-1>", lambda _: self._clear_history())
715
+
716
+ tk.Frame(parent, bg=t.border, height=1).pack(fill="x", padx=10, pady=4)
717
+
718
+ wrap = tk.Frame(parent, bg=t.panel_bg)
719
+ wrap.pack(fill="both", expand=True, padx=10, pady=(0, 10))
720
+
721
+ self._hist_canvas = tk.Canvas(
722
+ wrap, bg=t.panel_bg, highlightthickness=0)
723
+ vsb = ttk.Scrollbar(wrap, orient="vertical",
724
+ command=self._hist_canvas.yview)
725
+ vsb.pack(side="right", fill="y")
726
+ self._hist_canvas.config(yscrollcommand=vsb.set)
727
+ self._hist_canvas.pack(fill="both", expand=True)
728
+
729
+ self._hist_inner = tk.Frame(self._hist_canvas, bg=t.panel_bg)
730
+ self._hist_win = self._hist_canvas.create_window(
731
+ (0, 0), window=self._hist_inner, anchor="nw"
732
+ )
733
+ self._hist_inner.bind("<Configure>", self._on_hist_configure)
734
+ self._hist_canvas.bind("<Configure>", self._on_hist_configure)
735
+
736
+ for ev in ("<MouseWheel>", "<Button-4>", "<Button-5>"):
737
+ self._hist_canvas.bind(ev, self._on_scroll)
738
+ self._hist_inner.bind(ev, self._on_scroll)
739
+
740
+ self._refresh_history()
741
+
742
+ def _switch_mode(self, mode: str) -> None:
743
+ self._mode.set(mode)
744
+ self._sci_frame.pack_forget()
745
+ self._conv_frame.pack_forget()
746
+ if mode == "sci":
747
+ self._btn_frame.pack_forget()
748
+ self._sci_frame.pack(fill="both", expand=True,
749
+ padx=10, pady=(0, 10))
750
+ self._build_basic_buttons(self._left, self._tmgr.theme)
751
+ self._sci_frame.pack(fill="x", padx=10, pady=(0, 10))
752
+ self._mode_badge.pack()
753
+ elif mode == "conv":
754
+ self._btn_frame.pack_forget()
755
+ self._conv_frame.pack(fill="both", expand=True)
756
+ self._mode_badge.pack_forget()
757
+ else:
758
+ self._btn_frame.pack(fill="both", expand=True,
759
+ padx=10, pady=(0, 10))
760
+ self._mode_badge.pack_forget()
761
+
762
+ def _on_hist_configure(self, _e: Any = None) -> None:
763
+ self._hist_canvas.config(scrollregion=self._hist_canvas.bbox("all"))
764
+ self._hist_canvas.itemconfig(
765
+ self._hist_win, width=self._hist_canvas.winfo_width()
766
+ )
767
+
768
+ def _on_scroll(self, e: Any) -> None:
769
+ if e.delta:
770
+ self._hist_canvas.yview_scroll(-1 * (e.delta // 120), "units")
771
+ elif e.num == 4:
772
+ self._hist_canvas.yview_scroll(-1, "units")
773
+ else:
774
+ self._hist_canvas.yview_scroll(1, "units")
775
+
776
+ def _refresh_history(self) -> None:
777
+ t = self._tmgr.theme
778
+ for w in self._hist_inner.winfo_children():
779
+ w.destroy()
780
+
781
+ items = list(reversed(self._history[-50:]))
782
+ if not items:
783
+ tk.Label(
784
+ self._hist_inner,
785
+ text=_t(
786
+ "calc.hist_empty",
787
+ "Nenhum cálculo ainda.\nDigite uma expressão e pressione Enter.",
788
+ ),
789
+ bg=t.panel_bg,
790
+ fg=t.fg_muted,
791
+ font=(FONT_UI, 9),
792
+ justify="center",
793
+ ).pack(pady=30)
794
+ return
795
+
796
+ for item in items:
797
+ row = tk.Frame(
798
+ self._hist_inner,
799
+ bg=t.panel_bg,
800
+ highlightthickness=1,
801
+ highlightbackground=t.border,
802
+ )
803
+ row.pack(fill="x", pady=2, padx=1)
804
+
805
+ tk.Frame(row, bg=t.accent, width=3).pack(side="left", fill="y")
806
+
807
+ content = tk.Frame(row, bg=t.panel_bg)
808
+ content.pack(side="left", fill="both", expand=True)
809
+
810
+ expr_lbl = tk.Label(
811
+ content,
812
+ text=item.get("expr", ""),
813
+ bg=t.panel_bg,
814
+ fg=t.fg_muted,
815
+ font=(FONT_MONO, 8),
816
+ anchor="w",
817
+ cursor="hand2",
818
+ )
819
+ expr_lbl.pack(fill="x", padx=6, pady=(5, 0))
820
+ expr_lbl.bind(
821
+ "<Button-1>",
822
+ lambda _, e=item["expr"]: (
823
+ self._expr_var.set(e),
824
+ self._expr_entry.focus_set(),
825
+ ),
826
+ )
827
+
828
+ res_lbl = tk.Label(
829
+ content,
830
+ text=f"= {item.get('result', '')}",
831
+ bg=t.panel_bg,
832
+ fg=t.fg,
833
+ font=(FONT_MONO, 11, "bold"),
834
+ anchor="e",
835
+ )
836
+ res_lbl.pack(fill="x", padx=6, pady=(0, 5))
837
+
838
+ for w in (row, content, expr_lbl, res_lbl):
839
+ w.bind(
840
+ "<Enter>", lambda e, r=row: r.config(
841
+ highlightbackground=t.accent)
842
+ )
843
+ w.bind(
844
+ "<Leave>", lambda e, r=row: r.config(
845
+ highlightbackground=t.border)
846
+ )
847
+
848
+ def _evaluate(self) -> None:
849
+ expr = self._expr_var.get().strip()
850
+ if not expr:
851
+ return
852
+
853
+ safe_expr = (
854
+ expr.replace("×", "*")
855
+ .replace("÷", "/")
856
+ .replace("^", "**")
857
+ .replace("√", "sqrt")
858
+ )
859
+ safe_expr = _decimal_commas_to_points(safe_expr)
860
+
861
+ ns = dict(self._SAFE_BUILTINS)
862
+ if self._last_result is not None:
863
+ ns["ans"] = self._last_result
864
+ ns["_"] = self._last_result
865
+
866
+ try:
867
+ result = _safe_eval(safe_expr, ns)
868
+ result_str = self._format_result(result)
869
+ self._last_result = (
870
+ float(result) if isinstance(result, (int, float)) else None
871
+ )
872
+ self._result_var.set(result_str)
873
+
874
+ entry: dict = {"expr": expr, "result": result_str, "note": ""}
875
+ self._history.append(entry)
876
+ _save_history(self._history)
877
+ self._refresh_history()
878
+ self._history_idx = -1
879
+
880
+ except ZeroDivisionError:
881
+ self._result_var.set(
882
+ _t("calc.div_zero", "Divisão por zero")
883
+ )
884
+ except (ValueError, TypeError, OverflowError, ArithmeticError, SyntaxError) as exc:
885
+ self._result_var.set(f"Erro: {type(exc).__name__}")
886
+
887
+ def _format_result(self, result: Any) -> str:
888
+ if isinstance(result, float):
889
+ if (
890
+ result == int(result)
891
+ and not math.isinf(result)
892
+ and not math.isnan(result)
893
+ ) and abs(result) < 1e15:
894
+ return str(int(result))
895
+ return f"{result:.10g}"
896
+ return str(result)
897
+
898
+ def _btn_action(self, action: str) -> None:
899
+ cur = self._expr_var.get()
900
+ if action == "=":
901
+ self._evaluate()
902
+ elif action == "c":
903
+ self._expr_var.set("")
904
+ self._result_var.set("0")
905
+ elif action == "ce":
906
+ self._result_var.set("0")
907
+ elif action == "bs":
908
+ self._expr_var.set(cur[:-1])
909
+ elif action == "neg":
910
+ try:
911
+ val = float(self._result_var.get().replace(",", "."))
912
+ self._expr_var.set(str(-val))
913
+ except ValueError:
914
+ self._expr_var.set(f"-({cur})" if cur else "")
915
+ else:
916
+ self._expr_var.set(cur + action)
917
+ self._expr_entry.icursor("end")
918
+
919
+ def _insert_snippet(self, snippet: str) -> None:
920
+ cur = self._expr_var.get()
921
+ if snippet in ("pi", "e"):
922
+ self._expr_var.set(cur + snippet)
923
+ elif "x" in snippet:
924
+ x_val = self._result_var.get() if self._result_var.get() != "0" else cur
925
+ filled = snippet.replace("x", f"({x_val})")
926
+ self._expr_var.set(filled)
927
+ else:
928
+ self._expr_var.set(cur + snippet)
929
+ self._expr_entry.icursor("end")
930
+ self._expr_entry.focus_set()
931
+
932
+ def _history_up(self, _e: Any = None) -> None:
933
+ calc_hist = [h["expr"] for h in self._history]
934
+ if not calc_hist:
935
+ return
936
+ self._history_idx = max(
937
+ 0, (self._history_idx if self._history_idx >=
938
+ 0 else len(calc_hist)) - 1
939
+ )
940
+ self._expr_var.set(calc_hist[self._history_idx])
941
+
942
+ def _history_down(self, _e: Any = None) -> None:
943
+ calc_hist = [h["expr"] for h in self._history]
944
+ if self._history_idx < 0:
945
+ return
946
+ self._history_idx += 1
947
+ if self._history_idx >= len(calc_hist):
948
+ self._history_idx = -1
949
+ self._expr_var.set("")
950
+ else:
951
+ self._expr_var.set(calc_hist[self._history_idx])
952
+
953
+ def _clear_history(self) -> None:
954
+ self._history.clear()
955
+ _save_history(self._history)
956
+ self._refresh_history()
957
+
958
+ def _mem_update_label(self) -> None:
959
+ self._memory_lbl.config(text=f"M: {self._format_result(self._memory)}")
960
+
961
+ def _mem_clear(self) -> None:
962
+ self._memory = 0.0
963
+ self._mem_update_label()
964
+
965
+ def _mem_recall(self) -> None:
966
+ self._expr_var.set(self._expr_var.get() +
967
+ self._format_result(self._memory))
968
+
969
+ def _mem_add(self) -> None:
970
+ with contextlib.suppress(ValueError):
971
+ self._memory += float(self._result_var.get())
972
+ self._mem_update_label()
973
+
974
+ def _mem_sub(self) -> None:
975
+ with contextlib.suppress(ValueError):
976
+ self._memory -= float(self._result_var.get())
977
+ self._mem_update_label()
978
+
979
+ def _mem_store(self) -> None:
980
+ with contextlib.suppress(ValueError):
981
+ self._memory = float(self._result_var.get())
982
+ self._mem_update_label()