Refactored Profile Creation State to be independent of PyQt slots, and use callbacks

This commit is contained in:
SimplifiedPrivacy 2026-11-05 13:10:59 -05:00
parent 330fabfcb4
commit e224c12c7a
4 changed files with 160 additions and 129 deletions

View file

@ -121,3 +121,17 @@ def create_resolution_button_image(btn_path: str, resolution_text: str):
painter.end() painter.end()
return base_image return base_image
def blank_button_path(btn_path: str):
template_path = os.path.join(btn_path, "r1.png")
return template_path
def blank_button(btn_path: str):
"""Return an empty 'default' image with a border."""
template_path = os.path.join(btn_path, "r1.png")
if os.path.exists(template_path):
return QPixmap(template_path)
else:
return None

View file

@ -1,11 +1,11 @@
from core.services.profiles.filter_protocols import protocol_matches_profile_type from core.services.profiles.filter_protocols import protocol_matches_profile_type, app_matches_profile_type
from gui.v2.presenters.data.location_data import get_location_display_data from gui.v2.presenters.data.location_data import get_location_display_data
from gui.v2.presenters.data.app_data import get_app_display_data from gui.v2.presenters.data.app_data import get_app_display_data
from gui.v2.presenters.data.protocol_data import get_protocol_button_data from gui.v2.presenters.data.protocol_data import get_protocol_button_data
from gui.v2.presenters.data.resolution_data import get_resolution_data from gui.v2.presenters.data.resolution_data import get_resolution_data
from gui.v2.presenters.data.type_data import get_profile_type_data from gui.v2.presenters.data.type_data import get_profile_type_data
from gui.v2.presenters.image_tools.button_factory import create_button_image, create_resolution_button_image from gui.v2.presenters.image_tools.button_factory import create_button_image, create_resolution_button_image, blank_button, blank_button_path
from pathlib import Path from pathlib import Path
@ -13,85 +13,148 @@ from pathlib import Path
class RegistrationState: class RegistrationState:
def __init__(self, btn_path): def __init__(self, btn_path):
self.btn_path = btn_path self.btn_path = btn_path
self.all_options = {} # Stores the Path (static) or Dict (dynamic) self.all_options = {}
self.selections = {} # Stores current ID self.selections = {}
self.order_map = {} # Stores ID order self.order_map = {}
self.pixmap_cache = {} # Caches generated QPixmaps to prevent lag self.pixmap_cache = {}
# Filters where one data category affects another one. (in this case Protocol is affected by Type) # Maps a category to the function that validates its current selection.
self._filter_map = { self._filter_map = {
"Protocol": self.is_protocol_valid, "Protocol": self.is_protocol_valid,
"Browser": self.is_app_valid,
} }
# Maps a "Trigger" category to the categories it affects.
self._dependency_map = {
"Type": ["Protocol", "Browser"],
}
# Callbacks to notify the UI. Store functions here: { "Category": callback_func }
self.listeners = {}
self._load_all_data() self._load_all_data()
def _register_category(self, category, data, default_idx=0): def register_listener(self, category, callback):
"""Helper to handle the boilerplate of setting up a category.""" """UI elements call this to be notified when their category changes."""
# If data is a list (like resolutions), convert to a dict where keys are the values self.listeners[category] = callback
if isinstance(data, list):
data = {item: item for item in data}
self.all_options[category] = data
self.order_map[category] = list(data.keys())
if not self.order_map[category]:
self.selections[category] = None
return
if default_idx < len(self.order_map[category]):
self.selections[category] = self.order_map[category][default_idx]
else:
self.selections[category] = self.order_map[category][0]
def _load_all_data(self): def _load_all_data(self):
"""Fetch the data via external functions, and then register it for the UI""" """Load the data for a given category, and then register that data"""
load_config = { load_config = {
"Type": (get_profile_type_data, 0), "Type": (get_profile_type_data, 0),
"Protocol": (get_protocol_button_data, 0), "Protocol": (get_protocol_button_data, 0),
"Resolution": (get_resolution_data, 0), "Resolution": (get_resolution_data, 0),
"Location": (get_location_display_data, 0), "Location": (get_location_display_data, 0),
"Browser": (get_app_display_data, 0), "Browser": (get_app_display_data, 0),
} }
for category, (loader_func, default_idx) in load_config.items(): for category, (loader_func, default_idx) in load_config.items():
data = loader_func(self.btn_path) data = loader_func(self.btn_path)
self._register_category(category, data, default_idx) self._register_category(category, data, default_idx)
def _register_category(self, category, data, default_idx=0):
"""Setup a category with a given data set and default index"""
if isinstance(data, list):
data = {item: item for item in data}
self.all_options[category] = data
self.order_map[category] = list(data.keys())
# Default selection logic
ids = self.order_map[category]
self.selections[category] = ids[default_idx] if ids and default_idx < len(ids) else (ids[0] if ids else None)
def _ensure_valid(self, category):
"""Generic validator: resets selection to first valid option, or None if none exist."""
filter_func = self._filter_map.get(category)
if not filter_func:
return
current_val = self.selections.get(category)
# If current selection is invalid (or None), try to find a replacement
if current_val is None or not filter_func(current_val):
found_valid = False
for candidate_id in self.order_map.get(category, []):
if filter_func(candidate_id):
self.selections[category] = candidate_id
found_valid = True
break
# If no valid option is found, set to None to trigger blank image
if not found_valid:
self.selections[category] = None
def cycle_selection(self, category, direction):
ids = self.order_map.get(category, [])
if not ids:
self.selections[category] = None
self._notify(category)
return None
current_id = self.selections.get(category)
current_index = ids.index(current_id) if current_id in ids else 0
filter_func = self._filter_map.get(category)
found_valid = False
for i in range(1, len(ids) + 1):
next_index = (current_index + (i * direction)) % len(ids)
candidate_id = ids[next_index]
if filter_func is None or filter_func(candidate_id):
self.selections[category] = candidate_id
found_valid = True
break
# If we cycled through everything and found nothing valid, set to None
if not found_valid:
self.selections[category] = None
# Reactive Updates
dependents = self._dependency_map.get(category, [])
# 1. Notify the category that was just cycled
self._notify(category)
# 2. Check and notify all dependents (e.g., Type -> Browser)
for dep in dependents:
self._ensure_valid(dep)
self._notify(dep)
return self.get_current_image(category)
def _notify(self, category):
"""Triggers the UI callback for a specific category."""
if category in self.listeners:
self.listeners[category]()
def get_current_image(self, category): def get_current_image(self, category):
"""Use the data to create an image. It could be either static or dynamic.""" """Returns an image or a path to one depending on the category and data format"""
current_id = self.selections[category]
current_id = self.selections.get(category)
if current_id is None: if current_id is None:
return None return blank_button(self.btn_path)
data = self.all_options[category][current_id]
# Special case for Resolution: use the template path and the ID (the resolution string)
if category == "Resolution":
cache_key = f"{category}_{current_id}"
if cache_key in self.pixmap_cache:
return self.pixmap_cache[cache_key]
# Construct the template path here instead of in the loader
template_path = f"{self.btn_path}/resolution_template.png"
pixmap = create_resolution_button_image(
btn_path=template_path,
resolution_text=str(current_id)
)
self.pixmap_cache[cache_key] = pixmap
return pixmap
if data is None:
return None
# Static string of image path:
if isinstance(data, Path):
return data
# Cache check
cache_key = f"{category}_{current_id}" cache_key = f"{category}_{current_id}"
if cache_key in self.pixmap_cache: if cache_key in self.pixmap_cache:
return self.pixmap_cache[cache_key] return self.pixmap_cache[cache_key]
# dynamic creation of the image with the nested dict: # 3. IMAGE DISPATCH: sorts based on data type
data = self.all_options[category][current_id]
# Special Case: Resolution
if category == "Resolution":
res_img = create_resolution_button_image(
btn_path=f"{self.btn_path}/resolution_template.png",
resolution_text=str(current_id)
)
self.pixmap_cache[cache_key] = res_img
return res_img
if data is None:
return blank_button(self.btn_path)
if isinstance(data, Path):
return data
if isinstance(data, dict): if isinstance(data, dict):
pixmap = create_button_image( pixmap = create_button_image(
first_line=data.get('name', ''), first_line=data.get('name', ''),
@ -102,63 +165,18 @@ class RegistrationState:
self.pixmap_cache[cache_key] = pixmap self.pixmap_cache[cache_key] = pixmap
return pixmap return pixmap
def is_protocol_valid(self, protocol_id) -> bool:
"""
Checks if a specific protocol ID is compatible with the current Type.
Returns True if valid, False if it should be skipped.
"""
current_type = self.selections.get("Type")
if current_type is None:
return True # Default to valid if type isn't set yet
return protocol_matches_profile_type(protocol=protocol_id, profile_type=current_type)
def _ensure_protocol_valid(self):
"""Checks current protocol and resets it to the first valid one if invalid."""
current_proto = self.selections.get("Protocol")
if not self.is_protocol_valid(current_proto):
# Find the first valid protocol available for the new type
ids = self.order_map.get("Protocol", [])
for proto_id in ids:
if self.is_protocol_valid(proto_id):
self.selections["Protocol"] = proto_id
break
def cycle_selection(self, category, direction):
ids = self.order_map.get(category, [])
if not ids:
return None
current_id = self.selections.get(category)
current_index = ids.index(current_id) if current_id in ids else 0
num_ids = len(ids)
# Get the filter function for this category (if one exists)
filter_func = self._filter_map.get(category)
for i in range(1, num_ids + 1):
# Calculate the next index while ensuring it "wraps around" the list boundaries, using Modulo
next_index = (current_index + (i * direction)) % num_ids
candidate_id = ids[next_index]
# If a filter exists for this category, use it.
# If no filter exists, filter_func is None, so we just accept the candidate.
if filter_func is None or filter_func(candidate_id):
self.selections[category] = candidate_id
break
else: else:
print(f"No valid options found for {category}.") print("Error with Display State, invalid choice. But returning a blank image,")
return None return blank_button(self.btn_path)
# After the selection is updated, if we just changed the Type, # Validation logic, used by the generic _ensure_valid
# we must ensure the current Protocol is still valid. def is_app_valid(self, app_choice):
if category == "Type": current_type = self.selections.get("Type")
self._ensure_protocol_valid() return app_matches_profile_type(app_choice=app_choice, profile_type=current_type)
return self.get_current_image(category)
def is_protocol_valid(self, protocol_id):
current_type = self.selections.get("Type")
return True if current_type is None else protocol_matches_profile_type(protocol=protocol_id, profile_type=current_type)
def get_final_choices(self): def get_final_choices(self):
return self.selections return self.selections

View file

@ -219,6 +219,8 @@ class EditorPage(Page):
self.show_a_popup(message=error_msg, title="Missing fields") self.show_a_popup(message=error_msg, title="Missing fields")
return return
print(f"in evaluate_option_labels, location_codes is {location_codes} and profile_type is {profile_type}")
supported_protocols_result = get_supported_protocols_for_location(location_codes=location_codes, profile_type=profile_type) supported_protocols_result = get_supported_protocols_for_location(location_codes=location_codes, profile_type=profile_type)
if not supported_protocols_result.valid: if not supported_protocols_result.valid:

View file

@ -65,13 +65,14 @@ class TextInputGroup(QWidget):
class SelectionGroup(QWidget): class SelectionGroup(QWidget):
"""Create Image/Value Select Boxes of a particular style""" """Create Image/Value Select Boxes of a particular style"""
valueChanged = pyqtSignal(str)
def __init__(self, parent, title, category, state): def __init__(self, parent, title, category, state):
super().__init__(parent) super().__init__(parent)
self.category = category self.category = category
self.state = state self.state = state
# Tell the state: "When this category changes, run my update_display method"
self.state.register_listener(category, self.update_display)
# Ensure the group widget itself is wide enough to hold the layout # Ensure the group widget itself is wide enough to hold the layout
# (Legacy specs were: 30px prev + 185px box + 30px next + spacing) # (Legacy specs were: 30px prev + 185px box + 30px next + spacing)
self.setMinimumWidth(260) self.setMinimumWidth(260)
@ -119,15 +120,15 @@ class SelectionGroup(QWidget):
self.update_display() self.update_display()
def change_image(self, direction): def change_image(self, direction):
new_path = self.state.cycle_selection(self.category, direction) """Toggle the next image change by category and direction"""
self.set_image(new_path) self.state.cycle_selection(self.category, direction)
# Emit the signal so the parent knows something happened
self.valueChanged.emit(self.category)
def update_display(self): def update_display(self):
"""Get and Change the currently displayed image. This function is passed as a callback to the state"""
path = self.state.get_current_image(self.category) path = self.state.get_current_image(self.category)
self.set_image(path) self.set_image(path)
def set_image(self, image_source): def set_image(self, image_source):
# 1. Convert source to QPixmap regardless of what it is # 1. Convert source to QPixmap regardless of what it is
if isinstance(image_source, Path): if isinstance(image_source, Path):
@ -170,6 +171,7 @@ class FastRegistrationPage(Page):
self.button_apply.setVisible(True) self.button_apply.setVisible(True)
self.button_back.setVisible(True) self.button_back.setVisible(True)
self.button_apply.clicked.connect(self.submit_registration) self.button_apply.clicked.connect(self.submit_registration)
self.button_back.clicked.connect(self.reverse)
self.setFixedSize(800, 600) self.setFixedSize(800, 600)
@ -188,9 +190,6 @@ class FastRegistrationPage(Page):
self.group_browser = SelectionGroup(self.content_area, "Browser", "Browser", self.state) self.group_browser = SelectionGroup(self.content_area, "Browser", "Browser", self.state)
self.group_res = SelectionGroup(self.content_area, "Resolution", "Resolution", self.state) self.group_res = SelectionGroup(self.content_area, "Resolution", "Resolution", self.state)
# Connect the signal: When Type changes, tell other groups (such as Protocol) to refresh
self.group_type.valueChanged.connect(self.handle_type_change)
self.grid.addWidget(self.group_type, 0, 0, Qt.AlignmentFlag.AlignTop) self.grid.addWidget(self.group_type, 0, 0, Qt.AlignmentFlag.AlignTop)
self.grid.addWidget(self.group_name, 0, 1, Qt.AlignmentFlag.AlignTop) self.grid.addWidget(self.group_name, 0, 1, Qt.AlignmentFlag.AlignTop)
self.grid.addWidget(self.group_proto, 1, 0, Qt.AlignmentFlag.AlignTop) self.grid.addWidget(self.group_proto, 1, 0, Qt.AlignmentFlag.AlignTop)
@ -199,12 +198,6 @@ class FastRegistrationPage(Page):
self.grid.addWidget(self.group_res, 2, 1, Qt.AlignmentFlag.AlignTop) self.grid.addWidget(self.group_res, 2, 1, Qt.AlignmentFlag.AlignTop)
self.grid.setRowStretch(3, 1) self.grid.setRowStretch(3, 1)
def handle_type_change(self, category):
"""Redraw other relevant widgets that may be affected by a change"""
if category == "Type":
# Protocol is affected by Type
self.group_proto.update_display()
def after_submission(self, result: Result): def after_submission(self, result: Result):
"""Navigate to the homepage after the completion of the registration""" """Navigate to the homepage after the completion of the registration"""
@ -223,3 +216,7 @@ class FastRegistrationPage(Page):
final_choices["Name"] = input_text final_choices["Name"] = input_text
print(f"Submitting choices: {final_choices}") print(f"Submitting choices: {final_choices}")
create_profile(potential_data=final_choices, ui_caller=self.after_submission) create_profile(potential_data=final_choices, ui_caller=self.after_submission)
def reverse(self):
self.custom_window.navigator.navigate("menu")