Skip to content

Commit

Permalink
FIX: mypy extra linting
Browse files Browse the repository at this point in the history
  • Loading branch information
amilcarlucas committed Nov 14, 2024
1 parent 43581e0 commit 0c4e0f5
Show file tree
Hide file tree
Showing 11 changed files with 48 additions and 40 deletions.
5 changes: 3 additions & 2 deletions MethodicConfigurator/extract_param_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,10 +223,11 @@ def output_params(

for param_name, param_value in params.items():
if format_type == "missionplanner":
param_value_conv: float | str = param_value
# preserve non-floating point strings, if present
with contextlib.suppress(ValueError):
param_value = format(param_value, ".6f").rstrip("0").rstrip(".") # noqa: PLW2901
print(f"{param_name},{param_value}")
param_value_conv = format(param_value, ".6f").rstrip("0").rstrip(".")
print(f"{param_name},{param_value_conv}")
elif format_type == "mavproxy":
print(f"{param_name:<15} {param_value:.6f}")
elif format_type == "qgcs":
Expand Down
21 changes: 10 additions & 11 deletions MethodicConfigurator/frontend_tkinter_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,11 +336,14 @@ class BaseWindow:
creating a progress window and centering a window on its parent.
"""

def __init__(self, root_tk: Optional[tk.Tk] = None):
def __init__(self, root_tk: Optional[tk.Toplevel] = None):
if root_tk:
self.root = tk.Toplevel(root_tk)
else:
self.root = tk.Tk()
# Set the application icon for the window and all child windows
# https://pythonassets.com/posts/window-icon-in-tk-tkinter/
self.root.iconphoto(True, tk.PhotoImage(file=LocalFilesystem.application_icon_filepath()))

# Set the theme to 'alt'
style = ttk.Style()
Expand All @@ -350,19 +353,14 @@ def __init__(self, root_tk: Optional[tk.Tk] = None):
self.main_frame = ttk.Frame(self.root)
self.main_frame.pack(expand=True, fill=tk.BOTH)

# Set the application icon for the window and all child windows
# https://pythonassets.com/posts/window-icon-in-tk-tkinter/
if root_tk is None:
self.root.iconphoto(True, tk.PhotoImage(file=LocalFilesystem.application_icon_filepath()))

@staticmethod
def center_window(window, parent):
def center_window(window: tk.Toplevel, parent: tk.Toplevel):
"""
Center a window on its parent window.
Args:
window (tk.Toplevel): The window to center.
parent (tk.Tk): The parent window.
parent (tk.Toplevel): The parent window.
"""
window.update_idletasks()
parent_width = parent.winfo_width()
Expand All @@ -387,7 +385,8 @@ def put_image_in_label(parent: ttk.Frame, filepath: str, image_height: int = 40)

# Create a label with the resized image
image_label = ttk.Label(parent, image=photo)
image_label.image = photo # Keep a reference to the image to prevent it from being garbage collected
# Keep a reference to the image to prevent it from being garbage collected
image_label.image = photo # type: ignore
return image_label


Expand All @@ -408,7 +407,7 @@ def should_display(ptype: str) -> bool:

@staticmethod
def display( # pylint: disable=too-many-arguments
parent: tk.Tk,
parent: tk.Toplevel,
usage_popup_window: BaseWindow,
title: str,
ptype: str,
Expand Down Expand Up @@ -450,7 +449,7 @@ def update_show_again():
usage_popup_window.root.protocol("WM_DELETE_WINDOW", lambda: UsagePopupWindow.close(usage_popup_window, parent))

@staticmethod
def close(usage_popup_window, parent):
def close(usage_popup_window: BaseWindow, parent: tk.Toplevel):
usage_popup_window.root.destroy()
if platform_system() == "Windows":
parent.attributes("-disabled", False) # Re-enable the parent window
Expand Down
12 changes: 6 additions & 6 deletions MethodicConfigurator/frontend_tkinter_component_editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from logging import getLevelName as logging_getLevelName
from math import log2
from tkinter import ttk
from typing import Any
from typing import Any, Tuple

from MethodicConfigurator import _, __version__
from MethodicConfigurator.backend_filesystem import LocalFilesystem
Expand Down Expand Up @@ -460,7 +460,7 @@ def __set_motor_poles_from_fc_parameters(self, fc_parameters: dict):
elif "SERVO_FTW_MASK" in fc_parameters and fc_parameters["SERVO_FTW_MASK"] and "SERVO_FTW_POLES" in fc_parameters:
self.data["Components"]["Motors"]["Specifications"]["Poles"] = fc_parameters["SERVO_FTW_POLES"]

def update_esc_protocol_combobox_entries(self, esc_connection_type):
def update_esc_protocol_combobox_entries(self, esc_connection_type: str):
"""Updates the ESC Protocol combobox entries based on the selected ESC Type."""
if len(esc_connection_type) > 3 and esc_connection_type[:3] == "CAN":
protocols = ["DroneCAN"]
Expand All @@ -481,7 +481,7 @@ def update_esc_protocol_combobox_entries(self, esc_connection_type):
protocol_combobox.set(protocols[0] if protocols else "")
protocol_combobox.update_idletasks() # re-draw the combobox ASAP

def add_entry_or_combobox(self, value, entry_frame, path) -> ttk.Entry | ttk.Combobox:
def add_entry_or_combobox(self, value, entry_frame, path: Tuple[str, str, str]) -> ttk.Entry | ttk.Combobox:
# Default values for comboboxes in case the apm.pdef.xml metadata is not available
fallbacks = {
"RC_PROTOCOLS": [value["protocol"] for value in rc_protocols_dict.values()],
Expand Down Expand Up @@ -542,8 +542,8 @@ def get_combobox_values(param_name: str) -> list:
config = combobox_config.get(path)
if config:
cb = ttk.Combobox(entry_frame, values=config["values"])
cb.bind("<FocusOut>", lambda event, path=path: self.validate_combobox(event, path))
cb.bind("<KeyRelease>", lambda event, path=path: self.validate_combobox(event, path))
cb.bind("<FocusOut>", lambda event, path=path: self.validate_combobox(event, path)) # type: ignore
cb.bind("<KeyRelease>", lambda event, path=path: self.validate_combobox(event, path)) # type: ignore

if path == ("ESC", "FC Connection", "Type"): # immediate update of ESC Protocol upon ESC Type selection
cb.bind("<<ComboboxSelected>>", lambda event, path=path: self.update_esc_protocol_combobox_entries(cb.get()))
Expand Down Expand Up @@ -591,7 +591,7 @@ def get_validate_function(self, entry, path):
}
return validate_functions.get(path)

def validate_combobox(self, event, path) -> bool:
def validate_combobox(self, event: tk.Event, path: Tuple[str, ...]) -> bool:
"""
Validates the value of a combobox.
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def __init__(self, version, local_filesystem: LocalFilesystem):
self.root.after(10, self.__display_component_editor_usage_instructions(self.root))

@staticmethod
def __display_component_editor_usage_instructions(parent: tk.Tk):
def __display_component_editor_usage_instructions(parent: tk.Toplevel):
usage_popup_window = BaseWindow(parent)
style = ttk.Style()

Expand Down Expand Up @@ -213,7 +213,7 @@ def save_data(self):

# User confirmed, proceed with saving the data
for path, entry in self.entry_widgets.items():
value = entry.get()
value: str | int | float = entry.get()
# Navigate through the nested dictionaries using the elements of the path
current_data = self.data["Components"]
for key in path[:-1]:
Expand Down
9 changes: 7 additions & 2 deletions MethodicConfigurator/frontend_tkinter_connection_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,12 @@ def on_select_connection_combobox_change(self, _event):
selected_connection = self.conn_selection_combobox.get_selected_key()
error_msg = _("Connection combobox changed to: {selected_connection}")
logging_debug(error_msg.format(**locals()))
if self.flight_controller.master is None or selected_connection != self.flight_controller.comport.device:
comport_device = (
self.flight_controller.comport.device
if self.flight_controller.comport and hasattr(self.flight_controller.comport, "device")
else None
)
if self.flight_controller.master is None or selected_connection != comport_device:
if selected_connection == "Add another":
if not self.add_connection() and self.previous_selection:
# nothing got selected revert to the current connection
Expand Down Expand Up @@ -216,7 +221,7 @@ def __init__(self, flight_controller: FlightController, connection_result_string
skip_fc_connection_button = ttk.Button(
option3_label_frame,
text=_("Skip FC connection, just edit the .param files on disk"),
command=lambda flight_controller=flight_controller: self.skip_fc_connection(flight_controller),
command=lambda flight_controller=flight_controller: self.skip_fc_connection(flight_controller), # type: ignore
)
skip_fc_connection_button.pack(expand=False, fill=tk.X, padx=15, pady=6)
show_tooltip(
Expand Down
6 changes: 3 additions & 3 deletions MethodicConfigurator/frontend_tkinter_directory_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,8 @@ class VehicleDirectorySelectionWidgets(DirectorySelectionWidgets):

def __init__( # pylint: disable=too-many-arguments
self,
parent: tk.Widget,
parent_frame: ttk.Frame,
parent: tk.Toplevel,
parent_frame: ttk.Widget,
local_filesystem: LocalFilesystem,
initial_dir: str,
destroy_parent_on_open: bool,
Expand Down Expand Up @@ -354,7 +354,7 @@ def create_option2_widgets(self, initial_dir: str):
)
option2_label.pack(expand=False, fill=tk.X, padx=6)
self.connection_selection_widgets = VehicleDirectorySelectionWidgets(
self, option2_label_frame, self.local_filesystem, initial_dir, destroy_parent_on_open=True
self.root, option2_label_frame, self.local_filesystem, initial_dir, destroy_parent_on_open=True
)
self.connection_selection_widgets.container_frame.pack(expand=True, fill=tk.X, padx=3, pady=5, anchor=tk.NW)

Expand Down
2 changes: 1 addition & 1 deletion MethodicConfigurator/frontend_tkinter_entry_dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ def _previous(self, _event):
self._listbox.selection_clear(index)

if index == 0:
index = END
index = END # type: ignore
else:
index -= 1

Expand Down
6 changes: 3 additions & 3 deletions MethodicConfigurator/frontend_tkinter_pair_tuple_combobox.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,9 @@ def __init__(self, container, list_pair_tuple, selected_element, cb_name, *args,
# Bind events related to the dropdown
pd = self.tk.call("ttk::combobox::PopdownWindow", self)
lb = pd + ".f.l"
self._bind(("bind", lb), "<KeyRelease>", self.on_key_release, None)
self._bind(("bind", lb), "<Motion>", self.on_motion, None)
self._bind(("bind", lb), "<Escape>", self.on_escape_press, None)
self._bind(("bind", lb), "<KeyRelease>", self.on_key_release, None) # type: ignore
self._bind(("bind", lb), "<Motion>", self.on_motion, None) # type: ignore
self._bind(("bind", lb), "<Escape>", self.on_escape_press, None) # type: ignore
self.bind("<<ComboboxSelected>>", self.on_combobox_selected, None)

def on_key_release(self, _event):
Expand Down
8 changes: 4 additions & 4 deletions MethodicConfigurator/frontend_tkinter_parameter_editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class DocumentationFrame: # pylint: disable=too-few-public-methods
functionality to open these links in a web browser.
"""

def __init__(self, root: tk.Tk, local_filesystem, current_file: str):
def __init__(self, root: tk.Widget, local_filesystem, current_file: str):
self.root = root
self.local_filesystem = local_filesystem
self.current_file = current_file
Expand Down Expand Up @@ -116,7 +116,7 @@ def __update_documentation_label(self, label_key, text, url, url_expected=True):
label = self.documentation_labels[label_key]
if url:
label.config(text=text, foreground="blue", cursor="hand2", underline=True)
label.bind("<Button-1>", lambda event, url=url: webbrowser_open(url))
label.bind("<Button-1>", lambda event, url=url: webbrowser_open(url)) # type: ignore
show_tooltip(label, url)
else:
label.config(text=text, foreground="black", cursor="arrow", underline=False)
Expand Down Expand Up @@ -270,7 +270,7 @@ def __create_conf_widgets(self, version: str):
# Create a new frame inside the config_subframe for the intermediate parameter file directory selection labels
# and directory selection button
directory_selection_frame = VehicleDirectorySelectionWidgets(
self, config_subframe, self.local_filesystem, self.local_filesystem.vehicle_dir, destroy_parent_on_open=False
self.root, config_subframe, self.local_filesystem, self.local_filesystem.vehicle_dir, destroy_parent_on_open=False
)
directory_selection_frame.container_frame.pack(side=tk.LEFT, fill="x", expand=False, padx=(4, 6))

Expand Down Expand Up @@ -408,7 +408,7 @@ def __create_parameter_area_widgets(self):
)

@staticmethod
def __display_usage_popup_window(parent: tk.Tk):
def __display_usage_popup_window(parent: tk.Toplevel):
usage_popup_window = BaseWindow(parent)
style = ttk.Style()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ def __create_new_value_entry( # pylint: disable=too-many-arguments

bitmask_dict = None
value_str = format(param.value, ".6f").rstrip("0").rstrip(".")
new_value_entry: PairTupleCombobox | ttk.Entry
if (
param_metadata
and "values" in param_metadata
Expand Down
14 changes: 8 additions & 6 deletions MethodicConfigurator/frontend_tkinter_template_overview.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from logging import basicConfig as logging_basicConfig
from logging import getLevelName as logging_getLevelName
from tkinter import ttk
from typing import Optional

from MethodicConfigurator import _, __version__
from MethodicConfigurator.backend_filesystem_program_settings import ProgramSettings
Expand All @@ -32,14 +33,14 @@ class TemplateOverviewWindow(BaseWindow):
manner, making it easier for users to navigate and select the desired template for configuration.
Attributes:
window (tk.Tk): The root Tkinter window object for the GUI.
window (tk.Toplevel): The root Tkinter window object for the GUI.
Methods:
on_row_double_click(event): Handles the event triggered when a row in the Treeview is double-clicked, allowing the user
to store the corresponding template directory.
"""

def __init__(self, parent: tk.Tk):
def __init__(self, parent: Optional[tk.Toplevel] = None):
super().__init__(parent)
title = _("Amilcar Lucas's - ArduPilot methodic configurator {} - Template Overview and selection")
self.root.title(title.format(__version__))
Expand All @@ -49,7 +50,7 @@ def __init__(self, parent: tk.Tk):
instruction_label = ttk.Label(self.main_frame, text=instruction_text, font=("Arial", 12))
instruction_label.pack(pady=(10, 20))

self.sort_column = None
self.sort_column: str

style = ttk.Style(self.root)
# Add padding to Treeview heading style
Expand Down Expand Up @@ -97,7 +98,8 @@ def __init__(self, parent: tk.Tk):
self.tree.pack(fill=tk.BOTH, expand=True)

for col in self.tree["columns"]:
self.tree.heading(col, text=col, command=lambda col=col: self.__sort_by_column(col, False))
col_str = str(col)
self.tree.heading(col_str, text=col_str, command=lambda col=col_str: self.__sort_by_column(col, False))

if isinstance(self.root, tk.Toplevel):
try:
Expand Down Expand Up @@ -135,8 +137,8 @@ def __on_row_double_click(self, event):
ProgramSettings.store_template_dir(selected_template_relative_path)
self.root.destroy()

def __sort_by_column(self, col, reverse: bool):
if self.sort_column and self.sort_column != col:
def __sort_by_column(self, col: str, reverse: bool):
if hasattr(self, "sort_column") and self.sort_column and self.sort_column != col:
self.tree.heading(self.sort_column, text=self.sort_column)
self.tree.heading(col, text=col + (" ▼" if reverse else " ▲"))
self.sort_column = col
Expand Down

0 comments on commit 0c4e0f5

Please sign in to comment.