""" EU-Utility - Widget Registry Allows plugins to register widgets that appear in the Widgets tab. """ from typing import Dict, List, Callable, Optional from dataclasses import dataclass from PyQt6.QtWidgets import QWidget @dataclass class WidgetInfo: """Information about a registered widget.""" id: str name: str description: str icon: str # emoji or icon name creator: Callable[[], QWidget] # Function that creates the widget plugin_id: str # Which plugin registered this class WidgetRegistry: """Registry for plugin-provided widgets.""" _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance._widgets: Dict[str, WidgetInfo] = {} return cls._instance def register_widget( self, widget_id: str, name: str, description: str, icon: str, creator: Callable[[], QWidget], plugin_id: str = "unknown" ): """Register a widget. Args: widget_id: Unique identifier for this widget type name: Display name description: Short description shown in UI icon: Emoji or icon name creator: Function that returns a QWidget instance plugin_id: ID of the plugin registering this widget """ self._widgets[widget_id] = WidgetInfo( id=widget_id, name=name, description=description, icon=icon, creator=creator, plugin_id=plugin_id ) print(f"[WidgetRegistry] Registered widget: {name} (from {plugin_id})") def unregister_widget(self, widget_id: str): """Unregister a widget.""" if widget_id in self._widgets: del self._widgets[widget_id] print(f"[WidgetRegistry] Unregistered widget: {widget_id}") def get_widget(self, widget_id: str) -> Optional[WidgetInfo]: """Get widget info by ID.""" return self._widgets.get(widget_id) def get_all_widgets(self) -> List[WidgetInfo]: """Get all registered widgets.""" return list(self._widgets.values()) def get_widgets_by_plugin(self, plugin_id: str) -> List[WidgetInfo]: """Get all widgets registered by a specific plugin.""" return [w for w in self._widgets.values() if w.plugin_id == plugin_id] def create_widget(self, widget_id: str) -> Optional[QWidget]: """Create an instance of a registered widget.""" info = self._widgets.get(widget_id) if info: try: return info.creator() except Exception as e: print(f"[WidgetRegistry] Error creating widget {widget_id}: {e}") return None def clear(self): """Clear all registered widgets.""" self._widgets.clear() # Global registry instance def get_widget_registry() -> WidgetRegistry: """Get the global widget registry.""" return WidgetRegistry()