Files
cowork-local/theme.py
T
Nam Pham Dinh ThanhandClaude Opus 5 6c68417103 refactor: chia nốt theme.py, i18n.py, usage_tracker.py — Gamma hết file vượt 400 dòng
Ba file dữ liệu cuối cùng của Gamma còn trên ngưỡng CASAN Check 2.

i18n.py  3075 -> 94
    Dict STRINGS 3.000 dòng cắt thành 10 cụm theo đúng mốc phân đoạn có sẵn
    trong file (mỗi mốc là một màn/hộp thoại), cụm nào quá dài thì cắt tiếp ở
    ranh giới khoá. i18n.py giờ chỉ gộp lại và giữ 4 hàm set_language/
    get_language/tr/on_language_changed.

    Kiểm bằng cách so với bản gốc lấy từ git: 1437 mục / 1431 khoá duy nhất
    (bản gốc vốn có 6 khoá lặp), sau khi chia vẫn 1431, KHÔNG thiếu khoá nào,
    KHÔNG thừa khoá nào, KHÔNG giá trị nào lệch. Thứ tự gộp giữ nguyên nên
    quy tắc "khoá trùng thì bản sau thắng" không đổi.

theme.py  907 -> 130
    theme_palettes.py 328  hai bảng màu Tối/Sáng + lớp Palette
    theme_qss.py      198  nửa vỏ (reset + shell)
    theme_qss_controls.py 307  nửa điều khiển (nút, ô nhập, tab, badge)

    Khuôn QSS 470 dòng cắt đôi đúng mốc `/* ---- surfaces */` của chính nó.
    Đã đối chiếu: stylesheet('dark') ra đúng 24762 ký tự y như trước — khớp
    từng byte, không phải "trông có vẻ giống".

core/usage_tracker.py  536 -> 307
    usage_cost.py      101  bảng giá, quy đổi token sang tiền, định dạng
    usage_periods.py   144  gộp theo ngày/tuần/tháng/quý, chuỗi vẽ biểu đồ
    usage_ai_report.py  56  dựng câu nhắc cho AI phân tích

HAI LẦN TỰ CẮT HỎNG, ĐỀU CÙNG MỘT GỐC
--------------------------------------
1. Cắt theo m.lineno mà quên dòng @decorator phía trên -> @dataclass của
   Palette bị bỏ lại mồ côi, "Palette() takes no arguments".
2. Đọc số dòng từ AST GỐC trong khi danh sách dòng đã bị cắt -> lần bóc thứ
   hai dùng toạ độ cũ và cắt vào giữa một chữ ký hàm.

Cả hai lộ ngay vì mỗi script tự parse lại sau khi ghi. Bài học đã áp vào cả
ba lần chia: parse lại sau mỗi lần cắt, và luôn tính cả decorator.

KẾT QUẢ CASAN CHECK 2
---------------------
    Nam       0 file vượt 400   (trước: 4, tổng 5.898 dòng)
    Hiệp      0                 (trước: 1)
    Lâm       0                 (trước: 1)
    file mới  0                 (61 file dưới presentation/ application/
                                 domain/ infrastructure/ — chưa cái nào vượt)

Gamma sạch. 23 file còn vượt đều thuộc team khác (chat_panel.py 1802,
folder_tab.py 1589, structure_graph_view.py 1034...) — cần báo lên sớm chứ
đừng để tới hạn 30/08 mới lộ.

714 test xanh. 24/24 checker qua. CASAN Check 1 sạch.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 10:57:01 +09:00

131 lines
4.5 KiB
Python

"""The app's visual system: semantic design tokens + one style sheet template.
This replaces the previous mechanism, which was two hand-written Qt style
sheets (``_DARK`` / ``_LIGHT``) that duplicated each other and hard-coded ~105
hex literals, with a single source of truth:
Palette (tokens) -> _TEMPLATE (one QSS) -> stylesheet(theme)
Rules of the system
-------------------
* **Nothing outside this module names a colour.** Widgets that paint with
``QPainter`` (charts, canvases, syntax highlighters) call :func:`palette` and
read a token. Widgets that style themselves declaratively should instead be
given an ``objectName`` and styled in ``_TEMPLATE`` below.
* **Tokens are semantic, not literal.** ``danger``/``text_muted``/``code_string``
— never ``blue``/``grey2``. Adding a theme means adding a :class:`Palette`,
not editing a style sheet.
* **No gradients, no glows.** The palette is Visual Studio Code's — "Dark
Modern" and "Light Modern", taken from the shipped theme JSON. Flat surfaces,
square-ish corners, one accent spent only on what the user acts on. Depth
comes from the surface ramp and hairline borders, not from colour. Note the
VS Code silhouette: the nav rail is *darker* than the content area, not
lighter.
Contrast is held to WCAG AA (4.5:1) for body text and for text on filled
buttons. That is why ``accent`` and ``accent_solid`` are separate tokens: on a
dark background a blue readable *as text* is too light to carry white *as a
fill*, so each role gets the tint that passes.
Four VS Code values fall below AA and are nudged just far enough to clear it —
dark line numbers (3.59:1), light faint text on the sidebar (4.28:1), light
green (4.33:1) and light amber (3.12:1). Each carries a comment naming the
original value, so the deviation is auditable rather than silent.
"""
from __future__ import annotations
from .theme_palettes import ( # noqa: F401 — giữ đường vào cũ
DARK, LIGHT, Palette, _chevron_asset, _FONT, _MONO, _PALETTES,
)
from .theme_qss import _TEMPLATE
from dataclasses import dataclass, asdict
from string import Template
# ---------------------------------------------------------------------------
# The one style sheet. `$token` placeholders are filled from the Palette above;
# use `${token}px` where a unit follows the name.
#
# Read it as a cascade: reset -> shell -> surfaces -> controls -> chrome.
# ---------------------------------------------------------------------------
def resolve_theme(theme: str) -> str:
"""Resolve ``'system'`` to ``'dark'``/``'light'`` from the OS colour scheme."""
if theme in _PALETTES:
return theme
try:
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication
app = QApplication.instance()
if app is not None:
scheme = app.styleHints().colorScheme()
return "light" if scheme == Qt.ColorScheme.Light else "dark"
except Exception:
pass
return "dark"
def palette(theme: str) -> Palette:
"""The token set for ``theme``. Painting code reads its colours from here."""
return _PALETTES[resolve_theme(theme)]
# The theme the running app is currently showing. Painting code (paintEvent,
# QSyntaxHighlighter, canvas items) reads it via current_palette() instead of
# re-reading config.json — that used to cost a file open per repaint.
_active_theme = "dark"
def set_active_theme(theme: str) -> str:
"""Record the theme the app just applied. Call this next to every
``QApplication.setStyleSheet(stylesheet(...))``. Returns the resolved name."""
global _active_theme
_active_theme = resolve_theme(theme)
return _active_theme
def current_theme() -> str:
"""The resolved theme ('dark'/'light') the app is showing right now."""
return _active_theme
def current_palette() -> Palette:
"""Tokens for the theme the app is showing right now."""
return _PALETTES[_active_theme]
def stylesheet(theme: str) -> str:
"""The application-wide Qt style sheet for ``theme``."""
p = palette(theme)
values = asdict(p)
values["chevron_down"] = _chevron_asset("down", p.text_muted)
values["chevron_up"] = _chevron_asset("up", p.text_muted)
return _TEMPLATE.substitute(values)
def role_colors(theme: str) -> dict[str, str]:
"""Conversation/graph node colours keyed by role."""
p = palette(theme)
return {
"user": p.role_user,
"assistant": p.role_assistant,
"tool": p.role_tool,
"result": p.role_result,
"error": p.role_error,
}