hydraveil-gui/gui/v2/ui/pages/create_edit/edit_page.py

214 lines
8.7 KiB
Python

from core.observers.Notifications import Notifications, EventType
from core.models.Result import Result
from core.errors.logger import logger
from gui.v2.ui.pages.create_edit.components import SelectionGroup, TextInputGroup
from gui.v2.actions.profile_actions import edit_profile
from gui.v2.presenters.state.fast_registration_state import RegistrationState
from gui.v2.ui.styles.css.fast_register import FAST_REGISTER_ONE, FAST_REGISTER_TWO
from gui.v2.ui.pages.Page import Page
from gui.v2.ui.pages.create_edit.resolution_widget import CustomResolutionDialog
from gui.v2.ui.popups.error_popup import ErrorPopup
from PyQt6.QtWidgets import QWidget, QPushButton, QGridLayout, QVBoxLayout
from PyQt6.QtCore import Qt
from typing import Optional
class EditPage(Page):
def __init__(self, page_stack, main_window, prepared=None, profile_id: Optional[int] = None):
super().__init__("EditPage", page_stack, main_window)
self.profile_id = profile_id
# 1. Permanent Structure: Created once in init
self.content_area = QWidget()
self.grid = QGridLayout(self.content_area) # Set layout once here
self.grid.setSpacing(30)
self.grid.setContentsMargins(0, 0, 0, 0)
self.setFixedSize(800, 600)
self.main_layout = QVBoxLayout(self)
self.main_layout.setContentsMargins(40, 60, 40, 60)
# Add content_area to main_layout once here
self.main_layout.addWidget(self.content_area)
self.button_apply.setVisible(True)
self.button_back.setVisible(True)
self.button_apply.clicked.connect(self.submit_edits)
self.button_back.clicked.connect(self.reverse)
self.created_display = False
def clear_ui(self):
"""Removes all widgets from the grid layout and deletes them"""
while self.grid.count():
item = self.grid.takeAt(0)
widget = item.widget()
if widget:
widget.deleteLater()
def showEvent(self, event):
if not self.created_display and self.profile_id is not None:
logger.info(f"Recreating UI for profile {self.profile_id}")
self.create_ui(self.profile_id)
self.created_display = True
def create_ui(self, profile_id: int):
if profile_id is None:
logger.error("No profile id to edit.")
return
# 2. State Reset: Wipe old widgets and old state
self.clear_ui()
self.state = RegistrationState(btn_path=self.btn_path, profile_id=profile_id)
print("Created a new RegistrationState")
# 3. Create groups, passing the category string and the state object
self.group_type = SelectionGroup(self.content_area, title="Profile Type", category="type", state=self.state, sync_required=False, btn_path=self.btn_path)
self.group_name = TextInputGroup(self.content_area, title="Name", category="name", state=self.state)
self.group_proto = SelectionGroup(self.content_area, title="Protocol", category="protocol", state=self.state, sync_required=False, btn_path=self.btn_path)
self.group_loc = SelectionGroup(self.content_area, title="Location", category="location", state=self.state, sync_required=True, btn_path=self.btn_path)
self.group_browser = SelectionGroup(self.content_area, title="Browser", category="browser", state=self.state, sync_required=True, btn_path=self.btn_path)
self.group_res = SelectionGroup(self.content_area, title="Resolution", category="resolution", state=self.state, sync_required=False, btn_path=self.btn_path)
# 3. Quality Control: Force columns to share width equally
self.grid.setColumnStretch(0, 1)
self.grid.setColumnStretch(1, 1)
# 4. adding groups in rows of 2 items each:
self.grid.addWidget(self.group_type, 0, 0)
self.grid.addWidget(self.group_name, 0, 1)
self.grid.addWidget(self.group_proto, 1, 0)
self.grid.addWidget(self.group_loc, 1, 1)
self.grid.addWidget(self.group_browser, 2, 0)
self.grid.addWidget(self.group_res, 2, 1)
# 5. Custom Buttons:
custom_button = QPushButton("Custom Res", self.content_area) # Parent to content_area
custom_button.setStyleSheet(FAST_REGISTER_ONE)
custom_button.clicked.connect(self.show_custom_res_dialog)
self.grid.addWidget(custom_button, 3, 1, Qt.AlignmentFlag.AlignCenter)
self.grid.setRowStretch(4, 1)
# 6. UI State updates:
Notifications.subscribe(EventType.SYNC_COMPLETE, self.update_post_sync)
def after_submission(self, result: Result):
if result.valid:
print(f"Updated Profile {self.profile_id}")
self.created_display = False # Allow showEvent to trigger create_ui next time
self.custom_window.navigator.navigate("menu")
def _on_popup_answer(self, user_choice: bool, passed_result: dict):
if user_choice and passed_result:
# Remove the first warning from the dictionary
first_key = next(iter(passed_result))
del passed_result[first_key]
# Loop back to check if more warnings remain
self.warn_or_proceed(warnings_dict=passed_result)
def warn_or_proceed(self, warnings_dict: Optional[dict] = None):
# Initial entry point: determine if we have warnings
if warnings_dict is None:
pre_edit = self.state.before_we_proceed()
# If we can proceed immediately, skip to the task
if pre_edit.proceed:
self.proceed_with_edit(pre_edit.whats_different)
return
# Start the warning loop with the warnings_dict
warnings_dict = pre_edit.warnings_dict
# If there are still warnings to address
if warnings_dict:
first_key = next(iter(warnings_dict))
error_popup = ErrorPopup(
choice=True,
title=first_key,
message=warnings_dict[first_key],
end_app=False,
on_answer=self._on_popup_answer,
passed_result=warnings_dict,
)
error_popup.show()
else:
# No warnings left, execute the final task
# We call before_we_proceed one last time to get the final different_dict
final_state = self.state.before_we_proceed()
self.proceed_with_edit(final_state.whats_different)
def proceed_with_edit(self, different_content):
print(f"different_content is {different_content}")
edit_profile(
profile_id=self.profile_id,
potential_data=different_content,
ui_caller=self.after_submission
)
self.created_display = False
def submit_edits(self):
# name
input_text = self.group_name.text_input.text()
if not input_text:
self.show_a_popup("Pick a name in the top right box.")
return
self.state.set_selection(category="name", value=input_text)
self.warn_or_proceed()
def reverse(self):
# nothing changed, bounce:
if not self.state.is_anything_different():
self.actually_leave()
return
error_popup = ErrorPopup(
choice=True,
title="Unsaved changes",
message="Are you sure you want to leave with unfinished changes?",
end_app=False,
on_answer=self._after_reverse_decision,
passed_result=None,
)
error_popup.show()
def _after_reverse_decision(self, boolean_choice: bool, passed_result=None):
if boolean_choice:
self.actually_leave()
def actually_leave(self):
self.created_display = False
self.custom_window.navigator.navigate("menu")
def update_post_sync(self, string_notification: str):
"""At the completion of the sync, update the button styles"""
buttons_required_sync = [self.group_loc, self.group_browser]
for each_button in buttons_required_sync:
each_button.apply_styles_to_buttons(sync_required=False)
def show_custom_res_dialog(self):
# Shows the popup asking for the custom choice:
dialog = CustomResolutionDialog(
style_sheet=FAST_REGISTER_TWO,
parent=self
)
# if it passes the validation screen inside it, then update state:
dialog.resolution_selected.connect(self.handle_resolution_update)
dialog.exec()
def handle_resolution_update(self, resolution):
"""Update State with the selected Resolution"""
success = self.state.set_selection("resolution", resolution)
if success:
print(f"Resolution updated to {resolution}")
else:
print("Custom resolution failed validation.")