Repository navigation
Expand file tree
/
Copy paththeme.py
More file actions
480 lines (425 loc) · 21.7 KB
/
Copy paththeme.py
File metadata and controls
480 lines (425 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
"""
theme.py - Theme support.
Copyright (c) EDCD, All Rights Reserved
Licensed under the GNU General Public License v2 or later.
See LICENSE file.
Because of various ttk limitations this app is an unholy mix of Tk and ttk widgets.
So can't use ttk's theme support. So have to change colors manually.
"""
import os
import sys
import tkinter as tk
from tkinter import font as tk_font
from tkinter import ttk
from typing import Any
from collections.abc import Callable
from l10n import translations as tr
from config import config
from EDMCLogging import get_main_logger
from ttkHyperlinkLabel import HyperlinkLabel
logger = get_main_logger()
if __debug__:
from traceback import print_exc
# Can't use Case matching here due to bug in flake8-naming
if sys.platform == "win32":
import ctypes
from ctypes.wintypes import DWORD, LPCVOID, LPCWSTR
import win32gui
import win32con
AddFontResourceEx = ctypes.windll.gdi32.AddFontResourceExW
AddFontResourceEx.argtypes = [LPCWSTR, DWORD, LPCVOID]
AddFontResourceEx.restype = ctypes.c_int
FR_PRIVATE = 0x10
FR_NOT_ENUM = 0x20
font_path = str(config.respath_path / 'EUROCAPS.TTF')
if not AddFontResourceEx(font_path, FR_PRIVATE, None):
raise RuntimeError(f"Failed to load font {font_path}")
dpy = None
elif sys.platform == "linux":
from ctypes import POINTER, Structure, byref, c_char_p, c_int, c_long, c_uint, c_ulong, c_void_p, cdll
XID = c_ulong
Window = XID
Atom = c_ulong
Display = c_void_p
PropModeReplace = 0
PropModePrepend = 1
PropModeAppend = 2
MWM_HINTS_FUNCTIONS = 1 << 0
MWM_HINTS_DECORATIONS = 1 << 1
MWM_HINTS_INPUT_MODE = 1 << 2
MWM_HINTS_STATUS = 1 << 3
MWM_FUNC_ALL = 1 << 0
MWM_FUNC_RESIZE = 1 << 1
MWM_FUNC_MOVE = 1 << 2
MWM_FUNC_MINIMIZE = 1 << 3
MWM_FUNC_MAXIMIZE = 1 << 4
MWM_FUNC_CLOSE = 1 << 5
MWM_DECOR_ALL = 1 << 0
MWM_DECOR_BORDER = 1 << 1
MWM_DECOR_RESIZEH = 1 << 2
MWM_DECOR_TITLE = 1 << 3
MWM_DECOR_MENU = 1 << 4
MWM_DECOR_MINIMIZE = 1 << 5
MWM_DECOR_MAXIMIZE = 1 << 6
class MotifWmHints(Structure):
"""MotifWmHints structure."""
_fields_ = [
('flags', c_ulong),
('functions', c_ulong),
('decorations', c_ulong),
('input_mode', c_long),
('status', c_ulong),
]
# workaround for https://github.com/EDCD/EDMarketConnector/issues/568
if not os.getenv("EDMC_NO_UI"):
try:
xlib = cdll.LoadLibrary('libX11.so.6')
XInternAtom = xlib.XInternAtom
XInternAtom.argtypes = [POINTER(Display), c_char_p, c_int]
XInternAtom.restype = Atom
XChangeProperty = xlib.XChangeProperty
XChangeProperty.argtypes = [POINTER(Display), Window, Atom, Atom, c_int,
c_int, POINTER(MotifWmHints), c_int]
XChangeProperty.restype = c_int
XFlush = xlib.XFlush
XFlush.argtypes = [POINTER(Display)]
XFlush.restype = c_int
XOpenDisplay = xlib.XOpenDisplay
XOpenDisplay.argtypes = [c_char_p]
XOpenDisplay.restype = POINTER(Display)
XQueryTree = xlib.XQueryTree
XQueryTree.argtypes = [POINTER(Display), Window, POINTER(Window),
POINTER(Window), POINTER(Window), POINTER(c_uint)]
XQueryTree.restype = c_int
dpy = xlib.XOpenDisplay(None)
if not dpy:
raise Exception("Can't find your display, can't continue")
motif_wm_hints_property = XInternAtom(dpy, b'_MOTIF_WM_HINTS', False)
motif_wm_hints_normal = MotifWmHints(
MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS,
MWM_FUNC_RESIZE | MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE | MWM_FUNC_CLOSE,
MWM_DECOR_BORDER | MWM_DECOR_RESIZEH | MWM_DECOR_TITLE | MWM_DECOR_MENU | MWM_DECOR_MINIMIZE,
0, 0
)
motif_wm_hints_dark = MotifWmHints(
MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS,
MWM_FUNC_RESIZE | MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE | MWM_FUNC_CLOSE,
0, 0, 0
)
except Exception:
if __debug__:
print_exc()
dpy = None
else:
dpy = None
else:
dpy = None
class _Theme:
# Enum ? Remember these are, probably, based on 'value' of a tk
# RadioButton set. Looking in prefs.py, they *appear* to be hard-coded
# there as well.
THEME_DEFAULT = 0
THEME_DARK = 1
THEME_TRANSPARENT = 2
def __init__(self) -> None:
self.active: int | None = None # Starts out with no theme
self.minwidth: int | None = None
self.widgets: dict[tk.Widget | tk.BitmapImage, set[str]] = {}
self.widgets_pair: list[tuple[tuple[Any, ...], dict[str, Any]]] = []
self.defaults: dict[str, Any] = {}
self.current: dict[str, Any] = {}
self.default_ui_scale: float | None = None # None == not yet known
self.startup_ui_scale: int | None = None
def register(self, widget: tk.Widget | tk.BitmapImage) -> None: # noqa: CCR001
# Note widget and children for later application of a theme. Note if
# the widget has explicit fg or bg attributes.
if not isinstance(widget, (tk.Widget, tk.BitmapImage)):
raise TypeError(f'Expected widget, got {type(widget)}')
if not self.defaults:
self.defaults = {
'fg': tk.Label()['foreground'], # SystemButtonText, systemButtonText
'bg': tk.Label()['background'], # SystemButtonFace, White
'font': tk.Label()['font'], # TkDefaultFont
'bitmapfg': tk.BitmapImage()['foreground'], # '-foreground {} {} #000000 #000000'
'bitmapbg': tk.BitmapImage()['background'], # '-background {} {} {} {}'
'entryfg': tk.Entry()['foreground'], # SystemWindowText, Black
'entrybg': tk.Entry()['background'], # SystemWindow, systemWindowBody
'entryfont': tk.Entry()['font'], # TkTextFont
'frame': tk.Frame()['background'], # SystemButtonFace, systemWindowBody
'menufg': tk.Menu()['foreground'], # SystemMenuText,
'menubg': tk.Menu()['background'], # SystemMenu,
'menufont': tk.Menu()['font'], # TkTextFont
}
if widget not in self.widgets:
# No general way to tell whether the user has overridden, so compare against widget-type specific defaults
attribs = set()
match widget:
case tk.BitmapImage():
if widget['foreground'] not in ('', self.defaults['bitmapfg']):
attribs.add('fg')
if widget['background'] not in ('', self.defaults['bitmapbg']):
attribs.add('bg')
case tk.Entry() | ttk.Entry():
if widget['foreground'] not in ('', self.defaults['entryfg']):
attribs.add('fg')
if widget['background'] not in ('', self.defaults['entrybg']):
attribs.add('bg')
if 'font' in widget.keys() and str(widget['font']) not in ('', self.defaults['entryfont']):
attribs.add('font')
case tk.Canvas() | tk.Frame() | ttk.Frame():
if (('background' in widget.keys() or isinstance(widget, tk.Canvas))
and widget['background'] not in ('', self.defaults['frame'])):
attribs.add('bg')
case HyperlinkLabel():
pass
case tk.Menu():
if widget['foreground'] not in ('', self.defaults['menufg']):
attribs.add('fg')
if widget['background'] not in ('', self.defaults['menubg']):
attribs.add('bg')
if widget['font'] not in ('', self.defaults['menufont']):
attribs.add('font')
case _:
w_keys = widget.keys() if hasattr(widget, 'keys') else []
if 'foreground' in w_keys and widget['foreground'] not in ('', self.defaults['fg']):
attribs.add('fg')
if 'background' in w_keys and widget['background'] not in ('', self.defaults['bg']):
attribs.add('bg')
if 'font' in w_keys and widget['font'] not in ('', self.defaults['font']):
attribs.add('font')
self.widgets[widget] = attribs
if isinstance(widget, (tk.Frame, ttk.Frame)):
for child in widget.winfo_children():
self.register(child) # type: ignore
def register_alternate(self, pair: tuple, gridopts: dict) -> None:
self.widgets_pair.append((pair, gridopts))
def button_bind(self, widget: tk.Widget, command: Callable, image: tk.BitmapImage | None = None) -> None:
widget.bind('<Button-1>', command)
widget.bind('<Enter>', lambda e: self._enter(e, widget=widget, image=image))
widget.bind('<Leave>', lambda e: self._leave(e, widget=widget, image=image))
def _enter(self, event: tk.Event, widget: tk.Widget | None = None, # noqa: CCR001
image: tk.BitmapImage | None = None) -> None:
"""Handle mouse entering a widget or image."""
if widget is not None:
# Only apply foreground/background if the widget supports them
config_keys = widget.keys() if hasattr(widget, 'keys') else []
kwargs = {}
if 'foreground' in config_keys and self.current.get('highlightforeground'):
kwargs['foreground'] = self.current['highlightforeground']
if 'background' in config_keys and self.current.get('highlightbackground'):
kwargs['background'] = self.current['highlightbackground']
if kwargs:
widget.configure(**kwargs)
if image is not None and not isinstance(image, tk.PhotoImage):
# PhotoImage cannot be configured with fg/bg, skip safely
try:
config_keys = image.keys() if hasattr(image, 'keys') else []
kwargs = {}
if 'foreground' in config_keys and self.current.get('highlightforeground'):
kwargs['foreground'] = self.current['highlightforeground']
if 'background' in config_keys and self.current.get('highlightbackground'):
kwargs['background'] = self.current['highlightbackground']
if kwargs:
image.configure(**kwargs)
except tk.TclError:
# silently ignore unsupported image types
pass
def _leave(self, event: tk.Event, widget: tk.Widget | None = None, # noqa: CCR001
image: tk.BitmapImage | None = None) -> None:
"""Handle mouse leaving a widget or image."""
if widget is not None:
config_keys = widget.keys() if hasattr(widget, 'keys') else []
kwargs = {}
if 'foreground' in config_keys and self.current.get('foreground'):
kwargs['foreground'] = self.current['foreground']
if 'background' in config_keys and self.current.get('background'):
kwargs['background'] = self.current['background']
if kwargs:
widget.configure(**kwargs)
if image is not None and not isinstance(image, tk.PhotoImage):
# Skip PhotoImage objects; safely handle other types
try:
config_keys = image.keys() if hasattr(image, 'keys') else []
kwargs = {}
if 'foreground' in config_keys and self.current.get('foreground'):
kwargs['foreground'] = self.current['foreground']
if 'background' in config_keys and self.current.get('background'):
kwargs['background'] = self.current['background']
if kwargs:
image.configure(**kwargs)
except tk.TclError:
pass
# Set up colors
def _colors(self, root: tk.Tk, theme: int) -> None:
style = ttk.Style()
if sys.platform == 'linux':
style.theme_use('clam')
# Default dark theme colors
if not config.get_str('dark_text'):
config.set('dark_text', '#ff8000') # "Tangerine" in OSX color picker
if not config.get_str('dark_highlight'):
config.set('dark_highlight', 'white')
match theme:
case self.THEME_DEFAULT:
self.current = {
'background': style.lookup('TLabel', 'background'),
'foreground': style.lookup('TLabel', 'foreground'),
'activebackground': 'SystemHighlight' if sys.platform == 'win32' else style.lookup('TLabel',
'background',
['active']),
'activeforeground': 'SystemHighlightText' if sys.platform == 'win32' else style.lookup('TLabel',
'foreground',
['active']),
'disabledforeground': style.lookup('TLabel', 'foreground', ['disabled']),
'highlight': 'blue',
'font': 'TkDefaultFont',
}
case _:
r, g, b = root.winfo_rgb(config.get_str('dark_text'))
# Font only supports Latin 1 / Supplement / Extended, and a
# few General Punctuation and Mathematical Operators
# LANG: Label for commander name in main window
use_euro_caps = theme > 1 and not (0x250 < ord(tr.tl('Cmdr')[0]) < 0x3000)
chosen_font = tk_font.Font(family='Euro Caps', size=10,
weight=tk_font.NORMAL) if use_euro_caps else 'TkDefaultFont'
self.current = {
'background': 'grey4',
'foreground': config.get_str('dark_text'),
'activebackground': config.get_str('dark_text'),
'activeforeground': 'grey4',
'disabledforeground': f'#{int(r / 384):02x}{int(g / 384):02x}{int(b / 384):02x}',
'highlight': config.get_str('dark_highlight'),
'font': chosen_font,
}
def update(self, widget: tk.Widget) -> None:
"""
Apply current theme to a widget and its children.
Also, register it for future updates.
:param widget: Target widget.
"""
if not isinstance(widget, (tk.Widget, tk.BitmapImage)):
raise TypeError(f'Expected widget, got {type(widget)}')
if not self.current:
return # No need to call this for widgets created in plugin_app()
self.register(widget)
self._update_widget(widget)
if isinstance(widget, (tk.Frame, ttk.Frame)):
for child in widget.winfo_children():
self._update_widget(child) # type: ignore
# Apply current theme to a single widget
def _update_widget(self, widget: tk.Widget | tk.BitmapImage) -> None: # noqa: CCR001
if widget not in self.widgets:
w_class = widget.winfo_class() if isinstance(widget, tk.Widget) else ''
w_keys = widget.keys() if isinstance(widget, tk.Widget) else []
w_text = widget["text"] if "text" in w_keys else ""
raise ValueError(f'{w_class} {widget} "{w_text}"')
attribs = self.widgets.get(widget, set())
try:
match widget:
case tk.BitmapImage():
if 'fg' not in attribs:
widget['foreground'] = self.current['foreground']
if 'bg' not in attribs:
widget['background'] = self.current['background']
case _ if 'cursor' in widget.keys() and str(widget['cursor']) not in ('', 'arrow'):
# Hack - highlight widgets like HyperlinkLabel with a non-default cursor
if 'fg' not in attribs:
widget['foreground'] = self.current['highlight']
if 'insertbackground' in widget.keys(): # tk.Entry
widget['insertbackground'] = self.current['foreground']
if 'bg' not in attribs:
widget['background'] = self.current['background']
if 'highlightbackground' in widget.keys(): # tk.Entry
widget['highlightbackground'] = self.current['background']
if 'font' not in attribs:
widget['font'] = self.current['font']
case _ if 'activeforeground' in widget.keys():
# e.g. tk.Button, tk.Label, tk.Menu
if 'fg' not in attribs:
widget['foreground'] = self.current['foreground']
widget['activeforeground'] = self.current['activeforeground']
widget['disabledforeground'] = self.current['disabledforeground']
if 'bg' not in attribs:
widget['background'] = self.current['background']
widget['activebackground'] = self.current['activebackground']
if 'font' not in attribs:
widget['font'] = self.current['font']
case _ if 'foreground' in widget.keys():
# e.g. ttk.Label
if 'fg' not in attribs:
widget['foreground'] = self.current['foreground']
if 'bg' not in attribs:
widget['background'] = self.current['background']
if 'font' not in attribs:
widget['font'] = self.current['font']
case _ if 'background' in widget.keys() or isinstance(widget, tk.Canvas):
# e.g. Frame, Canvas
if 'bg' not in attribs:
widget['background'] = self.current['background']
widget['highlightbackground'] = self.current['disabledforeground']
except Exception:
logger.exception(f'Plugin widget issue? {widget=}')
# Apply configured theme
def apply(self, root: tk.Tk) -> None: # noqa: CCR001
theme = config.get_int('theme')
self._colors(root, theme)
# Apply colors
for widget in list(self.widgets.keys()):
if isinstance(widget, tk.Widget) and not widget.winfo_exists():
self.widgets.pop(widget) # has been destroyed
else:
self._update_widget(widget)
# Switch menus
for pair, gridopts in self.widgets_pair:
for widget in pair:
if isinstance(widget, tk.Widget):
widget.grid_remove()
if isinstance(pair[0], tk.Menu):
match theme:
case self.THEME_DEFAULT:
root['menu'] = pair[0]
case _: # Dark *or* Transparent
root['menu'] = ''
pair[theme].grid(**gridopts)
else:
pair[theme].grid(**gridopts)
if self.active == theme:
return # Don't need to mess with the window manager
self.active = theme
if sys.platform == 'win32':
root.overrideredirect(theme != self.THEME_DEFAULT)
root.attributes("-transparentcolor", 'grey4' if theme == self.THEME_TRANSPARENT else '')
root.withdraw()
root.update_idletasks() # Size and windows styles get recalculated here
hwnd = win32gui.GetParent(root.winfo_id())
win32gui.SetWindowLong(
hwnd,
win32con.GWL_STYLE,
win32gui.GetWindowLong(hwnd, win32con.GWL_STYLE) & ~win32con.WS_MAXIMIZEBOX
)
ex_style = win32con.WS_EX_APPWINDOW
if theme == self.THEME_TRANSPARENT:
ex_style |= win32con.WS_EX_LAYERED
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, ex_style)
root.deiconify()
root.wait_visibility() # need main window to be displayed before returning
else:
root.withdraw()
root.update_idletasks() # Size gets recalculated here
if dpy:
xroot, parent, children = Window(), Window(), Window()
nchildren = c_uint()
XQueryTree(dpy, root.winfo_id(), byref(xroot), byref(parent), byref(children), byref(nchildren))
wm_hints = motif_wm_hints_normal if theme == self.THEME_DEFAULT else motif_wm_hints_dark
XChangeProperty(dpy, parent, motif_wm_hints_property, motif_wm_hints_property, 32, PropModeReplace,
wm_hints, 5)
XFlush(dpy)
else:
root.overrideredirect(theme != self.THEME_DEFAULT)
root.deiconify()
root.wait_visibility() # need main window to be displayed before returning
if not self.minwidth:
self.minwidth = root.winfo_width() # Minimum width = width on first creation
root.minsize(self.minwidth, -1)
# Singleton
theme = _Theme()