mathshuttle 0.8.0__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.
mathshuttle/theme.py ADDED
@@ -0,0 +1,127 @@
1
+ """The look of the windows: the Sun Valley ttk theme (the Windows 11 style, light and dark) on Windows
2
+ and Linux, the native Aqua look on macOS.
3
+
4
+ The theme's Tcl files and pictures are in ``sv_theme/`` (sv-ttk 2.6.1 by rdbende, MIT licence, see
5
+ ``sv_theme/LICENSE``); no Python package is needed for it. Light or dark follows the system
6
+ (Windows: *Choose your app mode*), or the ``theme`` entry of the settings / the environment variable
7
+ ``MATHSHUTTLE_THEME`` (``light``, ``dark``, or ``native`` for Tk's own look).
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import ctypes
12
+ import os
13
+ import sys
14
+ import tkinter as tk
15
+ from tkinter import font as tkfont
16
+ from tkinter import ttk
17
+ from typing import Dict, Optional
18
+
19
+ _DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sv_theme")
20
+ CHOICES = ("system", "light", "dark", "native")
21
+
22
+ # colours of the classic Tk widgets (text panes, the preview strip, lists) to go with the ttk theme
23
+ PALETTES: Dict[str, Dict[str, str]] = {
24
+ "light": {"bg": "#fafafa", "fg": "#1c1c1c", "field": "#ffffff", "border": "#d9d9d9", "focus": "#005fb8",
25
+ "muted": "#5c5c5c", "error": "#b00020", "selbg": "#2f60d8", "selfg": "#ffffff",
26
+ "preview": "#ffffff", "toast": "#202124"},
27
+ "dark": {"bg": "#1c1c1c", "fg": "#fafafa", "field": "#2b2b2b", "border": "#3d3d3d", "focus": "#57c8ff",
28
+ "muted": "#a8a8a8", "error": "#ff99a4", "selbg": "#2f60d8", "selfg": "#ffffff",
29
+ # LaTeX draws black on white: the preview stays a sheet of paper
30
+ "preview": "#ffffff", "toast": "#2b2b2b"},
31
+ "native": {"bg": "", "fg": "", "field": "white", "border": "#c8c8c8", "focus": "#3b82f6",
32
+ "muted": "#555555", "error": "#b00020", "selbg": "", "selfg": "",
33
+ "preview": "white", "toast": "#202124"},
34
+ }
35
+
36
+
37
+ def system_prefers_dark() -> bool:
38
+ """Windows: the *app mode* of Settings > Personalisation > Colours; elsewhere light."""
39
+ if sys.platform != "win32":
40
+ return False
41
+ try:
42
+ import winreg
43
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
44
+ r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize") as key:
45
+ return winreg.QueryValueEx(key, "AppsUseLightTheme")[0] == 0
46
+ except OSError:
47
+ return False
48
+
49
+
50
+ def resolve(choice: Optional[str] = None) -> str:
51
+ """"light", "dark" or "native" for a setting (None / "system": the environment variable, then the
52
+ system's app mode). macOS keeps its native look: Aqua follows the system's dark mode by itself."""
53
+ env = os.environ.get("MATHSHUTTLE_THEME", "").strip().lower()
54
+ if env in CHOICES[1:]:
55
+ choice = env
56
+ if choice == "native" or sys.platform == "darwin":
57
+ return "native"
58
+ if choice in ("light", "dark"):
59
+ return choice
60
+ return "dark" if system_prefers_dark() else "light"
61
+
62
+
63
+ def apply(root: tk.Tk, choice: Optional[str] = None) -> str:
64
+ """Give `root` (and the windows it opens) the look; returns "light", "dark" or "native"."""
65
+ mode = resolve(choice)
66
+ if mode == "native":
67
+ return mode
68
+ try:
69
+ if not getattr(root, "_sv_loaded", False):
70
+ root.tk.call("source", os.path.join(_DIR, "sv.tcl"))
71
+ root._sv_loaded = True # type: ignore[attr-defined]
72
+ _point_sizes(root)
73
+ ttk.Style(root).theme_use("sun-valley-" + mode)
74
+ # the theme sets the window colours on <<ThemeChanged>>, which Tk sends to a window that is
75
+ # not shown yet only later, if at all: now, before the widgets are made
76
+ root.tk.call("configure_colors")
77
+ except tk.TclError: # a Tk without PNG pictures, missing files: Tk's own look still works
78
+ return "native"
79
+ return mode
80
+
81
+
82
+ def _point_sizes(root: tk.Tk) -> None:
83
+ """The theme gives its fonts in pixels, which are small on a 125 % or 150 % screen: points, which
84
+ Tk scales with the screen, of the same size at 100 %."""
85
+ for name, points in (("SunValleyCaptionFont", 9), ("SunValleyBodyFont", 10), ("SunValleyBodyStrongFont", 10),
86
+ ("SunValleyBodyLargeFont", 13), ("SunValleySubtitleFont", 15)):
87
+ try:
88
+ tkfont.nametofont(name, root=root).configure(size=points)
89
+ except (tk.TclError, TypeError):
90
+ try:
91
+ root.tk.call("font", "configure", name, "-size", points)
92
+ except tk.TclError:
93
+ pass
94
+
95
+
96
+ def palette(mode: str) -> Dict[str, str]:
97
+ return PALETTES.get(mode, PALETTES["native"])
98
+
99
+
100
+ def style_text(widget: tk.Widget, mode: str) -> None:
101
+ """A text pane (or a list) in the colours of the theme, with a thin border that shows the focus."""
102
+ p = palette(mode)
103
+ options = {"relief": "flat", "borderwidth": 0, "highlightthickness": 1,
104
+ "highlightbackground": p["border"], "highlightcolor": p["focus"]}
105
+ if mode != "native":
106
+ options.update(background=p["field"], foreground=p["fg"], insertbackground=p["fg"],
107
+ selectbackground=p["selbg"], selectforeground=p["selfg"],
108
+ inactiveselectbackground=p["selbg"])
109
+ known = set(widget.keys()) # a Listbox has no insertion cursor, for one
110
+ widget.configure(**{k: v for k, v in options.items() if k in known})
111
+
112
+
113
+ def dark_title_bar(window: tk.Misc, dark: bool) -> None:
114
+ """Windows 10 (20H1) and 11: a dark title bar to go with a dark window."""
115
+ if sys.platform != "win32":
116
+ return
117
+ try:
118
+ window.update_idletasks()
119
+ hwnd = ctypes.windll.user32.GetParent(window.winfo_id()) or window.winfo_id()
120
+ value = ctypes.c_int(1 if dark else 0)
121
+ # DWMWA_USE_IMMERSIVE_DARK_MODE: 20 (19 before Windows 10 20H1)
122
+ for attribute in (20, 19):
123
+ if ctypes.windll.dwmapi.DwmSetWindowAttribute(ctypes.c_void_p(hwnd), attribute, ctypes.byref(value),
124
+ ctypes.sizeof(value)) == 0:
125
+ break
126
+ except (AttributeError, OSError):
127
+ pass