|
| 1 | +# Copyright (c) 2021-2026 The University of Texas Southwestern Medical Center. |
| 2 | +# All rights reserved. |
| 3 | + |
| 4 | +"""Controller for the GUI settings popup.""" |
| 5 | + |
| 6 | +from collections.abc import Mapping, Sequence |
| 7 | +from math import isfinite |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +from navigate.view.popups.gui_settings_popup import GuiSettingsPopup |
| 11 | + |
| 12 | + |
| 13 | +def iter_gui_settings( |
| 14 | + settings: Any, path: tuple[str, ...] = () |
| 15 | +) -> list[tuple[tuple[str, ...], Any]]: |
| 16 | + """Return non-theme GUI configuration leaves and their paths.""" |
| 17 | + if isinstance(settings, Mapping) or hasattr(settings, "items"): |
| 18 | + rows: list[tuple[tuple[str, ...], Any]] = [] |
| 19 | + for key, value in settings.items(): |
| 20 | + key = str(key) |
| 21 | + if not path and key == "theme": |
| 22 | + continue |
| 23 | + rows.extend(iter_gui_settings(value, (*path, key))) |
| 24 | + return rows |
| 25 | + if isinstance(settings, Sequence) and not isinstance(settings, (str, bytes)): |
| 26 | + return [(path, list(settings))] |
| 27 | + return [(path, settings)] |
| 28 | + |
| 29 | + |
| 30 | +def flatten_gui_settings(settings: Any) -> list[tuple[str, str]]: |
| 31 | + """Return non-theme GUI settings as dotted path/value pairs.""" |
| 32 | + return [(".".join(path), str(value)) for path, value in iter_gui_settings(settings)] |
| 33 | + |
| 34 | + |
| 35 | +def is_integer_gui_setting(path: tuple[str, ...]) -> bool: |
| 36 | + """Return whether a GUI setting must use an integer entry.""" |
| 37 | + return path == ("channel_settings", "count") or path[:2] == ( |
| 38 | + "time", |
| 39 | + "timepoints", |
| 40 | + ) |
| 41 | + |
| 42 | + |
| 43 | +def is_boolean_gui_setting(path: tuple[str, ...]) -> bool: |
| 44 | + """Return whether a GUI setting is represented by a checkbutton.""" |
| 45 | + return path in {("histogram", "enabled"), ("mip_display", "enabled")} |
| 46 | + |
| 47 | + |
| 48 | +def is_waveform_gui_setting(path: tuple[str, ...]) -> bool: |
| 49 | + """Return whether a setting affects waveform popup control increments.""" |
| 50 | + return path[0] in {"remote_focus_waveform", "galvo_waveform"} |
| 51 | + |
| 52 | + |
| 53 | +def is_step_size_gui_setting(path: tuple[str, ...]) -> bool: |
| 54 | + """Return whether a GUI setting defines a numeric step size.""" |
| 55 | + return path[-1] == "step" or path[-1].endswith("_step_size") |
| 56 | + |
| 57 | + |
| 58 | +def is_positive_gui_setting(path: tuple[str, ...]) -> bool: |
| 59 | + """Return whether a GUI setting must be strictly greater than zero.""" |
| 60 | + return is_step_size_gui_setting(path) or path[:2] == ( |
| 61 | + "stack_acquisition", |
| 62 | + "step_size", |
| 63 | + ) |
| 64 | + |
| 65 | + |
| 66 | +def is_nonnegative_gui_setting(path: tuple[str, ...]) -> bool: |
| 67 | + """Return whether a GUI setting is constrained to non-negative values.""" |
| 68 | + return ( |
| 69 | + path[:2] |
| 70 | + in { |
| 71 | + ("channel_settings", "laser_power"), |
| 72 | + ("channel_settings", "exposure_time"), |
| 73 | + ("channel_settings", "interval"), |
| 74 | + } |
| 75 | + ) |
| 76 | + |
| 77 | + |
| 78 | +def gui_setting_minimum(path: tuple[str, ...]) -> str: |
| 79 | + """Return the entry minimum for GUI settings with lower-bound constraints.""" |
| 80 | + if path == ("channel_settings", "count"): |
| 81 | + return "1" |
| 82 | + if is_positive_gui_setting(path): |
| 83 | + return "0.000000001" |
| 84 | + if is_nonnegative_gui_setting(path) or path[0] == "time": |
| 85 | + return "0" |
| 86 | + return "-Infinity" |
| 87 | + |
| 88 | + |
| 89 | +def gui_setting_group(path: tuple[str, ...]) -> str: |
| 90 | + """Return the human-readable group title for a GUI setting path.""" |
| 91 | + group_names = { |
| 92 | + "remote_focus_waveform": "Remote Focus Waveform", |
| 93 | + "galvo_waveform": "Galvo Waveform", |
| 94 | + } |
| 95 | + return group_names.get(path[0], path[0].replace("_", " ").title()) |
| 96 | + |
| 97 | + |
| 98 | +def coerce_gui_value(value: str, path: tuple[str, ...]) -> Any: |
| 99 | + """Convert text entered in the popup to the value type for a GUI setting.""" |
| 100 | + parsed_value = int(value) if is_integer_gui_setting(path) else float(value) |
| 101 | + if not is_integer_gui_setting(path) and not isfinite(parsed_value): |
| 102 | + raise ValueError("Value must be finite") |
| 103 | + if path == ("channel_settings", "count") and parsed_value <= 0: |
| 104 | + raise ValueError("Value must be greater than 0") |
| 105 | + if is_positive_gui_setting(path) and parsed_value <= 0: |
| 106 | + raise ValueError("Value must be greater than 0") |
| 107 | + if (path[0] == "time" or is_nonnegative_gui_setting(path)) and parsed_value < 0: |
| 108 | + raise ValueError("Value must be greater than or equal to 0") |
| 109 | + return parsed_value |
| 110 | + |
| 111 | + |
| 112 | +class GuiSettingsPopupController: |
| 113 | + """Connect the GUI settings view to the shared GUI configuration.""" |
| 114 | + |
| 115 | + def __init__(self, view: GuiSettingsPopup, parent_controller: "Controller") -> None: |
| 116 | + self.view = view |
| 117 | + self.parent_controller = parent_controller |
| 118 | + self.view.buttons["apply"].configure(command=self.apply_settings) |
| 119 | + self.view.buttons["close"].configure(command=self.close_popup) |
| 120 | + self.view.popup.protocol("WM_DELETE_WINDOW", self.close_popup) |
| 121 | + self.populate_settings() |
| 122 | + |
| 123 | + def populate_settings(self) -> None: |
| 124 | + """Populate the view from the active GUI configuration.""" |
| 125 | + fields = [] |
| 126 | + for path, value in iter_gui_settings(self.parent_controller.configuration["gui"]): |
| 127 | + fields.append( |
| 128 | + { |
| 129 | + "path": path, |
| 130 | + "value": value, |
| 131 | + "group": gui_setting_group(path), |
| 132 | + "label": ".".join(path[1:]).replace("_", " "), |
| 133 | + "minimum": gui_setting_minimum(path), |
| 134 | + "type": ( |
| 135 | + "boolean" |
| 136 | + if is_boolean_gui_setting(path) |
| 137 | + else "integer" |
| 138 | + if is_integer_gui_setting(path) |
| 139 | + else "float" |
| 140 | + ), |
| 141 | + } |
| 142 | + ) |
| 143 | + self.view.populate_settings(fields) |
| 144 | + |
| 145 | + def apply_settings(self) -> bool: |
| 146 | + """Validate and write user edits to the shared GUI configuration.""" |
| 147 | + updates: list[tuple[tuple[str, ...], Any]] = [] |
| 148 | + validation_errors: list[tuple[tuple[str, ...], Any, ValueError]] = [] |
| 149 | + for path, (value_var, entry) in self.view.entries.items(): |
| 150 | + try: |
| 151 | + updates.append((path, coerce_gui_value(value_var.get(), path))) |
| 152 | + entry._toggle_error(False) |
| 153 | + except ValueError as error: |
| 154 | + entry._toggle_error(True) |
| 155 | + validation_errors.append((path, entry, error)) |
| 156 | + if validation_errors: |
| 157 | + path, entry, error = validation_errors[0] |
| 158 | + self.view.set_status(f"{'.'.join(path)}: {error}") |
| 159 | + entry.focus_set() |
| 160 | + return False |
| 161 | + updates.extend( |
| 162 | + (path, value_var.get()) |
| 163 | + for path, value_var in self.view.boolean_variables.items() |
| 164 | + ) |
| 165 | + |
| 166 | + waveform_settings_changed = False |
| 167 | + other_settings_changed = False |
| 168 | + display_setting_updates: list[tuple[tuple[str, ...], bool]] = [] |
| 169 | + for path, value in updates: |
| 170 | + parent = self.parent_controller.configuration["gui"] |
| 171 | + for key in path[:-1]: |
| 172 | + parent = parent[key] |
| 173 | + if parent[path[-1]] != value: |
| 174 | + if is_waveform_gui_setting(path): |
| 175 | + waveform_settings_changed = True |
| 176 | + elif is_boolean_gui_setting(path): |
| 177 | + display_setting_updates.append((path, value)) |
| 178 | + else: |
| 179 | + other_settings_changed = True |
| 180 | + parent[path[-1]] = value |
| 181 | + |
| 182 | + self._apply_display_setting_updates(display_setting_updates) |
| 183 | + messages = [] |
| 184 | + if waveform_settings_changed: |
| 185 | + waveform_popup = getattr( |
| 186 | + self.parent_controller, "waveform_popup_controller", None |
| 187 | + ) |
| 188 | + messages.append("Waveform step-size settings were applied successfully.") |
| 189 | + if waveform_popup is not None: |
| 190 | + messages.append( |
| 191 | + "The Waveform Parameters window was reopened to take effect" |
| 192 | + ) |
| 193 | + self._refresh_waveform_popup(waveform_popup) |
| 194 | + if other_settings_changed: |
| 195 | + messages.append( |
| 196 | + "Setting changes were saved. Restart Navigate for the changes " |
| 197 | + "to take effect." |
| 198 | + ) |
| 199 | + if messages: |
| 200 | + self.view.show_info("Settings Saved", "\n\n".join(messages)) |
| 201 | + return True |
| 202 | + |
| 203 | + def _apply_display_setting_updates( |
| 204 | + self, updates: list[tuple[tuple[str, ...], bool]] |
| 205 | + ) -> None: |
| 206 | + """Apply display toggles through the existing menu-controller workflow.""" |
| 207 | + menu_controller = self.parent_controller.menu_controller |
| 208 | + for path, value in updates: |
| 209 | + if path == ("histogram", "enabled"): |
| 210 | + menu_controller.histogram_enabled.set(value) |
| 211 | + menu_controller.toggle_histogram() |
| 212 | + elif path == ("mip_display", "enabled"): |
| 213 | + menu_controller.mip_enabled.set(value) |
| 214 | + menu_controller.toggle_mip() |
| 215 | + |
| 216 | + def _refresh_waveform_popup(self, waveform_popup=None) -> None: |
| 217 | + """Reopen an existing waveform popup so it uses the updated increments.""" |
| 218 | + if waveform_popup is None: |
| 219 | + waveform_popup = getattr( |
| 220 | + self.parent_controller, "waveform_popup_controller", None |
| 221 | + ) |
| 222 | + if waveform_popup is None: |
| 223 | + return |
| 224 | + waveform_popup.close_window() |
| 225 | + self.parent_controller.menu_controller.popup_waveform_setting() |
| 226 | + |
| 227 | + def showup(self) -> None: |
| 228 | + """Show the existing settings window.""" |
| 229 | + self.view.showup() |
| 230 | + |
| 231 | + def close_popup(self) -> None: |
| 232 | + """Close the popup and discard its controller reference.""" |
| 233 | + self.view.popup.destroy() |
| 234 | + if hasattr(self.parent_controller, "gui_settings_popup_controller"): |
| 235 | + del self.parent_controller.gui_settings_popup_controller |
0 commit comments