Skip to content

Commit 3c42e28

Browse files
committed
IMPROVEMENT: Refractor more code out of backend_filesystem.py
1 parent 6683bcf commit 3c42e28

File tree

4 files changed

+50
-57
lines changed

4 files changed

+50
-57
lines changed

MethodicConfigurator/backend_filesystem.py

Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
from os import getcwd as os_getcwd
1313
from os import listdir as os_listdir
1414
from os import rename as os_rename
15-
from os import walk as os_walk
1615

1716
from shutil import copy2 as shutil_copy2
1817
from shutil import copytree as shutil_copytree
@@ -42,8 +41,6 @@
4241
from MethodicConfigurator.backend_filesystem_configuration_steps import ConfigurationSteps
4342
from MethodicConfigurator.backend_filesystem_program_settings import ProgramSettings
4443

45-
from MethodicConfigurator.middleware_template_overview import TemplateOverview
46-
4744
TOOLTIP_MAX_LENGTH = 105
4845

4946

@@ -516,31 +513,6 @@ def supported_vehicles():
516513
return ['AP_Periph', 'AntennaTracker', 'ArduCopter', 'ArduPlane',
517514
'ArduSub', 'Blimp', 'Heli', 'Rover', 'SITL']
518515

519-
@staticmethod
520-
def get_vehicle_components_overviews():
521-
"""
522-
Finds all subdirectories of base_dir containing a "vehicle_components.json" file,
523-
creates a dictionary where the keys are the subdirectory names (relative to base_dir)
524-
and the values are instances of VehicleComponents.
525-
526-
:param base_dir: The base directory to start searching from.
527-
:return: A dictionary mapping subdirectory paths to VehicleComponents instances.
528-
"""
529-
vehicle_components_dict = {}
530-
file_to_find = VehicleComponents().vehicle_components_json_filename
531-
template_default_dir = ProgramSettings.get_templates_base_dir()
532-
for root, _dirs, files in os_walk(template_default_dir):
533-
if file_to_find in files:
534-
relative_path = os_path.relpath(root, template_default_dir)
535-
vehicle_components = VehicleComponents()
536-
comp_data = vehicle_components.load_vehicle_components_json_data(root)
537-
if comp_data:
538-
comp_data = comp_data.get('Components', {})
539-
vehicle_components_overview = TemplateOverview(comp_data)
540-
vehicle_components_dict[relative_path] = vehicle_components_overview
541-
542-
return vehicle_components_dict
543-
544516
@staticmethod
545517
def add_argparse_arguments(parser):
546518
parser.add_argument('-t', '--vehicle-type',

MethodicConfigurator/backend_filesystem_vehicle_components.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
'''
1010

1111
from os import path as os_path
12+
from os import walk as os_walk
1213

1314
# from sys import exit as sys_exit
1415
# from logging import debug as logging_debug
@@ -22,6 +23,10 @@
2223
from json import dump as json_dump
2324
from json import JSONDecodeError
2425

26+
from MethodicConfigurator.backend_filesystem_program_settings import ProgramSettings
27+
28+
from MethodicConfigurator.middleware_template_overview import TemplateOverview
29+
2530

2631
class VehicleComponents:
2732
"""
@@ -67,3 +72,28 @@ def get_fc_fw_version_from_vehicle_components_json(self) -> str:
6772
return version_str
6873
logging_error(f"FW version string {version_str} on {self.vehicle_components_json_filename} is invalid")
6974
return None
75+
76+
@staticmethod
77+
def get_vehicle_components_overviews():
78+
"""
79+
Finds all subdirectories of base_dir containing a "vehicle_components.json" file,
80+
creates a dictionary where the keys are the subdirectory names (relative to base_dir)
81+
and the values are instances of VehicleComponents.
82+
83+
:param base_dir: The base directory to start searching from.
84+
:return: A dictionary mapping subdirectory paths to VehicleComponents instances.
85+
"""
86+
vehicle_components_dict = {}
87+
file_to_find = VehicleComponents().vehicle_components_json_filename
88+
template_default_dir = ProgramSettings.get_templates_base_dir()
89+
for root, _dirs, files in os_walk(template_default_dir):
90+
if file_to_find in files:
91+
relative_path = os_path.relpath(root, template_default_dir)
92+
vehicle_components = VehicleComponents()
93+
comp_data = vehicle_components.load_vehicle_components_json_data(root)
94+
if comp_data:
95+
comp_data = comp_data.get('Components', {})
96+
vehicle_components_overview = TemplateOverview(comp_data)
97+
vehicle_components_dict[relative_path] = vehicle_components_overview
98+
99+
return vehicle_components_dict

MethodicConfigurator/frontend_tkinter_directory_selection.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
from MethodicConfigurator.common_arguments import add_common_arguments_and_parse
3232

3333
from MethodicConfigurator.backend_filesystem import LocalFilesystem
34+
from MethodicConfigurator.backend_filesystem_program_settings import ProgramSettings
3435

3536
from MethodicConfigurator.frontend_tkinter_base import show_no_param_files_error
3637
from MethodicConfigurator.frontend_tkinter_base import show_tooltip
@@ -49,12 +50,12 @@ class DirectorySelectionWidgets():
4950
"""
5051
def __init__(self, parent, parent_frame, initialdir: str, label_text: str, # pylint: disable=too-many-arguments
5152
autoresize_width: bool, dir_tooltip: str, button_tooltip: str,
52-
local_filesystem: LocalFilesystem = None):
53+
is_template_selection: bool):
5354
self.parent = parent
5455
self.directory = deepcopy(initialdir)
5556
self.label_text = label_text
5657
self.autoresize_width = autoresize_width
57-
self.local_filesystem2 = local_filesystem # "2" to not collide with VehicleDirectorySelectionWidgets.local_filesystem
58+
self.is_template_selection = is_template_selection
5859

5960
# Create a new frame for the directory selection label and button
6061
self.container_frame = ttk.Frame(parent_frame)
@@ -86,9 +87,9 @@ def __init__(self, parent, parent_frame, initialdir: str, label_text: str, # py
8687
self.directory_entry.xview_moveto(1.0)
8788

8889
def on_select_directory(self):
89-
if self.local_filesystem2:
90-
TemplateOverviewWindow(self.parent.root, self.local_filesystem2)
91-
selected_directory = self.local_filesystem2.get_recently_used_dirs()[0]
90+
if self.is_template_selection:
91+
TemplateOverviewWindow(self.parent.root)
92+
selected_directory = ProgramSettings.get_recently_used_dirs()[0]
9293
logging_info("Selected template directory: %s", selected_directory)
9394
else:
9495
selected_directory = filedialog.askdirectory(initialdir=self.directory, title=f"Select {self.label_text}")
@@ -155,7 +156,8 @@ def __init__(self, parent: ttk, parent_frame: ttk.Frame, # pylint: disable=too-
155156
"parameter files to be uploaded to the flight controller",
156157
"Select the vehicle-specific configuration directory containing the\n"
157158
"intermediate parameter files to be uploaded to the flight controller" \
158-
if destroy_parent_on_open else '')
159+
if destroy_parent_on_open else '',
160+
False)
159161
self.local_filesystem = local_filesystem
160162
self.destroy_parent_on_open = destroy_parent_on_open
161163

@@ -241,7 +243,7 @@ def create_option1_widgets(self, initial_template_dir: str, initial_base_dir: st
241243
False,
242244
template_dir_edit_tooltip,
243245
template_dir_btn_tooltip,
244-
self.local_filesystem)
246+
True)
245247
self.template_dir.container_frame.pack(expand=False, fill=tk.X, padx=3, pady=5, anchor=tk.NW)
246248

247249
use_fc_params_checkbox = ttk.Checkbutton(option1_label_frame, variable=self.use_fc_params,
@@ -261,7 +263,8 @@ def create_option1_widgets(self, initial_template_dir: str, initial_base_dir: st
261263
"(destination) base directory:",
262264
False,
263265
new_base_dir_edit_tooltip,
264-
new_base_dir_btn_tooltip)
266+
new_base_dir_btn_tooltip,
267+
False)
265268
self.new_base_dir.container_frame.pack(expand=False, fill=tk.X, padx=3, pady=5, anchor=tk.NW)
266269
new_dir_edit_tooltip = "A new vehicle configuration directory with this name will be created at the " \
267270
"(destination) base directory"
@@ -303,7 +306,8 @@ def create_option3_widgets(self, last_vehicle_dir: str):
303306
"Last used vehicle configuration directory:",
304307
False,
305308
"Last used vehicle configuration directory",
306-
"")
309+
"",
310+
False)
307311
last_dir.container_frame.pack(expand=False, fill=tk.X, padx=3, pady=5, anchor=tk.NW)
308312

309313
# Check if there is a last used vehicle configuration directory

MethodicConfigurator/frontend_tkinter_template_overview.py

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,15 @@
1717

1818
from MethodicConfigurator.middleware_template_overview import TemplateOverview
1919

20-
from MethodicConfigurator.backend_filesystem import LocalFilesystem
20+
from MethodicConfigurator.backend_filesystem_program_settings import ProgramSettings
21+
from MethodicConfigurator.backend_filesystem_vehicle_components import VehicleComponents
2122

2223
from MethodicConfigurator.common_arguments import add_common_arguments_and_parse
2324

2425
from MethodicConfigurator.frontend_tkinter_base import BaseWindow
25-
from MethodicConfigurator.frontend_tkinter_base import show_error_message
2626

2727
from MethodicConfigurator.version import VERSION
2828

29-
3029
class TemplateOverviewWindow(BaseWindow):
3130
"""
3231
Represents the window for viewing and managing ArduPilot vehicle templates.
@@ -38,18 +37,15 @@ class TemplateOverviewWindow(BaseWindow):
3837
3938
Attributes:
4039
window (tk.Tk): The root Tkinter window object for the GUI.
41-
local_filesystem (LocalFilesystem): An instance of LocalFilesystem used to interact with the filesystem, including
42-
operations related to template directories.
4340
4441
Methods:
4542
on_row_double_click(event): Handles the event triggered when a row in the Treeview is double-clicked, allowing the user
4643
to store the corresponding template directory.
4744
"""
48-
def __init__(self, parent: tk.Tk, local_filesystem: LocalFilesystem):
45+
def __init__(self, parent: tk.Tk):
4946
super().__init__(parent)
5047
self.root.title(f"Amilcar Lucas's - ArduPilot methodic configurator {VERSION} - Template Overview and selection")
5148
self.root.geometry("1200x300")
52-
self.local_filesystem = local_filesystem
5349

5450
instruction_text = "Please double-click the template below that most resembles your own vehicle components"
5551
instruction_label = ttk.Label(self.main_frame, text=instruction_text, font=('Arial', 12))
@@ -75,7 +71,7 @@ def __init__(self, parent: tk.Tk, local_filesystem: LocalFilesystem):
7571
self.tree.heading(col, text=col)
7672

7773
# Populate the Treeview with data from the template overview
78-
for key, template_overview in self.local_filesystem.get_vehicle_components_overviews().items():
74+
for key, template_overview in VehicleComponents.get_vehicle_components_overviews().items():
7975
attribute_names = template_overview.attributes()
8076
values = (key,) + tuple(getattr(template_overview, attr, '') for attr in attribute_names)
8177
self.tree.insert('', 'end', text=key, values=values)
@@ -118,7 +114,7 @@ def on_row_double_click(self, event):
118114
item_id = self.tree.identify_row(event.y)
119115
if item_id:
120116
selected_template_relative_path = self.tree.item(item_id)['text']
121-
self.local_filesystem.store_template_dir(selected_template_relative_path)
117+
ProgramSettings.store_template_dir(selected_template_relative_path)
122118
self.root.destroy()
123119

124120
def argument_parser():
@@ -136,25 +132,16 @@ def argument_parser():
136132
'apply changes directly to the flight controller. The tool is built to '
137133
'semi-automate the configuration process of ArduPilot for drones by '
138134
'providing a clear and intuitive interface for parameter management.')
139-
parser = LocalFilesystem.add_argparse_arguments(parser)
140135
return add_common_arguments_and_parse(parser)
141136

142137
def main():
143138
args = argument_parser()
144139

145140
logging_basicConfig(level=logging_getLevelName(args.loglevel), format='%(asctime)s - %(levelname)s - %(message)s')
146141

147-
vehicle_type = "ArduCopter"
148-
149-
try:
150-
local_filesystem = LocalFilesystem(args.vehicle_dir, vehicle_type, None, args.allow_editing_template_files)
151-
except SystemExit as expt:
152-
show_error_message("Fatal error reading parameter files", f"{expt}")
153-
raise
154-
155-
TemplateOverviewWindow(None, local_filesystem)
142+
TemplateOverviewWindow(None)
156143

157-
print(local_filesystem.get_recently_used_dirs()[0])
144+
print(ProgramSettings.get_recently_used_dirs()[0])
158145

159146
if __name__ == "__main__":
160147
main()

0 commit comments

Comments
 (0)