Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions src/addon/colors.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Any, Optional, Tuple, List, Dict
import re

from anki.hooks import wrap
import aqt
Expand All @@ -13,6 +14,22 @@

conf = ConfigManager()

# Sourced from aqt.browser.table.backend_color_to_aqt_color
# ACCENT_CARD and ACCENT_NOTE are passed to ThemeManager.qcolor, which doesn't support #RGBA
ARGB_ONLY_ENTRIES = (
"STATE_MARKED",
"STATE_SUSPENDED",
"STATE_BURIED",
"FLAG_1",
"FLAG_2",
"FLAG_3",
"FLAG_4",
"FLAG_5",
"FLAG_6",
"FLAG_7",
"ACCENT_CARD",
"ACCENT_NOTE"
)

# ReColor Python Colors
def recolor_python() -> None:
Expand Down Expand Up @@ -41,6 +58,25 @@ def hex_with_alpha_to_rgba(hex_color: str) -> str:
return hex_color


RGBA_RE = re.compile(r"\((\d+),\s*(\d+),\s*(\d+),\s*(\d+\.*\d+?)\)\s*")

def hex_with_alpha_to_argb(hex_color: str) -> str:
# ARGB_ONLY_ENTRIES get passed directly into a QColor, so they need to be of RGB hex format
# QColor also takes #ARGB, so prepend the alpha instead of removing it (https://doc.qt.io/qt-6/qcolor.html#fromString)
if hex_color.startswith("#") and len(hex_color) == 9:
# assume #RGBA, convert to #ARGB
return "#" + hex_color[7:9] + hex_color[1:7]
elif hex_color.startswith("rgba") and (m := re.match(RGBA_RE, hex_color[4:])):
# convert rgba(...) to #ARGB
r = int(m.group(1))
g = int(m.group(2))
b = int(m.group(3))
a = int(255 * float(m.group(4)))
return f"#{a:02x}{r:02x}{g:02x}{b:02x}"
# fallback to original
return hex_color


def replace_color(
color_entries: Dict[str, List[str]],
anki_name: str,
Expand All @@ -50,8 +86,9 @@ def replace_color(
addon_name = anki_name
if (anki_color := getattr(aqt.colors, anki_name, None)) is not None:
color_entry = color_entries[addon_name]
anki_color["light"] = hex_with_alpha_to_rgba(color_entry[1])
anki_color["dark"] = hex_with_alpha_to_rgba(color_entry[2])
color_map_fn = hex_with_alpha_to_rgba if anki_name not in ARGB_ONLY_ENTRIES else hex_with_alpha_to_argb
anki_color["light"] = color_map_fn(color_entry[1])
anki_color["dark"] = color_map_fn(color_entry[2])
setattr(aqt.colors, anki_name, anki_color)


Expand Down