EU-Utility/core/overlay_controller.py

251 lines
8.7 KiB
Python

"""
EU-Utility - Activity Bar Overlay Modes
========================================
GW2/Blish-style overlay system with multiple visibility modes:
Modes:
- DESKTOP_APP: Activity bar shows in desktop app only
- OVERLAY_ALWAYS: Activity bar always visible as overlay
- OVERLAY_GAME_FOCUSED: Only visible when EU window is focused
- OVERLAY_HOTKEY_TOGGLE: Toggle with hotkey (Ctrl+Shift+B)
- OVERLAY_TEMPORARY: Show for 7-10 seconds on hotkey, then hide
"""
from enum import Enum
from dataclasses import dataclass
from typing import Optional
from PyQt6.QtCore import QTimer, pyqtSignal
class OverlayMode(Enum):
"""Activity bar visibility modes."""
DESKTOP_APP = "desktop_app" # Only in desktop app
OVERLAY_ALWAYS = "overlay_always" # Always visible overlay
OVERLAY_GAME_FOCUSED = "overlay_game" # Only when EU game focused
OVERLAY_HOTKEY_TOGGLE = "overlay_toggle" # Toggle with hotkey
OVERLAY_TEMPORARY = "overlay_temp" # Show 7-10s on hotkey
@dataclass
class OverlayConfig:
"""Configuration for activity bar overlay behavior."""
# Default to game-focused mode (Blish HUD style)
mode: OverlayMode = OverlayMode.OVERLAY_GAME_FOCUSED
temporary_duration: int = 8000 # milliseconds (8 seconds default)
game_focus_poll_interval: int = 1000 # ms (1 second - faster response)
def to_dict(self):
return {
'mode': self.mode.value,
'temporary_duration': self.temporary_duration,
'game_focus_poll_interval': self.game_focus_poll_interval
}
@classmethod
def from_dict(cls, data):
mode_str = data.get('mode', 'overlay_toggle')
try:
mode = OverlayMode(mode_str)
except ValueError:
mode = OverlayMode.OVERLAY_HOTKEY_TOGGLE
return cls(
mode=mode,
temporary_duration=data.get('temporary_duration', 8000),
game_focus_poll_interval=data.get('game_focus_poll_interval', 2000)
)
class OverlayController:
"""
Controls activity bar visibility based on selected mode.
Usage:
controller = OverlayController(activity_bar, window_manager)
controller.set_mode(OverlayMode.OVERLAY_TEMPORARY)
controller.start()
"""
visibility_changed = pyqtSignal(bool) # is_visible
def __init__(self, activity_bar, window_manager=None):
self.activity_bar = activity_bar
self.window_manager = window_manager
self.config = OverlayConfig()
# State
self._mode = OverlayMode.OVERLAY_HOTKEY_TOGGLE
self._is_visible = False
self._game_focused = False
# Timers
self._game_focus_timer = QTimer()
self._game_focus_timer.timeout.connect(self._check_game_focus)
self._temporary_timer = QTimer()
self._temporary_timer.setSingleShot(True)
self._temporary_timer.timeout.connect(self._hide_temporary)
def set_mode(self, mode: OverlayMode):
"""Change overlay mode."""
self._mode = mode
self._apply_mode()
def start(self):
"""Start the overlay controller based on current mode."""
self._apply_mode()
def stop(self):
"""Stop all timers and hide overlay."""
self._game_focus_timer.stop()
self._temporary_timer.stop()
if self.activity_bar:
self.activity_bar.hide()
def _apply_mode(self):
"""Apply current mode settings."""
self._game_focus_timer.stop()
self._temporary_timer.stop()
if self._mode == OverlayMode.DESKTOP_APP:
# Only show in desktop app - hide overlay
self._hide()
elif self._mode == OverlayMode.OVERLAY_ALWAYS:
# Always show
self._show()
elif self._mode == OverlayMode.OVERLAY_GAME_FOCUSED:
# Show only when game focused
self._game_focus_timer.start(self.config.game_focus_poll_interval)
self._check_game_focus() # Check immediately
elif self._mode == OverlayMode.OVERLAY_HOTKEY_TOGGLE:
# Hotkey toggle - start hidden
self._hide()
elif self._mode == OverlayMode.OVERLAY_TEMPORARY:
# Temporary mode - start hidden
self._hide()
def toggle(self):
"""Toggle overlay visibility (for hotkey)."""
if self._mode == OverlayMode.OVERLAY_TEMPORARY:
self.show_temporary()
else:
if self._is_visible:
self._hide()
else:
self._show()
def show_temporary(self):
"""Show overlay temporarily (for temporary mode)."""
self._show()
self._temporary_timer.start(self.config.temporary_duration)
def _hide_temporary(self):
"""Hide after temporary duration."""
self._hide()
def _show(self):
"""Show the activity bar."""
if self.activity_bar and not self._is_visible:
self.activity_bar.show()
self._is_visible = True
self.visibility_changed.emit(True)
def _hide(self):
"""Hide the activity bar."""
if self.activity_bar and self._is_visible:
self.activity_bar.hide()
self._is_visible = False
self.visibility_changed.emit(False)
def _check_game_focus(self):
"""Check if EU game window is focused - non-blocking using QTimer.singleShot."""
# Run the actual check in next event loop iteration to not block
from PyQt6.QtCore import QTimer
QTimer.singleShot(0, self._do_check_game_focus)
def _do_check_game_focus(self):
"""Actual focus check (non-blocking)."""
if not self.window_manager:
return
# Track time for debugging
import time
start = time.perf_counter()
try:
# Set a flag to prevent re-entrancy
if getattr(self, '_checking_focus', False):
return
self._checking_focus = True
# Quick check - limit window enumeration time
eu_window = self._quick_find_eu_window()
if eu_window:
is_focused = eu_window.is_focused
if is_focused != self._game_focused:
self._game_focused = is_focused
if is_focused:
print("[OverlayController] EU focused - showing overlay")
self._show()
else:
print("[OverlayController] EU unfocused - hiding overlay")
self._hide()
else:
# No EU window found - hide if visible
if self._is_visible:
print("[OverlayController] EU window not found - hiding overlay")
self._hide()
self._game_focused = False
# Log if slow
elapsed = (time.perf_counter() - start) * 1000
if elapsed > 100:
print(f"[OverlayController] Warning: Focus check took {elapsed:.1f}ms")
except Exception as e:
print(f"[OverlayController] Error checking focus: {e}")
finally:
self._checking_focus = False
def _quick_find_eu_window(self):
"""Quick window find with timeout protection."""
import time
start = time.perf_counter()
try:
# Try window manager first
if hasattr(self.window_manager, 'find_eu_window'):
# Wrap in timeout check
result = self.window_manager.find_eu_window()
# If taking too long, skip future checks
elapsed = (time.perf_counter() - start) * 1000
if elapsed > 500: # More than 500ms is too slow
print(f"[OverlayController] Window find too slow ({elapsed:.1f}ms), disabling focus detection")
self._game_focus_timer.stop()
return None
return result
except Exception as e:
print(f"[OverlayController] Window find error: {e}")
return None
# Singleton instance
_overlay_controller = None
def get_overlay_controller(activity_bar=None, window_manager=None):
"""Get or create the overlay controller singleton."""
global _overlay_controller
if _overlay_controller is None:
if activity_bar is None:
raise ValueError("activity_bar required for first initialization")
_overlay_controller = OverlayController(activity_bar, window_manager)
return _overlay_controller