Skip to content

Commit

Permalink
IMPROVEMENT: Added more parameter type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
amilcarlucas committed Nov 21, 2024
1 parent c603a92 commit dcfbc5c
Show file tree
Hide file tree
Showing 11 changed files with 137 additions and 118 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from logging import warning as logging_warning
from sys import exit as sys_exit
from tkinter import simpledialog, ttk
from typing import Union

from MethodicConfigurator import _
from MethodicConfigurator.backend_flightcontroller import FlightController
Expand Down Expand Up @@ -44,7 +45,7 @@ def __init__( # pylint: disable=too-many-arguments, too-many-positional-argumen
self.flight_controller = flight_controller
self.destroy_parent_on_connect = destroy_parent_on_connect
self.download_params_on_connect = download_params_on_connect
self.previous_selection = (
self.previous_selection: Union[None, str] = (
flight_controller.comport.device
if flight_controller.comport and hasattr(flight_controller.comport, "device")
else None
Expand Down
24 changes: 12 additions & 12 deletions MethodicConfigurator/frontend_tkinter_entry_dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@ class EntryWithDynamicalyFilteredListbox(Entry): # pylint: disable=too-many-anc
def __init__( # pylint: disable=too-many-arguments, too-many-positional-arguments
self,
master,
list_of_items=None,
list_of_items: Union[None, list[str]] = None,
custom_filter_function=None,
listbox_width=None,
listbox_height=12,
ignorecase_match=False,
startswith_match=True,
vscrollbar=True,
hscrollbar=True,
listbox_width: Union[None, int] = None,
listbox_height: int = 12,
ignorecase_match: bool = False,
startswith_match: bool = True,
vscrollbar: bool = True,
hscrollbar: bool = True,
**kwargs,
) -> None:
if list_of_items is None:
Expand Down Expand Up @@ -176,7 +176,7 @@ def unpost_listbox(self) -> None:
def get_value(self) -> str:
return self._entry_var.get() # type: ignore[no-any-return] # mypy bug

def set_value(self, text, close_dialog=False) -> None:
def set_value(self, text: str, close_dialog: bool = False) -> None:
self._set_var(text)

if close_dialog:
Expand All @@ -185,12 +185,12 @@ def set_value(self, text, close_dialog=False) -> None:
self.icursor(END)
self.xview_moveto(1.0)

def _set_var(self, text) -> None:
def _set_var(self, text: str) -> None:
self._entry_var.trace_remove("write", self._trace_id)
self._entry_var.set(text)
self._trace_id = self._entry_var.trace_add("write", self._on_change_entry_var)

def update_entry_from_listbox(self, _event) -> str:
def update_entry_from_listbox(self, _event: Union[None, tk.Event]) -> str:
if self._listbox is not None:
current_selection = self._listbox.curselection()

Expand All @@ -207,7 +207,7 @@ def update_entry_from_listbox(self, _event) -> str:

return "break"

def _previous(self, _event) -> str:
def _previous(self, _event: Union[None, tk.Event]) -> str:
if self._listbox is not None:
current_selection = self._listbox.curselection()

Expand All @@ -229,7 +229,7 @@ def _previous(self, _event) -> str:

return "break"

def _next(self, _event) -> str:
def _next(self, _event: Union[None, tk.Event]) -> str:
if self._listbox is not None:
current_selection = self._listbox.curselection()
if len(current_selection) == 0:
Expand Down
28 changes: 16 additions & 12 deletions MethodicConfigurator/frontend_tkinter_pair_tuple_combobox.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,17 @@ class PairTupleCombobox(ttk.Combobox): # pylint: disable=too-many-ancestors
of a tuple based on its key.
"""

def __init__(self, container, list_pair_tuple, selected_element, cb_name, *args, **kwargs) -> None:
super().__init__(container, *args, **kwargs)
def __init__(
self, master, list_pair_tuple: list[tuple[str, str]], selected_element: Union[None, str], cb_name: str, *args, **kwargs
) -> None:
super().__init__(master, *args, **kwargs)
self.cb_name = cb_name
self.list_keys: list[str] = []
self.list_shows: list[str] = []
self.set_entries_tupple(list_pair_tuple, selected_element)
self.bind("<Configure>", self.on_combo_configure, add="+")

def set_entries_tupple(self, list_pair_tuple, selected_element) -> None:
def set_entries_tupple(self, list_pair_tuple, selected_element: Union[None, str]) -> None:
if isinstance(list_pair_tuple, list):
for tpl in list_pair_tuple:
self.list_keys.append(tpl[0])
Expand Down Expand Up @@ -83,7 +85,7 @@ def get_selected_key(self) -> Union[str, None]:
return None

# https://stackoverflow.com/questions/39915275/change-width-of-dropdown-listbox-of-a-ttk-combobox
def on_combo_configure(self, event) -> None:
def on_combo_configure(self, event: tk.Event) -> None:
combo = event.widget
style = ttk.Style()
# check if the combobox already has the "postoffset" property
Expand Down Expand Up @@ -132,8 +134,10 @@ class PairTupleComboboxTooltip(PairTupleCombobox): # pylint: disable=too-many-a
b) The dropdown is closed (either by selection or pressing Esc)
"""

def __init__(self, container, list_pair_tuple, selected_element, cb_name, *args, **kwargs) -> None:
super().__init__(container, list_pair_tuple, selected_element, cb_name, *args, **kwargs)
def __init__(
self, master, list_pair_tuple: list[tuple[str, str]], selected_element: Union[None, str], cb_name: str, *args, **kwargs
) -> None:
super().__init__(master, list_pair_tuple, selected_element, cb_name, *args, **kwargs)
self.tooltip: Union[None, Toplevel] = None

# Bind events related to the dropdown
Expand All @@ -144,26 +148,26 @@ def __init__(self, container, list_pair_tuple, selected_element, cb_name, *args,
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) -> None:
def on_key_release(self, _event: Union[None, tk.Event]) -> None:
"""Get the keyboard highlighted index and create a tooltip for it"""
pd = self.tk.call("ttk::combobox::PopdownWindow", self)
lb = pd + ".f.l"
if self.tk.call(lb, "curselection"):
highlighted_index = int(self.tk.call(lb, "curselection")[0])
self.create_tooltip_from_index(highlighted_index)

def on_motion(self, event) -> None:
def on_motion(self, event: tk.Event) -> None:
"""Get the mouse highlighted index and create a tooltip for it"""
pd = self.tk.call("ttk::combobox::PopdownWindow", self)
lb = pd + ".f.l"
index = self.tk.call(lb, "index", f"@{event.x},{event.y}")
self.create_tooltip_from_index(int(index))

def create_tooltip_from_index(self, index) -> None:
def create_tooltip_from_index(self, index: int) -> None:
with contextlib.suppress(IndexError):
self.create_tooltip(f"{self.list_keys[index]}: {self.list_shows[index]}")

def create_tooltip(self, text) -> None:
def create_tooltip(self, text: str) -> None:
self.destroy_tooltip()
try:
if self.tooltip is None or self.tooltip.winfo_exists():
Expand All @@ -178,10 +182,10 @@ def create_tooltip(self, text) -> None:
# If there's no active item, we don't need to update the tooltip
pass

def on_combobox_selected(self, _event) -> None:
def on_combobox_selected(self, _event: Union[None, tk.Event]) -> None:
self.destroy_tooltip()

def on_escape_press(self, _event) -> None:
def on_escape_press(self, _event: Union[None, tk.Event]) -> None:
self.destroy_tooltip()

def destroy_tooltip(self) -> None:
Expand Down
13 changes: 7 additions & 6 deletions MethodicConfigurator/frontend_tkinter_parameter_editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from logging import info as logging_info
from logging import warning as logging_warning
from tkinter import filedialog, messagebox, ttk
from typing import Union

# from logging import critical as logging_critical
from webbrowser import open as webbrowser_open # to open the blog post documentation
Expand All @@ -43,7 +44,7 @@
from MethodicConfigurator.tempcal_imu import IMUfit


def show_about_window(root, _version: str) -> None: # pylint: disable=too-many-locals
def show_about_window(root: ttk.Frame, _version: str) -> None: # pylint: disable=too-many-locals
# Create a new window for the custom "About" message
about_window = tk.Toplevel(root)
about_window.title(_("About"))
Expand Down Expand Up @@ -484,7 +485,7 @@ def __should_upload_file_to_fc(self, selected_file: str) -> None:
logging_warning(_("No flight controller connection, will not upload any file"))
messagebox.showwarning(_("Will not upload any file"), _("No flight controller connection"))

def on_param_file_combobox_change(self, _event, forced: bool = False) -> None:
def on_param_file_combobox_change(self, _event: Union[None, tk.Event], forced: bool = False) -> None:
if not self.file_selection_combobox["values"]:
return
self.parameter_editor_table.generate_edit_widgets_focus_out()
Expand Down Expand Up @@ -518,7 +519,7 @@ def download_flight_controller_parameters(self, redownload: bool = False) -> Non
if not redownload:
self.on_param_file_combobox_change(None, True) # the initial param read will trigger a table update

def repopulate_parameter_table(self, selected_file) -> None:
def repopulate_parameter_table(self, selected_file: Union[None, str]) -> None:
if not selected_file:
return # no file was yet selected, so skip it
if hasattr(self.flight_controller, "fc_parameters") and self.flight_controller.fc_parameters:
Expand Down Expand Up @@ -582,7 +583,7 @@ def upload_params_that_require_reset(self, selected_params: dict) -> None:

self.__reset_and_reconnect(fc_reset_required, fc_reset_unsure)

def __reset_and_reconnect(self, fc_reset_required, fc_reset_unsure) -> None:
def __reset_and_reconnect(self, fc_reset_required: bool, fc_reset_unsure: list[str]) -> None:
if not fc_reset_required and fc_reset_unsure:
# Ask the user if they want to reset the ArduPilot
_param_list_str = (", ").join(fc_reset_unsure)
Expand Down Expand Up @@ -625,7 +626,7 @@ def on_upload_selected_click(self) -> None:
self.on_skip_click(force_focus_out_event=False)

# This function can recurse multiple times if there is an upload error
def upload_selected_params(self, selected_params) -> None:
def upload_selected_params(self, selected_params: dict) -> None:
logging_info(_("Uploading %d selected %s parameters to flight controller..."), len(selected_params), self.current_file)

self.upload_params_that_require_reset(selected_params)
Expand Down Expand Up @@ -683,7 +684,7 @@ def upload_selected_params(self, selected_params) -> None:
logging_info(_("All parameters uploaded to the flight controller successfully"))
self.local_filesystem.write_last_uploaded_filename(self.current_file)

def on_skip_click(self, _event=None, force_focus_out_event=True) -> None:
def on_skip_click(self, _event: Union[None, tk.Event] = None, force_focus_out_event: bool = True) -> None:
if force_focus_out_event:
self.parameter_editor_table.generate_edit_widgets_focus_out()
self.write_changes_to_intermediate_parameter_file()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def update_documentation_labels(self, current_file: str) -> None:
if blog_url:
webbrowser_open(url=blog_url, new=0, autoraise=True)

def __update_documentation_label(self, label_key, text, url, url_expected=True) -> None:
def __update_documentation_label(self, label_key: str, text: str, url: str, url_expected: bool = True) -> None:
label = self.documentation_labels[label_key]
if url:
label.config(text=text, foreground="blue", cursor="hand2", underline=True)
Expand Down
Loading

0 comments on commit dcfbc5c

Please sign in to comment.