From 6a38019724880bb99ddb4ff155a4786bf3711379 Mon Sep 17 00:00:00 2001 From: SimplifiedPrivacy Date: Wed, 4 Nov 2026 19:39:17 -0500 Subject: [PATCH] New fast profile page, state management, and data filters --- gui/main_ui.py | 1 + gui/resources/images/hysteria2_button.png | Bin 0 -> 4441 bytes gui/v2/actions/config.py | 8 +- gui/v2/infrastructure/page_registry.py | 10 +- gui/v2/presenters/data/app_data.py | 42 ++++ gui/v2/presenters/data/location_data.py | 50 +++++ gui/v2/presenters/data/protocol_data.py | 20 ++ gui/v2/presenters/data/resolution_data.py | 69 ++++++ gui/v2/presenters/data/type_data.py | 26 +++ .../presenters/image_tools/button_factory.py | 123 +++++++++++ .../state/fast_registration_state.py | 164 ++++++++++++++ gui/v2/ui/pages/fast7b.py | 206 ++++++++++++++++++ gui/v2/ui/pages/fast_registration_page.py | 107 +-------- gui/v2/ui/styles/css/fast_register.py | 77 +++++++ 14 files changed, 800 insertions(+), 103 deletions(-) create mode 100644 gui/resources/images/hysteria2_button.png create mode 100644 gui/v2/presenters/data/app_data.py create mode 100644 gui/v2/presenters/data/location_data.py create mode 100644 gui/v2/presenters/data/protocol_data.py create mode 100644 gui/v2/presenters/data/resolution_data.py create mode 100644 gui/v2/presenters/data/type_data.py create mode 100644 gui/v2/presenters/image_tools/button_factory.py create mode 100644 gui/v2/presenters/state/fast_registration_state.py create mode 100644 gui/v2/ui/pages/fast7b.py create mode 100644 gui/v2/ui/styles/css/fast_register.py diff --git a/gui/main_ui.py b/gui/main_ui.py index 3ced655..492f270 100755 --- a/gui/main_ui.py +++ b/gui/main_ui.py @@ -1001,5 +1001,6 @@ def start_ui(force_sync): launch_app() # finally, start the GLOBAL event loop for the entire application. + calculate_max_screensize(app) sys.exit(app.exec()) diff --git a/gui/resources/images/hysteria2_button.png b/gui/resources/images/hysteria2_button.png new file mode 100644 index 0000000000000000000000000000000000000000..d9887d74d4d506a9f2d72bf5fecf32d94235188f GIT binary patch literal 4441 zcmV-f5vJ~mP)V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9+G1Oe63^1}!$OQ5vqw zTjjK{RRVt-A~%xTZ@<0S@Ao$VSglsgMZ}UM)%*Sa6`rZn;n3NlIeNqxfyeeEw>ARb zqAT*qf&~uCNaQUoExSQ9HjU^PpPii@ot&Ih_htWac6K&l07RDMo9dXP_!UmE5A6w8 z1IDe(bSUo)vTP6=g<5pt7H(Bw8Hv2Kw6sBzr22L1)=^$wJ_O)!IJ}WaWHecv4u``V z8z4H;@z?d<|kA+~weWIWe1EgO;RH9RLKCfZM*KAo^?zqGWpxvHuv z-USm1g)Vn=bhHC>bab@0w6xsxcs%~(m{`N}^y$-Qnwy(PtE#HHG#ZxGS;VXaw6gfP zaVvS8M@h6NIz#w!PWvFjG7>qYHazuEH!8JIK1(}zq-5;0qn6pkEKeji+5lo&=@$hKJW>C zqvn&ZD3Qk+mnMdA6-^*f^Q{*N(g!JCJj2P-)h|pa}(@extkb8~Z1k@C{i4Ng_*xgnWm)Mx!wLkk;g=Z`9 zbc?4KhADEBG)#62;pt)7C%Ob(M@9Ewv8rn@wkww826v~1z>}U5(L;s_eA6a36%`NS z7WdzZYIvIDgWy3iPNSQJmDhz^wu+n?OYCw7*oT#!xYQn8SzKYMR5lPD7YnBiT37n= z%eDOGHyzw{*WJpI&rFe=>LH2pTQQ39}pv#;R{Olr1A=L`3`GY~R8-XPhd<IGQ6q|vBFITPCo&Qh7W;8-3LZ+44WlswSaw}YSmyp`f& zP}!5@u(-$pEU*@M9W$$&EM+!ra&zoh8~5G!4_K`r?8!4S{Gb({AoBP@Gpm~{RXRI; zY}~qQXHSyJC~`>3>Lwu*m99&97c2CWi0> f@M1RhB$@vQ bool: os.makedirs(gui_cache_home, exist_ok=True) diff --git a/gui/v2/infrastructure/page_registry.py b/gui/v2/infrastructure/page_registry.py index 934a887..f353fe5 100755 --- a/gui/v2/infrastructure/page_registry.py +++ b/gui/v2/infrastructure/page_registry.py @@ -28,7 +28,7 @@ PAGE_REGISTRY = { "ticket_crypto_picker": ("gui.v2.ui.pages.ticket_crypto_picker_page", "TicketCryptoPickerPage"), "ticket_prep": ("gui.v2.ui.pages.ticket_prep_page", "TicketPrepPage"), "ticket_or_billing_choice": ("gui.v2.ui.pages.ticket_or_billing_choice_page", "TicketOrBillingChoicePage"), - "fast_registration": ("gui.v2.ui.pages.fast_registration_page", "FastRegistrationPage"), + "fast_registration": ("gui.v2.ui.pages.fast7b", "FastRegistrationPage"), "fast_mode_prompt": ("gui.v2.ui.pages.fast_mode_prompt_page", "FastModePromptPage"), } @@ -41,10 +41,12 @@ PRELOAD_SKIP = { ASYNC_PREPARE = { "settings", - "fast_registration", "editor", } +# "fast_registration", + + REGULAR_FLOW_ONLY = { "protocol", "location", @@ -66,7 +68,6 @@ PRELOAD_ORDER = [ "policy_suggestion", "systemwide_prompt", "fast_mode_prompt", - "fast_registration", "id", "protocol", "location", @@ -82,6 +83,9 @@ PRELOAD_ORDER = [ "sync_screen", ] +# "fast_registration", + + # "duration_selection", # "payment_details", # "ticket_or_billing_choice", diff --git a/gui/v2/presenters/data/app_data.py b/gui/v2/presenters/data/app_data.py new file mode 100644 index 0000000..5db0cca --- /dev/null +++ b/gui/v2/presenters/data/app_data.py @@ -0,0 +1,42 @@ +from core.models.orm_calls.application_version_calls import get_all_supported_apps +from core.errors.logger import logger + +from pathlib import Path + +def get_list_of_apps() -> list: + database_object = get_all_supported_apps() + + if not database_object.valid: + logger.error(f"Critical Database error with fetching all supported apps. {database_object.error_type} with {database_object.message}") + return None + + list_of_data = list(database_object.data) + return list_of_data + +def get_app_display_data(button_path: str) -> dict: + all_apps = get_list_of_apps() + + display_dto = {} + + for each_app in all_apps: + app_id = each_app.id + app_name = each_app.application_code + version = each_app.version_number + button_image_path = f"{app_name}_button.png" + + full_image_path = Path(button_path, button_image_path) + default_path = Path(button_path, "default_location_button.png") + + data = { + 'path': default_path, + 'name': app_name, + 'second_line': version, + 'existing_icon': full_image_path + } + + display_dto[app_id] = data + + return display_dto + + + diff --git a/gui/v2/presenters/data/location_data.py b/gui/v2/presenters/data/location_data.py new file mode 100644 index 0000000..efa84c5 --- /dev/null +++ b/gui/v2/presenters/data/location_data.py @@ -0,0 +1,50 @@ +from core.models.orm_calls.location_calls import execute_all_locations +from core.errors.logger import logger + +from pathlib import Path + + +def get_all_locations(): + """Use core to fetch all locations with SQL""" + location_object = execute_all_locations() + + if not location_object.valid: + critical_error = f"Got invalid SQL Query which could not be solved by the wrapper, with error message {location_object.message} and type {location_object.error_type}" + logger.error(critical_error) + return None + + list_of_all_locations = location_object.data + return list_of_all_locations + + +def get_location_display_data(button_path: str) -> dict|None: + """Organize display data for the UI""" + all_locations = get_all_locations() + + if all_locations is None: + return None + + location_display_dto = {} + + for each_location in all_locations: + location_id = each_location.id + location_name = each_location.country_name + country_code = each_location.country_code + provider = each_location.operator.name + code = each_location.code + button_image_path = f"button_{country_code}_{code}.png" + + full_image_path = Path(button_path, button_image_path) + default_path = Path(button_path, "default_location_button.png") + + data = { + 'path': default_path, + 'name': location_name, + 'second_line': provider, + 'existing_icon': full_image_path + } + + location_display_dto[location_id] = data + + return location_display_dto + diff --git a/gui/v2/presenters/data/protocol_data.py b/gui/v2/presenters/data/protocol_data.py new file mode 100644 index 0000000..1393bdc --- /dev/null +++ b/gui/v2/presenters/data/protocol_data.py @@ -0,0 +1,20 @@ + +from core.services.profiles.filter_protocols import get_filtered_protocol_list +from core.models.enum_models import ProtocolChoice + +from pathlib import Path + +def get_protocol_button_data(button_path: str) -> dict|None: + """Return a dict of protocols with their image paths.""" + protocol_list = get_filtered_protocol_list() + + protocol_display_dto = {} + + for each_protocol in protocol_list: + name_as_string = each_protocol.value + button_image_path = f"{name_as_string}_button.png" + full_image_path = Path(button_path, button_image_path) + protocol_display_dto[each_protocol] = full_image_path + + return protocol_display_dto + diff --git a/gui/v2/presenters/data/resolution_data.py b/gui/v2/presenters/data/resolution_data.py new file mode 100644 index 0000000..45a72e7 --- /dev/null +++ b/gui/v2/presenters/data/resolution_data.py @@ -0,0 +1,69 @@ +from gui.v2.infrastructure.screen_size import get_max_screensize +from gui.v2.actions.config import get_registrations + + +PRE_MADE_RESOLUTIONS = [ + '800x600', '1024x760', '1152x1080', '1200x1000', + '1280x1024', '1300x900', '1920x1080', '2560x1440', + '2560x1600', '1920x1440', '1792x1344', '2048x1152' +] + +def are_dynamic_larger_profiles_enabled(): + registration_settings = get_registrations() + return registration_settings.get("dynamic_larger_profiles", False) + + +def _get_dynamic_resolution_list(host_width: int, host_height: int, full_btn_path: str) -> list: + """Get a list of resolutions slightly smaller than the host, counting down by incriments of 50, after adjusting for heights too long""" + + adjusted_host_height = round(host_height * 0.8) + dynamic_resolutions = [] + + for i in range(5): + new_height = host_width - (50 * (i + 1)) + new_width = adjusted_host_height - (50 * (i + 1)) + resolution_as_string = f"{str(new_height)}x{str(new_width)}" + dynamic_resolutions.append(resolution_as_string) + + # print(f"dynamic_resolutions are {dynamic_resolutions}") + return dynamic_resolutions + + +def _get_filtered_premade_list(host_width: int, host_height: int) -> list: + """Get a list of resolutions that fit with a small buffer""" + premade_resolutions = [] + + adjusted_host_height = host_height - 50 + adjusted_host_width = host_width - 50 + + for each_pre_made in PRE_MADE_RESOLUTIONS: + premade_width, premade_height = each_pre_made.split("x") + + if int(premade_width) > adjusted_host_width: + # print(f"skipping {each_pre_made} due to width. the premade width is {premade_width} which is larger than the host of {adjusted_host_width}") + continue + + if int(premade_height) > adjusted_host_height: + # print(f"skipping {each_pre_made} due to height. the premade height is {premade_height} which is larger than the host of {adjusted_host_height}") + continue + + premade_resolutions.append(each_pre_made) + + # print(f"final premade_resolutions {premade_resolutions}") + return premade_resolutions + +def get_resolution_data(btn_path: str) -> list: + max_screen_size = get_max_screensize() + # print(f"max_screen_size is {max_screen_size}") + host_w, host_h = max_screen_size.split("x") + + host_width = int(host_w) + host_height = int(host_h) + + dynamic_enabled = are_dynamic_larger_profiles_enabled() + + if dynamic_enabled: + return _get_dynamic_resolution_list(host_width=host_width, host_height=host_height) + + return _get_filtered_premade_list(host_width=host_width, host_height=host_height) + diff --git a/gui/v2/presenters/data/type_data.py b/gui/v2/presenters/data/type_data.py new file mode 100644 index 0000000..2767c04 --- /dev/null +++ b/gui/v2/presenters/data/type_data.py @@ -0,0 +1,26 @@ +from core.models.BaseProfile import ProfileType +from core.models.enum_models import get_list_of +from core.errors.logger import logger + +from pathlib import Path + +def get_profile_type_data(button_path: str) -> dict|None: + """Return a dict of Profile types with their image paths.""" + profile_types_list = get_list_of(ProfileType) + + display_dto = {} + + for each_type in profile_types_list: + + if each_type == ProfileType.SYSTEM: + button_image_path = "system-wide.png" + elif each_type == ProfileType.SESSION: + button_image_path = "browser-only.png" + else: + logger.error("Currently unsupported profile type") + return None + + full_image_path = Path(button_path, button_image_path) + display_dto[each_type] = full_image_path + + return display_dto diff --git a/gui/v2/presenters/image_tools/button_factory.py b/gui/v2/presenters/image_tools/button_factory.py new file mode 100644 index 0000000..8e38b57 --- /dev/null +++ b/gui/v2/presenters/image_tools/button_factory.py @@ -0,0 +1,123 @@ +from PyQt6.QtWidgets import QApplication +from PyQt6.QtGui import QPixmap, QPainter, QColor, QFont, QTransform +from PyQt6.QtCore import Qt + +import os + +def create_button_image(first_line, fallback_image_path, second_line=None, existing_icon_path=None): + # 1. Determine Base Image + if existing_icon_path: + # Wrap in str() to convert Path object to string + base_image = QPixmap(str(existing_icon_path)) + if base_image.isNull(): + # Wrap in str() here as well + base_image = QPixmap(str(fallback_image_path)) + draw_location_text = False + else: + # Wrap in str() here as well + base_image = QPixmap(str(fallback_image_path)) + draw_location_text = True + + if base_image.isNull(): + return None + + painter = QPainter(base_image) + try: + # 2. Draw Location Name + if draw_location_text: + font_size = 12 + app_font = QApplication.font() + app_font.setPointSize(font_size) + app_font.setWeight(QFont.Weight.Bold) + + # Dynamic scaling based on text length + text_length = len(first_line) + if text_length <= 10: + font_stretch, tw_scale, th_scale = 100, 1.1, 1.4 + elif text_length <= 15: + font_stretch, tw_scale, th_scale = 90, 1.0, 2.0 + else: + font_stretch, tw_scale, th_scale = 100, 1.1, 4.5 + + app_font.setStretch(font_stretch) + painter.setFont(app_font) + + # Font size shrink-to-fit logic + text_rect = painter.fontMetrics().boundingRect(first_line) + while text_rect.width() > 110 and font_size > 5: + font_size -= 1 + app_font.setPointSize(font_size) + painter.setFont(app_font) + text_rect = painter.fontMetrics().boundingRect(first_line) + + # Position calculations + x = ((base_image.width() - text_rect.width()) // 2) - 30 + y = ((base_image.height() + text_rect.height()) // 2) - 15 + + transform = QTransform() + transform.scale(tw_scale, th_scale) + painter.setTransform(transform) + + x_scaled, y_scaled = int(x / tw_scale), int(y / th_scale) + + # Shadow and Main Text + painter.setPen(QColor(0, 0, 0)) + painter.drawText(x_scaled + 1, y_scaled + 1, first_line) + painter.setPen(QColor(0, 255, 255)) + painter.drawText(x_scaled, y_scaled, first_line) + painter.setTransform(QTransform()) + + # 3. Draw second_line Text + if second_line: + painter.setPen(QColor(128, 128, 128)) + second_line_font = QApplication.font() + second_line_font.setPointSize(7) + second_line_font.setWeight(QFont.Weight.Normal) + painter.setFont(second_line_font) + + p_rect = painter.fontMetrics().boundingRect(second_line) + px = ((base_image.width() - p_rect.width()) // 2) - 30 + py = 50 + painter.drawText(int(px) + 5, int(py) + 2, second_line) + finally: + painter.end() + + return base_image + + + +def create_resolution_button_image(btn_path: str, resolution_text: str): + """Create the button image for a given text of screen resolution""" + + template_path = os.path.join( + btn_path, "resolution_template_button.png") + + if os.path.exists(template_path): + base_image = QPixmap(template_path) + if 'Resolution' in resolution_text: + base_image = base_image.scaled(195, 50) + font_size = 10 + else: + base_image = base_image.scaled(187, 75) + font_size = 13 + else: + base_image = QPixmap(185, 75) + base_image.fill(QColor(44, 62, 80)) + font_size = 13 + + painter = QPainter(base_image) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + + font = QFont() + font.setPointSize(font_size) + font.setBold(True) + painter.setFont(font) + + painter.setPen(QColor(0, 255, 255)) + + text_rect = base_image.rect() + painter.drawText(text_rect, Qt.AlignmentFlag.AlignCenter | + Qt.AlignmentFlag.AlignVCenter, resolution_text) + + painter.end() + return base_image diff --git a/gui/v2/presenters/state/fast_registration_state.py b/gui/v2/presenters/state/fast_registration_state.py new file mode 100644 index 0000000..ec72da1 --- /dev/null +++ b/gui/v2/presenters/state/fast_registration_state.py @@ -0,0 +1,164 @@ +from core.services.profiles.filter_protocols import protocol_matches_profile_type + +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.protocol_data import get_protocol_button_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.image_tools.button_factory import create_button_image, create_resolution_button_image + + +from pathlib import Path + +class RegistrationState: + def __init__(self, btn_path): + self.btn_path = btn_path + self.all_options = {} # Stores the Path (static) or Dict (dynamic) + self.selections = {} # Stores current ID + self.order_map = {} # Stores ID order + self.pixmap_cache = {} # Caches generated QPixmaps to prevent lag + + # Filters where one data category affects another one. (in this case Protocol is affected by Type) + self._filter_map = { + "Protocol": self.is_protocol_valid, + } + + self._load_all_data() + + def _register_category(self, category, data, default_idx=0): + """Helper to handle the boilerplate of setting up a category.""" + # If data is a list (like resolutions), convert to a dict where keys are the values + 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): + """Fetch the data via external functions, and then register it for the UI""" + load_config = { + "Type": (get_profile_type_data, 0), + "Protocol": (get_protocol_button_data, 0), + "Resolution": (get_resolution_data, 0), + "Location": (get_location_display_data, 0), + "Browser": (get_app_display_data, 0), + } + + for category, (loader_func, default_idx) in load_config.items(): + data = loader_func(self.btn_path) + self._register_category(category, data, default_idx) + + def get_current_image(self, category): + """Use the data to create an image. It could be either static or dynamic.""" + current_id = self.selections[category] + if current_id is None: + return None + + 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_key = f"{category}_{current_id}" + if cache_key in self.pixmap_cache: + return self.pixmap_cache[cache_key] + + # dynamic creation of the image with the nested dict: + if isinstance(data, dict): + pixmap = create_button_image( + first_line=data.get('name', ''), + fallback_image_path=data.get('path'), + second_line=data.get('second_line'), + existing_icon_path=data.get('existing_icon') + ) + self.pixmap_cache[cache_key] = 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: + print(f"No valid options found for {category}.") + return None + + # After the selection is updated, if we just changed the Type, + # we must ensure the current Protocol is still valid. + if category == "Type": + self._ensure_protocol_valid() + + return self.get_current_image(category) + + + def get_final_choices(self): + return self.selections diff --git a/gui/v2/ui/pages/fast7b.py b/gui/v2/ui/pages/fast7b.py new file mode 100644 index 0000000..5260e21 --- /dev/null +++ b/gui/v2/ui/pages/fast7b.py @@ -0,0 +1,206 @@ +from gui.v2.presenters.state.fast_registration_state import RegistrationState +from gui.v2.ui.styles.css.fast_register import ENTER_NAME_TEXT, NAME_TEXT_STYLE, GROUP_TITLE_LABEL, DISPLAY_BOX_STYLE +from gui.v2.ui.pages.Page import Page + +from pathlib import Path + +from PyQt6 import QtWidgets, QtCore, QtGui +from PyQt6.QtWidgets import QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout, QGridLayout, QSizePolicy, QLineEdit +from PyQt6.QtGui import QPixmap +from PyQt6.QtCore import Qt, pyqtSignal + +class TextInputGroup(QWidget): + def __init__(self, parent, title, category, state): + super().__init__(parent) + self.category = category + self.state = state + + # Match the width of the SelectionGroup + self.setMinimumWidth(260) + + self.main_layout = QVBoxLayout(self) + self.main_layout.setContentsMargins(0, 0, 0, 0) + self.main_layout.setSpacing(5) + self.main_layout.setAlignment(Qt.AlignmentFlag.AlignTop) + + # Same title style as SelectionGroup + self.title_label = QLabel(title) + self.title_label.setStyleSheet(NAME_TEXT_STYLE) + self.main_layout.addWidget(self.title_label) + + # Row layout to hold the input field + self.row_layout = QHBoxLayout() + self.row_layout.setSpacing(10) + + self.text_input = QLineEdit() + + # Set initial value from state if it exists + # initial_text = self.state.get_value(self.category) if hasattr(self.state, 'get_value') else "" + # self.text_input.setText(initial_text) + + # Match the display_box styling + self.text_input.setFixedSize(240, 35) # Slightly shorter than the image box for better text look + self.text_input.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) + self.text_input.setStyleSheet(ENTER_NAME_TEXT) + + # Update state in real-time as user types + self.text_input.textChanged.connect(self.update_state) + + self.row_layout.addWidget(self.text_input) + + # Center the input field within the row layout + self.row_layout.setAlignment(Qt.AlignmentFlag.AlignCenter) + + self.main_layout.addLayout(self.row_layout) + + def update_state(self, text): + if hasattr(self.state, 'set_value'): + self.state.set_value(self.category, text) + +class SelectionGroup(QWidget): + # Define a signal that tells the world this widget's value changed + valueChanged = pyqtSignal(str) # Pass the category name + + def __init__(self, parent, title, category, state): + super().__init__(parent) + self.category = category + self.state = state + + # Ensure the group widget itself is wide enough to hold the layout + # (30px prev + 185px box + 30px next + spacing) + self.setMinimumWidth(260) + + self.main_layout = QVBoxLayout(self) + self.main_layout.setContentsMargins(0, 0, 0, 0) + self.main_layout.setSpacing(5) + self.main_layout.setAlignment(Qt.AlignmentFlag.AlignTop) + + self.title_label = QLabel(title) + self.title_label.setStyleSheet(GROUP_TITLE_LABEL) + self.main_layout.addWidget(self.title_label) + + self.row_layout = QHBoxLayout() + self.row_layout.setSpacing(10) # Add a little gap between buttons and box + + self.btn_prev = QPushButton("<") + self.btn_prev.setFixedWidth(30) + self.btn_prev.clicked.connect(lambda: self.change_image(-1)) + + self.display_box = QLabel() + self.display_box.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) + + # --- STRICT SIZE POLICY --- + self.display_box.setFixedSize(185, 75) + # widget MUST be exactly this size + self.display_box.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) + + self.display_box.setStyleSheet(DISPLAY_BOX_STYLE) + + self.btn_next = QPushButton(">") + self.btn_next.setFixedWidth(30) + self.btn_next.clicked.connect(lambda: self.change_image(1)) + + # Add widgets without stretch factors to maintain the fixed-size integrity + self.row_layout.addWidget(self.btn_prev) + self.row_layout.addWidget(self.display_box) + self.row_layout.addWidget(self.btn_next) + + self.main_layout.addLayout(self.row_layout) + + + def showEvent(self, event): + super().showEvent(event) + self.update_display() + + def change_image(self, direction): + new_path = self.state.cycle_selection(self.category, direction) + self.set_image(new_path) + # Emit the signal so the parent knows something happened + self.valueChanged.emit(self.category) + + def update_display(self): + path = self.state.get_current_image(self.category) + self.set_image(path) + + def set_image(self, image_source): + # 1. Convert source to QPixmap regardless of what it is + if isinstance(image_source, Path): + pixmap = QPixmap(str(image_source)) + elif isinstance(image_source, QPixmap): + pixmap = image_source + else: + return + + if pixmap.isNull(): + return + + # 2. Apply the scaling logic we built in the previous step + box_width = self.display_box.width() + box_height = self.display_box.height() + + if pixmap.width() > box_width or pixmap.height() > box_height: + scaled_pixmap = pixmap.scaled( + box_width, + box_height, + QtCore.Qt.AspectRatioMode.KeepAspectRatio, + QtCore.Qt.TransformationMode.SmoothTransformation + ) + self.display_box.setPixmap(scaled_pixmap) + else: + self.display_box.setPixmap(pixmap) + + +class FastRegistrationPage(Page): + def __init__(self, page_stack, main_window, prepared=None): + super().__init__("FastRegistration", page_stack, main_window) + + # 1. Initialize State + self.state = RegistrationState(btn_path=self.btn_path) + + # Banner temp disabled: + # self.title.setGeometry(550, 40, 250, 40) + # self.title.setText("Fast Registration") + + self.button_apply.setVisible(True) + self.button_back.setVisible(True) + self.button_apply.clicked.connect(self.submit_registration) + + self.setFixedSize(800, 600) + + self.content_area = QWidget(self) + self.content_area.setGeometry(100, 60, 600, 370) + + self.grid = QGridLayout(self.content_area) + self.grid.setSpacing(30) + self.grid.setContentsMargins(0, 0, 0, 0) + + # 2. Create groups, passing the category string and the state object + self.group_type = SelectionGroup(self.content_area, "Profile Type", "Type", self.state) + self.group_name = TextInputGroup(self.content_area, "Name", "Name", self.state) + self.group_proto = SelectionGroup(self.content_area, "Protocol", "Protocol", self.state) + self.group_loc = SelectionGroup(self.content_area, "Location", "Location", self.state) + self.group_browser = SelectionGroup(self.content_area, "Browser", "Browser", self.state) + self.group_res = SelectionGroup(self.content_area, "Resolution", "Resolution", self.state) + + # Connect the signal: When Type changes, tell 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_name, 0, 1, Qt.AlignmentFlag.AlignTop) + self.grid.addWidget(self.group_proto, 1, 0, Qt.AlignmentFlag.AlignTop) + self.grid.addWidget(self.group_loc, 1, 1, Qt.AlignmentFlag.AlignTop) + self.grid.addWidget(self.group_browser, 2, 0, Qt.AlignmentFlag.AlignTop) + self.grid.addWidget(self.group_res, 2, 1, Qt.AlignmentFlag.AlignTop) + 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 submit_registration(self): + """Get current choices from state, and submit.""" + final_choices = self.state.get_final_choices() + print(f"Submitting choices: {final_choices}") + diff --git a/gui/v2/ui/pages/fast_registration_page.py b/gui/v2/ui/pages/fast_registration_page.py index 31b40ff..d7439f5 100755 --- a/gui/v2/ui/pages/fast_registration_page.py +++ b/gui/v2/ui/pages/fast_registration_page.py @@ -8,14 +8,17 @@ from PyQt6.QtGui import QIcon, QPixmap, QTransform from PyQt6.QtCore import QSize from PyQt6 import QtCore -from core.controllers.ProfileController import ProfileController +# from core.controllers.ProfileController import ProfileController from gui.v2.actions.profile_order import append_profile_to_visual_order from gui.v2.actions.singbox_prereqs import singbox_prereqs_installed + +from gui.v2.ui.styles.css.fast_register import FAST_REGISTER_ONE, FAST_REGISTER_TWO, NAME_ONE, HOST_INFO_ONE from gui.v2.ui.pages.Page import Page from gui.v2.ui.pages.browser_page import BrowserPage from gui.v2.ui.pages.location_page import LocationPage from gui.v2.ui.pages.location_verification_page import LocationVerificationPage + from gui.v2.workers.page_data_worker import PageDataWorker from gui.v2.workers.worker_thread import WorkerThread @@ -62,8 +65,7 @@ class FastRegistrationPage(Page): self.name = QLineEdit(self) self.name.setPlaceholderText("Enter name") self.name.setGeometry(265, 70, 190, 30) - self.name.setStyleSheet( - "color: cyan; border: 1px solid #666666; border-radius: 3px; background-color: rgba(0, 0, 0, 0.3);") + self.name.setStyleSheet(NAME_ONE) self.name.setCursor(QtCore.Qt.CursorShape.IBeamCursor) self.name.focusInEvent = lambda event: self.name_hint.hide() self.name.focusOutEvent = lambda event: self.name_hint.show( @@ -86,61 +88,10 @@ class FastRegistrationPage(Page): self.initialize_default_selections() - @staticmethod - def prepare_data(custom_window): - return ProfileController.get_all() - - def initialize_default_selections(self): - if not self.selected_values['location']: - locations = self._available_locations_for_protocol() - if locations: - random_index = random.randint(0, len(locations) - 1) - self.selected_values['location'] = locations[random_index] - else: - self._select_valid_location_for_protocol() - - if not self.selected_values['browser']: - browsers = self.connection_manager.get_browser_list() - if browsers: - random_index = random.randint(0, len(browsers) - 1) - self.selected_values['browser'] = browsers[random_index] - - def get_next_available_profile_id(self, profiles=None) -> int: - if profiles is None: - profiles = ProfileController.get_all() - if not profiles: - return 1 - - existing_ids = sorted(profiles.keys()) - - for i in range(1, max(existing_ids) + 2): - if i not in existing_ids: - return i - - return 1 - def showEvent(self, event): super().showEvent(event) - self.initialize_default_selections() self.create_interface_elements() - self._start_profiles_prefetch() - def _start_profiles_prefetch(self): - worker = PageDataWorker( - "fast_registration", FastRegistrationPage.prepare_data, self.custom_window) - worker.data_ready.connect( - lambda name, profiles: self._on_profiles_prefetched(profiles)) - worker.finished.connect( - lambda w=worker: self._cleanup_fast_reg_worker(w)) - self._fast_reg_workers.add(worker) - worker.start() - - def _on_profiles_prefetched(self, profiles): - self._prefetched_profiles = profiles - - def _cleanup_fast_reg_worker(self, worker): - self._fast_reg_workers.discard(worker) - worker.deleteLater() def create_interface_elements(self): for label in self.labels: @@ -159,8 +110,7 @@ class FastRegistrationPage(Page): f"Host Screen: {self.update_status.host_screen_width}x{self.update_status.host_screen_height}", self) self.host_info_label.setGeometry(415, 470, 250, 20) self.host_info_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) - self.host_info_label.setStyleSheet( - "color: #00ffff; font-size: 13px; font-weight: bold;") + self.host_info_label.setStyleSheet(HOST_INFO_ONE) self.host_info_label.show() self.labels.append(self.host_info_label) @@ -435,19 +385,7 @@ class FastRegistrationPage(Page): custom_button = QPushButton("Custom", self) custom_button.setGeometry(435, 430, 185, 30) - custom_button.setStyleSheet(""" - QPushButton { - background-color: rgba(0, 255, 255, 0.1); - color: #00ffff; - border: 1px solid #00ffff; - border-radius: 5px; - font-size: 12px; - font-weight: bold; - } - QPushButton:hover { - background-color: rgba(0, 255, 255, 0.2); - } - """) + custom_button.setStyleSheet(FAST_REGISTER_ONE) custom_button.clicked.connect(self.show_custom_res_dialog) custom_button.show() self.buttons.append(custom_button) @@ -457,36 +395,7 @@ class FastRegistrationPage(Page): dialog.setWindowTitle("Custom Resolution") dialog.setFixedSize(300, 150) dialog.setModal(True) - dialog.setStyleSheet(""" - QDialog { - background-color: #2c3e50; - border: 2px solid #00ffff; - border-radius: 10px; - } - QLabel { - color: white; - font-size: 12px; - } - QLineEdit { - background-color: #34495e; - color: white; - border: 1px solid #00ffff; - border-radius: 5px; - padding: 5px; - font-size: 12px; - } - QPushButton { - background-color: #2c3e50; - color: white; - border: 2px solid #00ffff; - border-radius: 5px; - padding: 8px; - font-size: 12px; - } - QPushButton:hover { - background-color: #34495e; - } - """) + dialog.setStyleSheet(FAST_REGISTER_TWO) layout = QVBoxLayout() input_layout = QHBoxLayout() diff --git a/gui/v2/ui/styles/css/fast_register.py b/gui/v2/ui/styles/css/fast_register.py new file mode 100644 index 0000000..3174144 --- /dev/null +++ b/gui/v2/ui/styles/css/fast_register.py @@ -0,0 +1,77 @@ + +ENTER_NAME_TEXT = """ + QLineEdit { + background-color: #222; + border: 2px solid #555; + border-radius: 5px; + color: white; + padding-left: 5px; + } + QLineEdit:focus { + border: 2px solid #888; + } +""" + +NAME_TEXT_STYLE = "color: #cacbcb; font-weight: bold; font-family: Arial;" + + +GROUP_TITLE_LABEL = "color: #cacbcb; font-weight: bold; font-family: Arial;" + +DISPLAY_BOX_STYLE = "background-color: #222; border: 2px solid #555; border-radius: 5px;" + +# Legacy below + + +FAST_REGISTER_ONE = """ + QPushButton { + background-color: rgba(0, 255, 255, 0.1); + color: #00ffff; + border: 1px solid #00ffff; + border-radius: 5px; + font-size: 12px; + font-weight: bold; + } + QPushButton:hover { + background-color: rgba(0, 255, 255, 0.2); + } +""" + + +FAST_REGISTER_TWO = """ + QDialog { + background-color: #2c3e50; + border: 2px solid #00ffff; + border-radius: 10px; + } + QLabel { + color: white; + font-size: 12px; + } + QLineEdit { + background-color: #34495e; + color: white; + border: 1px solid #00ffff; + border-radius: 5px; + padding: 5px; + font-size: 12px; + } + QPushButton { + background-color: #2c3e50; + color: white; + border: 2px solid #00ffff; + border-radius: 5px; + padding: 8px; + font-size: 12px; + } + QPushButton:hover { + background-color: #34495e; + } +""" + + +NAME_ONE = "color: cyan; border: 1px solid #666666; border-radius: 3px; background-color: rgba(0, 0, 0, 0.3);" + + +HOST_INFO_ONE = "color: #00ffff; font-size: 13px; font-weight: bold;" + +LOCATION_INFO_ONE = "color: #888888; font-size: 14px; font-style: italic;" \ No newline at end of file