forked from ArduPilot/MethodicConfigurator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrontend_tkinter_base_window.py
More file actions
514 lines (396 loc) · 19.7 KB
/
frontend_tkinter_base_window.py
File metadata and controls
514 lines (396 loc) · 19.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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
"""
Base window implementation for the ArduPilot Methodic Configurator Tkinter frontend.
This module provides the BaseWindow class, which serves as a foundation for all Tkinter-based
windows in the application. It handles common functionality such as DPI scaling, theming,
window management, and icon loading.
Key Features:
- Automatic DPI scaling detection and adjustment for HiDPI displays
- Consistent theming across all application windows
- Graceful icon loading with fallback for test environments
- Utility methods for window positioning and image handling
This file is part of ArduPilot Methodic Configurator. https://github.com/ArduPilot/MethodicConfigurator
SPDX-FileCopyrightText: 2024-2026 Amilcar do Carmo Lucas <amilcar.lucas@iav.de>
SPDX-License-Identifier: GPL-3.0-or-later
"""
# https://wiki.tcl-lang.org/page/Changing+Widget+Colors
import io
import os
import tkinter as tk
# from logging import debug as logging_debug
# from logging import info as logging_info
from logging import error as logging_error
from platform import system as platform_system
from tkinter import messagebox, ttk
from typing import Optional, Union
from PIL import Image
from screeninfo import get_monitors
from ardupilot_methodic_configurator import _
from ardupilot_methodic_configurator.backend_filesystem_program_settings import ProgramSettings
from ardupilot_methodic_configurator.frontend_tkinter_font import get_safe_font_size
def is_debugging() -> bool:
"""Return True if a VS Code's debugger is attached."""
try:
# debug adapter used by VS Code Python debugger
import debugpy # noqa: PLC0415,T100 # pylint: disable=import-outside-toplevel # pyright: ignore[reportMissingImports]
except ImportError:
debugpy = None
is_connected = getattr(debugpy, "is_client_connected", None)
if not callable(is_connected):
return False
try:
return bool(is_connected())
except (TypeError, RuntimeError) as e:
logging_error(_("Error while checking debugpy connection: %s"), e)
return False
class BaseWindow:
"""
A foundational class for creating Tkinter windows in the ArduPilot Methodic Configurator.
This class provides common functionality for all application windows, including:
- DPI-aware scaling for HiDPI displays
- Consistent theming and styling
- Icon management with test environment fallbacks
- Window positioning utilities
- Image loading and display helpers
The class automatically detects whether it's running in a test environment and
adjusts behavior accordingly (e.g., skipping icon loading to avoid Tkinter issues).
Attributes:
root (Union[tk.Toplevel, tk.Tk]): The main Tkinter window object
dpi_scaling_factor (float): Detected DPI scaling factor for the display
main_frame (ttk.Frame): The primary container frame for window content
Example:
>>> # Create a main window
>>> window = BaseWindow()
>>>
>>> # Create a child window
>>> child = BaseWindow(window.root)
"""
def __init__(self, root_tk: Optional[tk.Tk] = None) -> None:
"""
Initialize a new BaseWindow instance.
Args:
root_tk (Optional[tk.Tk]): Parent window. If None, creates a new root window.
If provided, creates a Toplevel window as a child.
Note:
When root_tk is None, this creates the main application window.
When root_tk is provided, this creates a child dialog or sub-window.
"""
self.root: Union[tk.Toplevel, tk.Tk]
if root_tk:
self.root = tk.Toplevel(root_tk)
else:
self.root = tk.Tk(className="ArduPilotMethodicConfigurator")
# Only set icon for main windows, and only outside test environments
self._setup_application_icon()
# Detect DPI scaling for HiDPI support
self.dpi_scaling_factor = self._get_dpi_scaling_factor()
self.default_font_size: int = 0
# Configure theme and styling
self._setup_theme_and_styling()
# Create main container frame
self.main_frame = ttk.Frame(self.root)
self.main_frame.pack(expand=True, fill=tk.BOTH)
def _setup_application_icon(self) -> None:
"""
Set up the application icon for the main window.
This method handles icon loading with proper fallbacks for test environments
and error conditions. Icons are only loaded for main windows (not Toplevel windows)
and are skipped entirely during test runs to avoid Tkinter-related issues.
Note:
This method silently handles icon loading failures to prevent application
crashes due to missing icon files or Tkinter configuration issues.
"""
# Skip icon loading during tests to avoid tkinter issues
if os.environ.get("PYTEST_CURRENT_TEST"):
return
if is_debugging():
return # the vscode debugger can not cope with the application icon
# https://pythonassets.com/posts/window-icon-in-tk-tkinter/
try:
icon_path = ProgramSettings.application_icon_filepath()
self.root.iconphoto(True, tk.PhotoImage(file=icon_path)) # noqa: FBT003
except (tk.TclError, FileNotFoundError) as e:
# Silently ignore icon loading errors (common in test environments)
logging_error(_("Could not load application icon: %s"), e)
def _setup_theme_and_styling(self) -> None:
"""
Configure the TTK theme and create custom styles.
This method sets up the visual appearance of the application by:
- Selecting an appropriate TTK theme
- Creating custom styles for common UI elements
- Applying DPI-aware font sizing
- Ensuring readable text colors across platforms (especially Linux dark themes)
"""
# Set the theme to 'alt' for consistent appearance
style = ttk.Style()
style.theme_use("alt")
# Create custom styles with DPI-aware font sizes
self.default_font_size = get_safe_font_size()
# Warning: on linux the font size might be negative
bold_font_size = self.calculate_scaled_font_size(self.default_font_size)
style.configure("Bold.TLabel", font=("TkDefaultFont", bold_font_size, "bold"))
# Configure Entry and Combobox styles with explicit foreground colors
# This prevents white-on-white text issues on Linux with dark themes
style.configure("default_v.TEntry", fieldbackground="light blue", foreground="black")
style.configure("below_limit.TEntry", fieldbackground="orangered", foreground="black")
style.configure("above_limit.TEntry", fieldbackground="red3", foreground="white")
style.map("readonly.TCombobox", fieldbackground=[("readonly", "white")])
style.map("readonly.TCombobox", selectbackground=[("readonly", "white")])
style.map("readonly.TCombobox", selectforeground=[("readonly", "black")])
style.map("default_v.TCombobox", fieldbackground=[("readonly", "light blue")])
style.map("default_v.TCombobox", selectbackground=[("readonly", "light blue")])
style.map("default_v.TCombobox", selectforeground=[("readonly", "black")])
def _get_dpi_scaling_factor(self) -> float:
"""
Detect the DPI scaling factor for HiDPI displays.
This method uses multiple detection approaches to determine the appropriate
scaling factor for the current display configuration:
1. Calculates scaling based on actual DPI vs standard DPI (96)
2. Checks Tkinter's internal scaling factor
3. Uses the maximum of both methods for robustness
Returns:
float: The scaling factor (1.0 for standard DPI, 2.0 for 200% scaling, etc.)
Note:
Falls back to 1.0 if DPI detection fails, ensuring the application
remains functional even on systems with unusual configurations.
"""
try:
# Get the DPI from Tkinter
dpi = self.root.winfo_fpixels("1i") # pixels per inch
# Standard DPI is typically 96, so calculate scaling factor
standard_dpi = 96.0
scaling_factor = dpi / standard_dpi
# Also check the tk scaling factor which might be set by the system
tk_scaling = float(self.root.tk.call("tk", "scaling"))
# Use the maximum of both methods to ensure we catch HiDPI scaling
return max(scaling_factor, tk_scaling)
except (tk.TclError, AttributeError):
# Fallback to 1.0 if detection fails
return 1.0
def calculate_scaled_font_size(self, base_size: int) -> int:
"""
Calculate a DPI-aware font size.
Args:
base_size (int): The base font size in points
Returns:
int: The scaled font size appropriate for the current display
"""
return int(base_size * self.dpi_scaling_factor)
def calculate_scaled_image_size(self, base_size: int) -> int:
"""
Calculate a DPI-aware image size.
Args:
base_size (int): The base image size in pixels
Returns:
int: The scaled image size appropriate for the current display
"""
return int(base_size * self.dpi_scaling_factor)
def calculate_scaled_padding(self, base_padding: int) -> int:
"""
Calculate DPI-aware padding values.
Args:
base_padding (int): The base padding value in pixels
Returns:
int: The scaled padding value appropriate for the current display
"""
return int(base_padding * self.dpi_scaling_factor)
def calculate_scaled_padding_tuple(self, padding1: int, padding2: int) -> tuple[int, int]:
"""
Calculate a tuple of DPI-aware padding values.
Args:
padding1 (int): The first padding value in pixels
padding2 (int): The second padding value in pixels
Returns:
tuple[int, int]: A tuple of scaled padding values
"""
return (self.calculate_scaled_padding(padding1), self.calculate_scaled_padding(padding2))
@staticmethod
def center_window(window: Union[tk.Toplevel, tk.Tk], parent: Union[tk.Toplevel, tk.Tk]) -> None:
"""
Center a window relative to its parent window.
This method calculates the appropriate position to center a child window
on top of its parent window, taking into account both windows' dimensions
and the parent's current position.
Args:
window (Union[tk.Toplevel, tk.Tk]): The window to center
parent (Union[tk.Toplevel, tk.Tk]): The parent window to center on
Note:
This method calls update_idletasks() to ensure accurate dimension
calculations before positioning the window.
Example:
>>> main_window = BaseWindow()
>>> dialog = BaseWindow(main_window.root)
>>> BaseWindow.center_window(dialog.root, main_window.root)
"""
window.update_idletasks()
parent_width = parent.winfo_width()
parent_height = parent.winfo_height()
window_width = window.winfo_width()
window_height = window.winfo_height()
# logging_error(_("Parent position: %d,%d"), parent.winfo_x(), parent.winfo_y())
# logging_error(_("Parent size: %dx%d"), parent_width, parent_height)
# logging_error(_("Window size: %dx%d"), window_width, window_height)
x = parent.winfo_x() + (parent_width // 2) - (window_width // 2)
y = parent.winfo_y() + (parent_height // 2) - (window_height // 2)
window.geometry(f"+{x}+{y}")
if platform_system() == "Darwin":
window.update_idletasks()
else:
window.update()
@staticmethod
def center_window_on_screen(window: Union[tk.Toplevel, tk.Tk]) -> None:
"""
Center a window on the screen where the mouse pointer is located.
This method handles multiple monitors by querying individual monitor geometry
and centering the window on the monitor containing the pointer.
Works cross-platform on Linux, Windows, and macOS.
Args:
window (Union[tk.Toplevel, tk.Tk]): The window to center on screen
Note:
This method calls update_idletasks() to ensure accurate dimension
calculations before positioning the window. Requires screeninfo library.
Example:
>>> progress_window = tk.Toplevel()
>>> BaseWindow.center_window_on_screen(progress_window)
"""
window.update_idletasks()
# Get the window dimensions
window_width = window.winfo_reqwidth()
window_height = window.winfo_reqheight()
# Get pointer position to determine which monitor it's on
pointer_x = window.winfo_pointerx()
pointer_y = window.winfo_pointery()
# Try to get individual monitor geometry using screeninfo
try:
monitors = get_monitors()
except Exception: # pylint: disable=broad-exception-caught
monitors = [] # screeninfo may fail on headless/Wayland/permission issues
# Find the monitor containing the pointer
target_monitor = None
for monitor in monitors:
if monitor.x <= pointer_x < monitor.x + monitor.width and monitor.y <= pointer_y < monitor.y + monitor.height:
target_monitor = monitor
break
# Fallback to primary monitor if pointer is not on any monitor
if target_monitor is None and monitors:
target_monitor = monitors[0]
if target_monitor:
# Center window on the target monitor
x = target_monitor.x + (target_monitor.width - window_width) // 2
y = target_monitor.y + (target_monitor.height - window_height) // 2
# Ensure window stays within monitor bounds
x = max(target_monitor.x, min(x, target_monitor.x + target_monitor.width - window_width))
y = max(target_monitor.y, min(y, target_monitor.y + target_monitor.height - window_height))
else:
# Fallback to simple screen centering if screeninfo fails
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
x = max(0, x)
y = max(0, y)
# Set the position
window.geometry(f"+{x}+{y}")
window.update()
def put_image_in_label( # pylint: disable=too-many-locals
self,
parent: ttk.Frame,
filepath: str,
image_height: int = 40,
fallback_text: Optional[str] = None,
) -> ttk.Label:
"""
Load an image and create a TTK label containing the resized image.
This method handles image loading with comprehensive error handling and fallback
behavior. It automatically scales images to the specified height while maintaining
aspect ratio, and provides graceful degradation when images cannot be loaded.
Args:
parent (ttk.Frame): The parent frame to contain the image label
filepath (str): Path to the image file to load
image_height (int, optional): Target height for the image in pixels.
Defaults to 40.
fallback_text (Optional[str], optional): Text to display if image loading
fails. If None, creates an empty label.
Returns:
ttk.Label: A label widget containing either the loaded image or fallback content
Raises:
None: All exceptions are caught and handled gracefully with fallback behavior
Example:
>>> frame = ttk.Frame(root)
>>> logo_label = BaseWindow.put_image_in_label(
... frame,
... "assets/logo.png",
... image_height=60,
... fallback_text="Logo"
... )
Note:
The returned label has an 'image' attribute set to prevent garbage collection
of the PhotoImage object. This is a Tkinter requirement for image persistence.
"""
try:
# Validate input parameters
if not filepath:
msg = _("Image filepath cannot be empty")
raise ValueError(msg)
if image_height <= 0:
msg = _("Image height must be positive")
raise ValueError(msg)
# Check if file exists
if not os.path.isfile(filepath):
msg = _("Image file not found: %s") % filepath
raise FileNotFoundError(msg)
# Load and validate the image
with Image.open(filepath) as image:
if image is None:
msg = _("Failed to load image from %s") % filepath
raise ValueError(msg)
# Calculate new dimensions while preserving aspect ratio
width, height = image.size
if height == 0:
msg = _("Image has zero height")
raise ValueError(msg)
if width == 0:
msg = _("Image has zero width")
raise ValueError(msg)
aspect_ratio = width / height
dpi_scaled_height = int(image_height * self.dpi_scaling_factor)
# Ensure minimum dimensions to prevent resize errors
dpi_scaled_height = max(dpi_scaled_height, 1)
calculated_width = int(dpi_scaled_height * aspect_ratio)
calculated_width = max(calculated_width, 1)
# Resize the image
resized_image = image.resize((calculated_width, dpi_scaled_height), Image.Resampling.LANCZOS)
# Convert to PhotoImage for Tkinter using a buffer approach
buffer = io.BytesIO()
# Ensure the image is in a format that tk.PhotoImage can handle
if resized_image.mode not in ("RGB", "RGBA"):
resized_image = resized_image.convert("RGB")
# Save as PNG to buffer
resized_image.save(buffer, format="PNG")
buffer.seek(0)
# Create PhotoImage from buffer
photo = tk.PhotoImage(data=buffer.getvalue())
if is_debugging():
return ttk.Label(parent) # the vscode debugger can not cope with the images
# Create the label with the image
image_label = ttk.Label(parent, image=photo)
# Keep a reference to prevent garbage collection
image_label.image = photo # type: ignore[attr-defined]
return image_label
except FileNotFoundError:
# Re-raise FileNotFoundError to let calling code handle it
raise
except (OSError, ValueError, TypeError, AttributeError) as e:
# Log the error for debugging
logging_error(_("Error loading image from %s: %s"), filepath, e)
# Create fallback label
return ttk.Label(parent, text=fallback_text) if fallback_text else ttk.Label(parent)
def show_info_popup(title: str, message: str) -> None:
messagebox.showinfo(title, message)
def show_warning_popup(title: str, message: str) -> None:
messagebox.showwarning(title, message)
def show_error_popup(title: str, message: str) -> None:
messagebox.showerror(title, message)
def ask_yesno_popup(title: str, message: str) -> bool:
return messagebox.askyesno(title, message)
def ask_retry_cancel_popup(title: str, message: str) -> bool:
return messagebox.askretrycancel(title, message)