From f92c42d2243924822592952c1c700921eac5cde9 Mon Sep 17 00:00:00 2001 From: S4NKALP Date: Sat, 25 Apr 2026 08:30:03 +0545 Subject: [PATCH] remove bloatware plugins --- config/launcher.json | 42 +- src/window/launcher/plugin_manager.py | 7 - src/window/launcher/plugins/bookmarks.py | 784 --------------------- src/window/launcher/plugins/otp.py | 851 ----------------------- src/window/launcher/plugins/password.py | 689 ------------------ src/window/launcher/plugins/reminders.py | 448 ------------ src/window/launcher/plugins/system.py | 240 ------- src/window/launcher/plugins/tmux.py | 334 --------- 8 files changed, 1 insertion(+), 3394 deletions(-) delete mode 100644 src/window/launcher/plugins/bookmarks.py delete mode 100644 src/window/launcher/plugins/otp.py delete mode 100644 src/window/launcher/plugins/password.py delete mode 100644 src/window/launcher/plugins/reminders.py delete mode 100644 src/window/launcher/plugins/system.py delete mode 100644 src/window/launcher/plugins/tmux.py diff --git a/config/launcher.json b/config/launcher.json index 481d56b..332e2d2 100644 --- a/config/launcher.json +++ b/config/launcher.json @@ -24,10 +24,6 @@ "icon": "apps", "description": "Applications - Launch installed applications" }, - "bin": { - "icon": "terminal", - "description": "Bins - Search and run executable binaries" - }, "power": { "icon": "shutdown", "description": "Power - System power management and session control" @@ -58,42 +54,6 @@ "? google cats", "? youtube music" ] - }, - "remind": { - "icon": "alarm-timer", - "description": "Reminders - Set time-based reminders with notifications" - }, - "otp": { - "icon": "auth-otp-symbolic", - "description": "Manage TOTP codes and 2FA authentication" - }, - "pass": { - "icon": "nextcloud-password-client", - "description": "Password Manager - Search and manage passwords" - }, - "bm": { - "icon": "bookmark-add-symbolic", - "description": "Bookmarks - Search and manage bookmarks" - }, - "script": { - "icon": "terminal", - "description": "Bash Scripts - Manage and execute bash scripts" - }, - "bash": { - "icon": "terminal", - "description": "Bash Scripts - Manage and execute bash scripts" - }, - "sh": { - "icon": "terminal", - "description": "Bash Scripts - Manage and execute bash scripts" - }, - "tmux": { - "icon": "terminal", - "description": "Tmux Manager - Create, attach, rename, and kill tmux sessions" - }, - "cp": { - "icon": "color-select-symbolic", - "description": "Color Picker - Pick colors from the screen (HEX, RGB, HSV)" } }, "settings": { @@ -102,4 +62,4 @@ "fallback_example_template": "{trigger} ", "config_version": "1.0" } -} \ No newline at end of file +} diff --git a/src/window/launcher/plugin_manager.py b/src/window/launcher/plugin_manager.py index e84add7..5692375 100644 --- a/src/window/launcher/plugin_manager.py +++ b/src/window/launcher/plugin_manager.py @@ -79,7 +79,6 @@ class PluginManager: default_plugins = [ "applications", "calculator", - "system", "clipboard", "power", "caffeine", @@ -87,12 +86,6 @@ class PluginManager: "emoji", "wallpaper", "websearch", - "reminders", - "otp", - "password", - "bookmarks", - "tmux", - "colorpicker", ] for plugin_name in default_plugins: diff --git a/src/window/launcher/plugins/bookmarks.py b/src/window/launcher/plugins/bookmarks.py deleted file mode 100644 index 417b924..0000000 --- a/src/window/launcher/plugins/bookmarks.py +++ /dev/null @@ -1,784 +0,0 @@ -import json -import subprocess -import threading -import time -from pathlib import Path -from typing import Dict, List, Optional -from urllib.parse import urlparse - -from fabric.utils import GLib, get_relative_path -from thefuzz import fuzz - -from window.launcher.plugin_base import PluginBase -from window.launcher.result import Result - - -class BookmarkManager: - """Manages user's custom bookmarks.""" - - def __init__(self, storage_file: Path): - self.storage_file = storage_file - self.bookmarks: List[Dict] = [] - self.cache_lock = threading.Lock() - self.last_loaded = 0 - self.cache_ttl = 30 # Cache for 30 seconds - self._load_bookmarks() - - def _get_favicon_url(self, url: str) -> str: - """Generate favicon URL for a given website URL.""" - try: - parsed = urlparse(url) - return f"{parsed.scheme}://{parsed.netloc}/favicon.ico" - except Exception: - return "" - - def _extract_domain(self, url: str) -> str: - """Extract domain from URL.""" - try: - parsed = urlparse(url) - domain = parsed.netloc - # Remove www. prefix - if domain.startswith("www."): - domain = domain[4:] - return domain - except Exception: - return url - - def _normalize_url(self, url: str) -> str: - """Normalize URL by adding protocol if missing.""" - url = url.strip() - if not url.startswith(("http://", "https://")): - if url.startswith("www."): - url = "https://" + url - else: - url = "https://" + url - return url - - def _load_bookmarks(self): - """Load bookmarks from JSON file with caching.""" - with self.cache_lock: - current_time = time.time() - - # Check if cache is still valid - if ( - current_time - self.last_loaded - ) < self.cache_ttl and self.last_loaded > 0: - return - - try: - if self.storage_file.exists(): - with open(self.storage_file, "r", encoding="utf-8") as f: - data = json.load(f) - self.bookmarks = data.get("bookmarks", []) - else: - # File doesn't exist, start with empty list but don't save yet - self.bookmarks = [] - - self.last_loaded = current_time - except Exception as e: - print(f"Error loading bookmarks: {e}") - self.bookmarks = [] - - def get_bookmarks(self) -> List[Dict]: - """Get bookmarks, loading from file if needed.""" - self._load_bookmarks() - return self.bookmarks - - def _save_bookmarks_unlocked(self): - """Save bookmarks to JSON file without acquiring lock.""" - try: - self.storage_file.parent.mkdir(parents=True, exist_ok=True) - data = { - "bookmarks": self.bookmarks, - "last_updated": time.time(), - } - with open(self.storage_file, "w", encoding="utf-8") as f: - json.dump(data, f, indent=2, ensure_ascii=False) - - # Update cache timestamp - self.last_loaded = time.time() - except Exception as e: - print(f"Error saving bookmarks: {e}") - - def _save_bookmarks(self): - """Save bookmarks to JSON file.""" - with self.cache_lock: - self._save_bookmarks_unlocked() - - def add_bookmark( - self, title: str, url: str, description: str = "", tags: List[str] = None - ) -> bool: - """Add a new bookmark.""" - try: - url = self._normalize_url(url) - - # Check if bookmark already exists - for bookmark in self.bookmarks: - if bookmark["url"] == url: - return False # Already exists - - new_bookmark = { - "title": title.strip(), - "url": url, - "description": description.strip(), - "tags": tags or [], - "created": time.time(), - "accessed": 0, - } - - self.bookmarks.append(new_bookmark) - self._save_bookmarks() - - # Clear cache to force reload - self.last_loaded = 0 - - return True - - except Exception as e: - print(f"Error adding bookmark: {e}") - return False - - def remove_bookmark(self, identifier: str) -> bool: - """Remove a bookmark by title or URL.""" - try: - identifier = identifier.lower().strip() - - for i, bookmark in enumerate(self.bookmarks): - if ( - bookmark["title"].lower() == identifier - or bookmark["url"].lower() == identifier - or self._extract_domain(bookmark["url"]).lower() == identifier - ): - self.bookmarks.pop(i) - self._save_bookmarks() - - # Clear cache to force reload - self.last_loaded = 0 - - return True - - return False - - except Exception as e: - print(f"Error removing bookmark: {e}") - return False - - def update_access_time(self, url: str): - """Update the last accessed time for a bookmark.""" - try: - for bookmark in self.bookmarks: - if bookmark["url"] == url: - bookmark["accessed"] = time.time() - self._save_bookmarks() - break - except Exception as e: - print(f"Error updating access time: {e}") - - def get_bookmark_count(self) -> int: - """Get total number of bookmarks.""" - return len(self.get_bookmarks()) - - -class BookmarksPlugin(PluginBase): - """ - User bookmarks plugin for the launcher. - Allows users to add, remove, and search their own bookmarks. - """ - - def __init__(self): - super().__init__() - self.display_name = "Bookmarks" - self.description = "Manage and search your personal bookmarks" - - # Initialize bookmark manager with storage file - self.bookmark_file = Path( - get_relative_path("../../../../config/bookmarks.json") - ) - self.bookmark_manager = BookmarkManager(self.bookmark_file) - self.max_results = 15 - - # Cache for results - self._results_cache = {} - self._cache_timestamps = {} - self._cache_ttl = 30 # 30 seconds - - # Launcher instance for refreshing - self._launcher_instance = None - self._original_close_launcher = None - - def initialize(self): - """Initialize the bookmarks plugin.""" - self.set_triggers(["bm"]) - self._setup_launcher_hooks() - - def cleanup(self): - """Cleanup the bookmarks plugin.""" - self._results_cache.clear() - self._cache_timestamps.clear() - self._cleanup_launcher_hooks() - - def query(self, query_string: str) -> List[Result]: - """Process bookmark queries with caching.""" - query_key = query_string.strip() - current_time = time.time() - - # Check cache first (except for add/remove commands which should always execute) - if ( - not query_key.startswith(("add ", "remove ", "delete ", "rm ")) - and query_key in self._results_cache - and (current_time - self._cache_timestamps.get(query_key, 0)) - < self._cache_ttl - ): - return self._results_cache[query_key] - - query = query_key.lower() - results = [] - - if not query: - # Show recent/popular bookmarks when no query - results = self._get_recent_bookmarks() - elif query.startswith("add "): - # Add new bookmark (don't cache) - results = self._handle_add_command(query[4:].strip()) - elif query.startswith(("remove ", "delete ", "rm ")): - # Remove bookmark (don't cache) - command_parts = query_key.split(" ", 1) - if len(command_parts) > 1: - results = self._handle_remove_command(command_parts[1].strip()) - else: - results = self._show_remove_help() - else: - # Search bookmarks - results = self._search_bookmarks(query) - - # Cache results (except for add/remove commands) - if not query.startswith(("add ", "remove ", "delete ", "rm ")): - self._results_cache[query_key] = results - self._cache_timestamps[query_key] = current_time - - return results - - def _search_bookmarks(self, query: str) -> List[Result]: - """Search through bookmarks.""" - bookmarks = self.bookmark_manager.get_bookmarks() - - if not bookmarks: - return [ - Result( - title="No Bookmarks Found", - subtitle="Use 'add <url>' to add first bookmark", - icon_name="info", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "info", "keep_launcher_open": True}, - ) - ] - - # Search bookmarks - results = [] - for bookmark in bookmarks: - relevance = self._calculate_relevance(bookmark, query) - if relevance > 0.3: # Only show relevant results - result = self._create_bookmark_result(bookmark, relevance) - if result: - results.append(result) - - # Sort by relevance and limit results - results.sort(key=lambda r: r.relevance, reverse=True) - return results[: self.max_results] - - def _get_recent_bookmarks(self) -> List[Result]: - """Get recent/popular bookmarks when no query is provided.""" - bookmarks = self.bookmark_manager.get_bookmarks() - - if not bookmarks: - return [ - Result( - title="No Bookmarks Yet", - subtitle="Use 'add <title> <url>' to add first bookmark", - icon_name="info", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ), - Result( - title="Example: Add Google", - subtitle="add Google https://google.com", - icon_name="info", - action=lambda: None, - relevance=0.9, - plugin_name=self.display_name, - data={"type": "example", "keep_launcher_open": True}, - ), - ] - - # Sort by access time (most recent first) and show top 10 - sorted_bookmarks = sorted( - bookmarks, key=lambda b: b.get("accessed", 0), reverse=True - ) - results = [] - for bookmark in sorted_bookmarks[:10]: - result = self._create_bookmark_result(bookmark, 0.8) - if result: - results.append(result) - - return results - - def _handle_add_command(self, args: str) -> List[Result]: - """Handle add bookmark command.""" - if not args: - return [ - Result( - title="Add Bookmark", - subtitle="Usage: add <title> <url> [description]", - icon_name="info", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ), - Result( - title="Example", - subtitle="add Google https://google.com Search engine", - icon_name="info", - action=lambda: None, - relevance=0.9, - plugin_name=self.display_name, - data={"type": "example", "keep_launcher_open": True}, - ), - ] - - # Parse arguments: title url [description] - parts = args.split() - if len(parts) < 2: - return [ - Result( - title="Invalid Format", - subtitle="Usage: add <title> <url> [description]", - icon_name="alert", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "error", "keep_launcher_open": True}, - ) - ] - - title = parts[0] - url = parts[1] - description = " ".join(parts[2:]) if len(parts) > 2 else "" - - # Check if bookmark already exists - normalized_url = self.bookmark_manager._normalize_url(url) - existing_bookmarks = self.bookmark_manager.get_bookmarks() - already_exists = any( - bookmark["url"] == normalized_url for bookmark in existing_bookmarks - ) - - if already_exists: - # Truncate URL for display to prevent launcher resize - display_url = normalized_url - if len(display_url) > 35: - display_url = display_url[:32] + "..." - - return [ - Result( - title="Bookmark Already Exists", - subtitle=f"URL '{display_url}' already exists", - icon_name="alert", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "error", "keep_launcher_open": True}, - ) - ] - - # Show add action - will execute on Enter - domain = self.bookmark_manager._extract_domain(normalized_url) - - # Truncate domain if too long - if len(domain) > 25: - domain = domain[:22] + "..." - - subtitle = f"Click to add: {domain}" - if description: - # Truncate description to prevent launcher resize - max_desc_len = 35 - len(domain) # Account for domain + separator - if len(description) > max_desc_len: - description = description[: max_desc_len - 3] + "..." - subtitle += f" • {description}" - - # Truncate title for display - display_title = title - if len(display_title) > 25: - display_title = display_title[:22] + "..." - - return [ - Result( - title=f"Add bookmark '{display_title}'", - subtitle=subtitle, - icon_name="plus", - action=lambda: self._add_bookmark_action(title, url, description), - relevance=1.0, - plugin_name=self.display_name, - data={"type": "add", "name": title, "keep_launcher_open": True}, - ) - ] - - def _handle_remove_command(self, identifier: str) -> List[Result]: - """Handle remove bookmark command.""" - if not identifier: - return self._show_remove_help() - - # Find matching bookmarks - bookmarks = self.bookmark_manager.get_bookmarks() - identifier_lower = identifier.lower().strip() - - matching_bookmarks = [] - for bookmark in bookmarks: - if ( - bookmark["title"].lower() == identifier_lower - or bookmark["url"].lower() == identifier_lower - or self.bookmark_manager._extract_domain(bookmark["url"]).lower() - == identifier_lower - ): - matching_bookmarks.append(bookmark) - - if not matching_bookmarks: - return [ - Result( - title="Bookmark Not Found", - subtitle=f"No bookmark found matching '{identifier}'", - icon_name="alert", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "error", "keep_launcher_open": True}, - ) - ] - - # Show remove action - will execute on Enter - bookmark = matching_bookmarks[0] # Take first match - title = bookmark.get("title", "Untitled") - domain = self.bookmark_manager._extract_domain(bookmark.get("url", "")) - - # Truncate title and domain for display - display_title = title - if len(display_title) > 25: - display_title = display_title[:22] + "..." - - display_domain = domain - if len(display_domain) > 30: - display_domain = display_domain[:27] + "..." - - return [ - Result( - title=f"Remove '{display_title}'?", - subtitle=f"Click to confirm: {display_domain}", - icon_name="trash", - action=lambda: self._remove_bookmark_action(identifier), - relevance=1.0, - plugin_name=self.display_name, - data={"type": "remove", "name": title, "keep_launcher_open": True}, - ) - ] - - def _show_remove_help(self) -> List[Result]: - """Show help for remove command.""" - bookmarks = self.bookmark_manager.get_bookmarks() - results = [ - Result( - title="Remove Bookmark", - subtitle="Usage: remove <title|url|domain>", - icon_name="info", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ) - ] - - # Show available bookmarks to remove - if bookmarks: - results.append( - Result( - title="Available Bookmarks:", - subtitle=f"{len(bookmarks)} bookmarks available to remove", - icon_name="bookmarks-organize", - action=lambda: None, - relevance=0.9, - plugin_name=self.display_name, - data={"type": "info", "keep_launcher_open": True}, - ) - ) - - # Show first few bookmarks as examples - for bookmark in bookmarks[:3]: - title = bookmark.get("title", "Untitled") - domain = self._extract_domain(bookmark.get("url", "")) - - # Truncate title and domain for consistent display - display_title = title - if len(display_title) > 20: - display_title = display_title[:17] + "..." - - display_domain = domain - if len(display_domain) > 20: - display_domain = display_domain[:17] + "..." - - results.append( - Result( - title=f"remove {display_title}", - subtitle=f"Click to remove: {display_title} ({display_domain})", - icon_name="trash", - action=lambda t=title: self._remove_bookmark_action(t), - relevance=0.8, - plugin_name=self.display_name, - data={ - "type": "remove_option", - "bookmark": bookmark, - "keep_launcher_open": True, - }, - ) - ) - - return results - - def _add_bookmark_action(self, title: str, url: str, description: str = ""): - """Execute the add bookmark action.""" - success = self.bookmark_manager.add_bookmark(title, url, description) - if success: - print(f"✓ Added bookmark '{title}' - {url}") - # Clear cache to force refresh - self._results_cache.clear() - self._cache_timestamps.clear() - # Reset to trigger word and refresh - self._reset_to_trigger() - else: - print(f"✗ Failed to add bookmark '{title}' - already exists") - - def _remove_bookmark_action(self, identifier: str): - """Execute the remove bookmark action.""" - success = self.bookmark_manager.remove_bookmark(identifier) - if success: - print(f"✓ Removed bookmark '{identifier}'") - # Clear cache to force refresh - self._results_cache.clear() - self._cache_timestamps.clear() - # Reset to trigger word and refresh - self._reset_to_trigger() - else: - print(f"✗ Failed to remove bookmark '{identifier}' - not found") - - def _remove_bookmark_with_reset(self, identifier: str): - """Execute the remove bookmark action via alt_action (Shift+Enter) and reset to trigger.""" - success = self.bookmark_manager.remove_bookmark(identifier) - if success: - print(f"✓ Removed bookmark '{identifier}'") - # Clear cache to force refresh - self._results_cache.clear() - self._cache_timestamps.clear() - # Reset to trigger word and refresh - self._reset_to_trigger() - else: - print(f"✗ Failed to remove bookmark '{identifier}' - not found") - - def _calculate_relevance(self, bookmark: Dict, query: str) -> float: - """Calculate relevance score for a bookmark.""" - title = bookmark.get("title", "").lower() - url = bookmark.get("url", "").lower() - description = bookmark.get("description", "").lower() - - # Exact title match - if query == title: - return 1.0 - - # Title starts with query - if title.startswith(query): - return 0.95 - - # Query in title - if query in title: - position = title.index(query) - position_score = 1.0 - (position / len(title)) - return 0.8 + (position_score * 0.1) - - # Query in URL - if query in url: - return 0.7 - - # Query in description - if query in description: - return 0.6 - - # Fuzzy matching for title - if len(query) >= 3: - fuzzy_score = fuzz.partial_ratio(query, title) / 100.0 - if fuzzy_score >= 0.7: - return fuzzy_score * 0.6 - - return 0.0 - - def _create_bookmark_result( - self, bookmark: Dict, relevance: float - ) -> Optional[Result]: - """Create a Result object for a bookmark.""" - try: - title = bookmark.get("title", "Untitled") - url = bookmark.get("url", "") - description = bookmark.get("description", "") - - # Truncate long titles to prevent launcher resize - if len(title) > 45: - title = title[:42] + "..." - - # Create subtitle with domain and description - domain = self._extract_domain(url) - - # Truncate domain if too long - if len(domain) > 30: - domain = domain[:27] + "..." - - if description: - # Truncate description to prevent launcher resize - # Account for domain + separator - max_desc_len = 50 - len(domain) - if len(description) > max_desc_len: - description = description[: max_desc_len - 3] + "..." - subtitle = f"{domain} • {description}" - else: - subtitle = domain - - # Final subtitle length check to ensure consistent launcher size - if len(subtitle) > 60: - subtitle = subtitle[:57] + "..." - - return Result( - title=title, - subtitle=subtitle, - icon_name="bookmark-organize", - action=lambda u=url: self._open_bookmark(u), - relevance=relevance, - plugin_name=self.display_name, - data={ - "type": "bookmark", - "url": url, - "domain": domain, - "description": description, - "keep_launcher_open": False, - "alt_action": lambda t=title: self._remove_bookmark_with_reset(t), - }, - ) - except Exception as e: - print(f"Error creating bookmark result: {e}") - return None - - def _extract_domain(self, url: str) -> str: - """Extract domain from URL.""" - try: - parsed = urlparse(url) - domain = parsed.netloc - # Remove www. prefix - if domain.startswith("www."): - domain = domain[4:] - return domain - except Exception: - return url - - def _open_bookmark(self, url: str): - """Open bookmark URL in default browser and update access time.""" - try: - # Update access time - self.bookmark_manager.update_access_time(url) - - # Open URL - subprocess.Popen( - ["xdg-open", url], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL - ) - except Exception as e: - print(f"Failed to open bookmark: {e}") - - def _setup_launcher_hooks(self): - """Setup hooks to monitor launcher state.""" - try: - # Try to find the launcher instance - import gc - - for obj in gc.get_objects(): - if ( - hasattr(obj, "__class__") - and obj.__class__.__name__ == "Launcher" - and hasattr(obj, "close_launcher") - ): - self._launcher_instance = obj - break - except Exception as e: - print(f"Warning: Could not setup launcher hooks: {e}") - - def _cleanup_launcher_hooks(self): - """Cleanup launcher hooks.""" - try: - self._launcher_instance = None - except Exception as e: - print(f"Warning: Could not cleanup launcher hooks: {e}") - - def _reset_to_trigger(self): - """Reset launcher to trigger word and refresh.""" - try: - if self._launcher_instance and hasattr( - self._launcher_instance, "search_entry" - ): - # Get the current trigger (bookmark or bm) - current_text = self._launcher_instance.search_entry.get_text() - trigger = "bookmark " - - # Determine which trigger was used - if current_text.lower().startswith("bm "): - trigger = "bm " - - # Reset to trigger word with space - try: - - def reset_and_refresh(): - # Set text to trigger word - self._launcher_instance.search_entry.set_text(trigger) - # Position cursor at end - self._launcher_instance.search_entry.set_position(-1) - # Trigger search to show default bookmarks - self._launcher_instance._perform_search(trigger) - return False - - GLib.timeout_add(50, reset_and_refresh) - except ImportError: - # Fallback: direct call if GLib not available - self._launcher_instance.search_entry.set_text(trigger) - self._launcher_instance.search_entry.set_position(-1) - self._launcher_instance._perform_search(trigger) - except Exception as e: - print(f"Could not reset to trigger: {e}") - - def _force_launcher_refresh(self): - """Force the launcher to refresh and show updated results.""" - try: - if self._launcher_instance and hasattr( - self._launcher_instance, "_perform_search" - ): - # Get current search text - current_text = "" - if hasattr(self._launcher_instance, "search_entry"): - current_text = self._launcher_instance.search_entry.get_text() - - # Trigger a search to refresh results - try: - - def refresh(): - self._launcher_instance._perform_search(current_text) - return False - - GLib.timeout_add(50, refresh) - except ImportError: - # Fallback: direct call if GLib not available - self._launcher_instance._perform_search(current_text) - except Exception as e: - print(f"Could not force launcher refresh: {e}") diff --git a/src/window/launcher/plugins/otp.py b/src/window/launcher/plugins/otp.py deleted file mode 100644 index 6d9669e..0000000 --- a/src/window/launcher/plugins/otp.py +++ /dev/null @@ -1,851 +0,0 @@ -import json -import subprocess -import threading -from pathlib import Path -from typing import Dict, List, Optional - -from fabric.utils import GLib, get_relative_path, time - -from services.auth import ( - generate_totp, - get_time_remaining_with_blink, - parse_otpauth_uri, - scan_qr_and_add_account, - validate_base32_secret, -) -from window.launcher.plugin_base import PluginBase -from window.launcher.result import Result - - -class OTPPlugin(PluginBase): - """Plugin for managing TOTP (Time-based One-Time Password) codes.""" - - def __init__(self): - super().__init__() - self.display_name = "OTP Manager" - self.description = "Manage TOTP codes and 2FA authentication" - - self.secrets_file = Path(get_relative_path("../../../../config/accounts.json")) - self.secrets: Dict[str, Dict] = {} - self.last_update = 0 - - # Threading for auto-refresh - self.refresh_thread = None - self.stop_refresh = threading.Event() - - def initialize(self): - """Initialize the OTP plugin.""" - self.set_triggers(["otp"]) - self._load_secrets() - self._ensure_config_file() - self._start_refresh_thread() - - def cleanup(self): - """Cleanup the OTP plugin.""" - if self.refresh_thread and self.refresh_thread.is_alive(): - self.stop_refresh.set() - self.refresh_thread.join(timeout=1) - - def _load_secrets(self): - """Load secrets from JSON file.""" - try: - if self.secrets_file.exists(): - with open(self.secrets_file, "r", encoding="utf-8") as f: - self.secrets = json.load(f) - else: - self.secrets = {} - except Exception as e: - print(f"Error loading OTP secrets: {e}") - self.secrets = {} - - def _save_secrets(self): - """Save secrets to JSON file.""" - try: - self.secrets_file.parent.mkdir(parents=True, exist_ok=True) - with open(self.secrets_file, "w", encoding="utf-8") as f: - json.dump(self.secrets, f, indent=2) - except Exception as e: - print(f"Error saving OTP secrets: {e}") - - def _ensure_config_file(self): - """Ensure the config file exists.""" - if not self.secrets_file.exists(): - self.secrets_file.parent.mkdir(parents=True, exist_ok=True) - with open(self.secrets_file, "w", encoding="utf-8") as f: - json.dump({}, f, indent=2) - - def _start_refresh_thread(self): - """Start background thread for auto-refreshing tokens.""" - - def refresh_loop(): - while not self.stop_refresh.wait(5): - current_time = time.time() - if current_time - self.last_update >= 5: - self.last_update = current_time - # Only refresh if we have secrets and launcher is likely active - if self.secrets: - try: - self._selective_force_refresh() - except Exception: - pass - - self.refresh_thread = threading.Thread(target=refresh_loop, daemon=True) - self.refresh_thread.start() - - def _selective_force_refresh(self): - """Update time display in existing OTP result items.""" - try: - from fabric import Application - - def do_update(): - try: - app = Application.get_default() - if not app: - return False - - launcher = None - for window in app.get_windows(): - if window.get_name() == "launcher-window": - launcher = window - break - - if ( - launcher - and hasattr(launcher, "results_box") - and hasattr(launcher, "visible") - and launcher.visible - and hasattr(launcher, "results") - and launcher.results - ): - has_otp_results = any( - result.data and result.data.get("type") == "totp" - for result in launcher.results - if hasattr(result, "data") and result.data - ) - - if has_otp_results: - self._update_existing_result_labels(launcher.results_box) - except Exception: - pass - return False - - GLib.idle_add(do_update) - except Exception: - pass - - def _update_existing_result_labels(self, results_box): - """Update subtitle labels in existing ResultItem widgets.""" - try: - time_display = self._get_time_remaining_with_blink() - for child in results_box.get_children(): - if ( - hasattr(child, "__class__") - and child.__class__.__name__ == "ResultItem" - and hasattr(child, "result") - and hasattr(child.result, "data") - and child.result.data - and child.result.data.get("type") == "totp" - ): - self._update_result_item_content(child, time_display) - except Exception as e: - print(f"Error updating result labels: {e}") - - def _update_result_item_content(self, result_item, time_display): - """Update both the title (OTP code) and subtitle (time display) of a specific ResultItem.""" - try: - account_name = result_item.result.data.get("account", "") - if not account_name or account_name not in self.secrets: - return - - account_data = self.secrets[account_name] - secret = account_data.get("secret", "") - issuer = account_data.get("issuer", "") - display_name = f"{issuer} - {account_name}" if issuer else account_name - - current_totp_code = self._generate_totp(secret) - if not current_totp_code: - return - - old_code = result_item.result.data.get("code", "") - if current_totp_code != old_code: - result_item.result.data["code"] = current_totp_code - self._find_and_update_title_label(result_item, current_totp_code) - result_item.result.action = lambda code=current_totp_code: ( - self._copy_to_clipboard(code) - ) - - new_subtitle_markup = f"{display_name} • {time_display} remaining" - self._find_and_update_subtitle_label(result_item, new_subtitle_markup) - except Exception as e: - print(f"Error updating result item: {e}") - - def _find_and_update_title_label(self, result_item, new_title): - """Find the title label widget and update its text.""" - - def find_title_label(widget): - if hasattr(widget, "get_name") and widget.get_name() == "result-item-title": - return widget - if hasattr(widget, "get_children"): - for child in widget.get_children(): - found = find_title_label(child) - if found: - return found - return None - - title_label = find_title_label(result_item) - if title_label and hasattr(title_label, "set_label"): - title_label.set_label(new_title) - - def _find_and_update_subtitle_label(self, result_item, new_markup): - """Find the subtitle label widget and update its markup.""" - - def find_subtitle_label(widget): - if ( - hasattr(widget, "get_name") - and widget.get_name() == "result-item-subtitle" - ): - return widget - if hasattr(widget, "get_children"): - for child in widget.get_children(): - found = find_subtitle_label(child) - if found: - return found - return None - - subtitle_label = find_subtitle_label(result_item) - if subtitle_label and hasattr(subtitle_label, "set_markup"): - subtitle_label.set_markup(new_markup) - - def _copy_to_clipboard(self, text: str): - """Copy text to clipboard.""" - try: - try: - subprocess.run(["wl-copy"], input=text.encode(), check=True) - except subprocess.SubprocessError: - subprocess.run( - ["xclip", "-selection", "clipboard"], - input=text.encode(), - check=True, - ) - except Exception as e: - print(f"Failed to copy to clipboard: {e}") - - def _trigger_refresh(self): - """Trigger launcher refresh to return to default OTP view.""" - try: - # Use a small delay to ensure the action completes first - def trigger_refresh(): - try: - # Try to access the launcher through the fabric Application - from fabric import Application - - app = Application.get_default() - - if app and hasattr(app, "launcher"): - launcher = app.launcher - if launcher and hasattr(launcher, "search_entry"): - # Clear the search entry and set it to just "otp " - launcher.search_entry.set_text("otp ") - # Position cursor at the end - launcher.search_entry.set_position(-1) - # Trigger the search to show default OTP view - if hasattr(launcher, "_perform_search"): - launcher._perform_search("otp ") - return False - - # Fallback: try to find launcher instance through other means - import gc - - for obj in gc.get_objects(): - if ( - hasattr(obj, "__class__") - and obj.__class__.__name__ == "Launcher" - ): - if hasattr(obj, "search_entry") and hasattr( - obj, "_perform_search" - ): - obj.search_entry.set_text("otp ") - obj.search_entry.set_position(-1) - obj._perform_search("otp ") - return False - - except Exception as e: - print(f"Error forcing launcher refresh: {e}") - - return False # Don't repeat - - # Use a small delay to ensure the action completes first - GLib.timeout_add(50, trigger_refresh) - - except Exception as e: - print(f"Could not trigger refresh: {e}") - - def _remove_account_and_refresh(self, account_name: str): - """Remove an account and trigger refresh to return to default OTP view.""" - try: - if account_name in self.secrets: - # Remove the account - del self.secrets[account_name] - self._save_secrets() - - # Trigger refresh to return to default OTP view - self._trigger_refresh() - except Exception as e: - print(f"Error removing account {account_name}: {e}") - - def _generate_totp(self, secret: str) -> Optional[str]: - """Generate TOTP code from secret.""" - return generate_totp(secret) - - def _get_time_remaining_with_blink(self) -> str: - """Get time remaining with blinking effect.""" - return get_time_remaining_with_blink() - - def query(self, query_string: str) -> List[Result]: - """Process OTP queries.""" - query = query_string.strip() - - if not query: - return self._list_otp_codes() - - query_lower = query.lower() - if query_lower.startswith("add "): - add_content = query[4:].strip() - - # Handle both formats: with ``` and without ``` - if "```" in add_content: - # Old format: add account```secret``` - parts = add_content.split("```", 1) - if len(parts) == 2: - account_name = parts[0].strip() - secret_or_uri = parts[1].strip() - return self._handle_direct_add(account_name, secret_or_uri) - elif " " in add_content: - # New format: add account secret - parts = add_content.split(" ", 1) - if len(parts) == 2: - account_name = parts[0].strip() - secret_or_uri = parts[1].strip() - return self._handle_direct_add(account_name, secret_or_uri) - - return self._handle_add_command(add_content) - elif query_lower == "remove" or query_lower.startswith("remove "): - # Handle both "remove" and "remove accountname" - if query_lower == "remove": - remove_content = "" - else: - remove_content = query[7:].strip() - return self._handle_remove_command(remove_content) - elif query_lower == "qr" or query_lower.startswith("qr "): - # Handle QR scanning command - if query_lower == "qr": - qr_content = "" - else: - qr_content = query[3:].strip() - return self._handle_qr_command(qr_content) - else: - return self._search_accounts(query) - - def _handle_direct_add(self, account_name: str, secret_or_uri: str) -> List[Result]: - """Handle direct addition of OTP account.""" - if not account_name or not secret_or_uri: - return [ - Result( - title="Invalid format", - subtitle="Usage: add <account_name> <secret> or add <account_name>```<secret>```", - icon_name="info", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ) - ] - - try: - if secret_or_uri.startswith("otpauth://"): - return self._handle_otpauth_uri(account_name, secret_or_uri) - else: - return self._handle_base32_secret(account_name, secret_or_uri) - except Exception as e: - print(f"OTP Debug: Error in _handle_direct_add: {e}") - return [ - Result( - title="Error adding account", - subtitle=f"Debug: {str(e)}", - icon_name="cancel", - action=lambda: None, - relevance=0.5, - plugin_name=self.display_name, - data={"type": "error", "keep_launcher_open": True}, - ) - ] - - def _list_otp_codes(self) -> List[Result]: - """List all OTP codes with current tokens.""" - results = [] - - if not self.secrets: - results.append( - Result( - title="No OTP accounts configured", - subtitle="Use 'add <account> <secret>' to add your first account", - icon_name="gtk-authentication-symbolic", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "empty", "keep_launcher_open": True}, - ) - ) - results.append( - Result( - title="Available commands:", - subtitle="add <account> <secret> | remove <account> | qr <account>", - icon_name="info", - action=lambda: None, - relevance=0.9, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ) - ) - return results - - time_display = self._get_time_remaining_with_blink() - - for account_name, account_data in self.secrets.items(): - secret = account_data.get("secret", "") - issuer = account_data.get("issuer", "") - totp_code = self._generate_totp(secret) - - if totp_code: - display_name = f"{issuer} - {account_name}" if issuer else account_name - results.append( - Result( - title=f"{totp_code}", - subtitle_markup=f"{display_name} • { - time_display - } remaining • Shift+Enter: remove", - icon_name="gtk-authentication-symbolic", - action=lambda code=totp_code: self._copy_to_clipboard(code), - relevance=1.0, - plugin_name=self.display_name, - data={ - "type": "totp", - "account": account_name, - "code": totp_code, - "alt_action": lambda acc=account_name: ( - self._remove_account_and_refresh(acc) - ), - }, - ) - ) - else: - results.append( - Result( - title=f"Error: {account_name}", - subtitle="Invalid secret or configuration", - icon_name="dialog-cancel-symbolic", - action=lambda: None, - relevance=0.5, - plugin_name=self.display_name, - data={ - "type": "error", - "account": account_name, - "keep_launcher_open": True, - }, - ) - ) - - return results - - def _search_accounts(self, query: str) -> List[Result]: - """Search accounts by name or issuer.""" - results = [] - query_lower = query.lower() - - for account_name, account_data in self.secrets.items(): - issuer = account_data.get("issuer", "").lower() - account_lower = account_name.lower() - - if query_lower in account_lower or query_lower in issuer: - secret = account_data.get("secret", "") - totp_code = self._generate_totp(secret) - - if totp_code: - display_name = ( - f"{account_data.get('issuer', '')} - {account_name}" - if account_data.get("issuer") - else account_name - ) - time_display = self._get_time_remaining_with_blink() - - results.append( - Result( - title=f"{totp_code}", - subtitle_markup=f"{display_name} • { - time_display - } remaining • Shift+Enter: remove", - icon_name="gtk-authentication-symbolic", - action=lambda code=totp_code: self._copy_to_clipboard(code), - relevance=1.0, - plugin_name=self.display_name, - data={ - "type": "totp", - "account": account_name, - "code": totp_code, - "alt_action": lambda acc=account_name: ( - self._remove_account_and_refresh(acc) - ), - }, - ) - ) - - if not results: - results.append( - Result( - title=f"No accounts found for '{query}'", - subtitle="Use 'add <account> <secret>' to create new account", - icon_name="edit-find-symbolic", - action=lambda: None, - relevance=0.5, - plugin_name=self.display_name, - data={"type": "no_results", "keep_launcher_open": True}, - ) - ) - results.append( - Result( - title="Available commands:", - subtitle="add <account> <secret> | remove <account> | qr <account>", - icon_name="info", - action=lambda: None, - relevance=0.4, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ) - ) - - return results - - def _handle_add_command(self, account_name: str) -> List[Result]: - """Handle manual addition of OTP secret.""" - if not account_name: - return [ - Result( - title="Enter account name", - subtitle="Usage: add <account_name> <secret>", - icon_name="dialog-question-symbolic", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ) - ] - - return [ - Result( - title=f"To add '{account_name}':", - subtitle=f"Type: add {account_name} <secret>", - icon_name="info", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={ - "type": "instruction", - "account": account_name, - "keep_launcher_open": True, - }, - ), - Result( - title="Base32 Secret Format:", - subtitle="Example: add gmail JBSWY3DPEHPK3PXP", - icon_name="info", - action=lambda: None, - relevance=0.9, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ), - Result( - title="otpauth URI Format:", - subtitle="Example: add github otpauth://totp/GitHub:user?secret=JBSWY3DPEHPK3PXP", - icon_name="info", - action=lambda: None, - relevance=0.9, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ), - Result( - title="Remove Account:", - subtitle="Example: remove gmail", - icon_name="trash", - action=lambda: None, - relevance=0.8, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ), - ] - - def _handle_qr_command(self, account_name: str) -> List[Result]: - """Handle QR scanning command.""" - if not account_name: - return [ - Result( - title="Scan QR Code", - subtitle="Click to scan QR code from screen", - icon_name="view-barcode-qr-symbolic", - action=lambda: self._scan_qr_and_add_account(""), - relevance=1.0, - plugin_name=self.display_name, - data={"type": "qr_scan"}, - ), - Result( - title="QR Scan Instructions:", - subtitle="Use 'qr <account_name>' to specify account name", - icon_name="info", - action=lambda: None, - relevance=0.9, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ), - ] - else: - return [ - Result( - title=f"Scan QR Code for '{account_name}'", - subtitle="Click to scan QR code from screen", - icon_name="view-barcode-qr-symbolic", - action=lambda name=account_name: self._scan_qr_and_add_account( - name - ), - relevance=1.0, - plugin_name=self.display_name, - data={"type": "qr_scan"}, - ), - ] - - def _scan_qr_and_add_account(self, account_name: str): - """Scan QR code and add OTP account.""" - print(f"QR scan action called for account: '{account_name}'") - print("Starting QR scan process asynchronously...") - - # Run QR scanning asynchronously so launcher closes immediately - import threading - - thread = threading.Thread(target=self._scan_qr_async, args=(account_name,)) - thread.daemon = True - thread.start() - - def _scan_qr_async(self, account_name: str): - """Async QR scanning process.""" - result = scan_qr_and_add_account(account_name, str(self.secrets_file)) - - if result["success"]: - print(result["message"]) - # Reload secrets from file - self._load_secrets() - # Trigger refresh to show the new account - self._trigger_refresh() - else: - print(f"QR scan failed: {result['error']}") - - def _handle_remove_command(self, account_name: str) -> List[Result]: - """Handle removal of OTP account.""" - if not account_name: - # Show all available accounts for removal - results = [] - - if not self.secrets: - results.append( - Result( - title="No OTP accounts to remove", - subtitle="Use 'add <account> <secret>' to add accounts first", - icon_name="info", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "empty", "keep_launcher_open": True}, - ) - ) - else: - results.append( - Result( - title="Select account to remove:", - subtitle="Type: remove <account_name> to remove an account", - icon_name="user-trash-symbolic", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ) - ) - - # Get time display for consistency with main OTP view - time_display = self._get_time_remaining_with_blink() - - # Show all accounts with their current OTP codes and remove actions - for acc_name, account_data in self.secrets.items(): - secret = account_data.get("secret", "") - issuer = account_data.get("issuer", "") - display_name = f"{issuer} - {acc_name}" if issuer else acc_name - - # Generate current TOTP code - totp_code = self._generate_totp(secret) - - if totp_code: - results.append( - Result( - title=f"{totp_code}", - subtitle_markup=f"Press Enter to remove • { - time_display - } remaining", - icon_name="user-trash-symbolic", - action=lambda acc=acc_name: ( - self._remove_account_and_refresh(acc) - ), - relevance=0.9, - plugin_name=self.display_name, - data={ - "type": "remove_instruction", - "account": acc_name, - "code": totp_code, - "keep_launcher_open": True, - }, - ) - ) - else: - results.append( - Result( - title=f"Error: {acc_name}", - subtitle="Press Enter to remove (Invalid secret)", - icon_name="user-trash-symbolic", - action=lambda acc=acc_name: ( - self._remove_account_and_refresh(acc) - ), - relevance=0.8, - plugin_name=self.display_name, - data={ - "type": "remove_instruction", - "account": acc_name, - "keep_launcher_open": True, - }, - ) - ) - - return results - - # Check if account exists - if account_name not in self.secrets: - return [ - Result( - title=f"Account '{account_name}' not found", - subtitle="Use 'remove' to see all available accounts", - icon_name="dialog-cancel-symbolic", - action=lambda: None, - relevance=0.5, - plugin_name=self.display_name, - data={"type": "error", "keep_launcher_open": True}, - ) - ] - - # Get account info for confirmation - account_data = self.secrets[account_name] - issuer = account_data.get("issuer", "") - display_name = f"{issuer} - {account_name}" if issuer else account_name - - # Show confirmation for removal - return [ - Result( - title=f"Remove '{display_name}'?", - subtitle="Press Enter to confirm removal", - icon_name="user-trash-symbolic", - action=lambda acc=account_name: self._remove_account_and_refresh(acc), - relevance=1.0, - plugin_name=self.display_name, - data={ - "type": "remove_confirm", - "account": account_name, - "keep_launcher_open": True, - }, - ) - ] - - def _handle_base32_secret(self, account_name: str, secret: str) -> List[Result]: - """Handle raw Base32 secret.""" - result = validate_base32_secret(secret) - - if not result["success"]: - return [ - Result( - title="Invalid Base32 secret", - subtitle=result["error"], - icon_name="dialog-cancel-symbolic", - action=lambda: None, - relevance=0.5, - plugin_name=self.display_name, - data={"type": "error", "keep_launcher_open": True}, - ) - ] - - self.secrets[account_name] = { - "secret": result["secret"], - "issuer": "", - "algorithm": "SHA1", - "digits": 6, - "period": 30, - } - self._save_secrets() - - return [ - Result( - title=f"✓ Added '{account_name}'", - subtitle=f"OTP account added successfully (secret: { - result['secret'][:4] - }...)", - icon_name="emblem-ok-symbolic", - action=lambda: self._trigger_refresh(), - relevance=1.0, - plugin_name=self.display_name, - data={"type": "success", "keep_launcher_open": True}, - ) - ] - - def _handle_otpauth_uri(self, account_name: str, uri: str) -> List[Result]: - """Handle otpauth:// URI.""" - result = parse_otpauth_uri(uri, account_name) - - if not result["success"]: - return [ - Result( - title="Error parsing otpauth URI", - subtitle=result["error"], - icon_name="dialog-cancel-symbolic", - action=lambda: None, - relevance=0.5, - plugin_name=self.display_name, - data={"type": "error", "keep_launcher_open": True}, - ) - ] - - self.secrets[result["account_name"]] = { - "secret": result["secret"], - "issuer": result["issuer"], - "algorithm": result["algorithm"], - "digits": result["digits"], - "period": result["period"], - } - self._save_secrets() - - display_name = ( - f"{result['issuer']} - {result['account_name']}" - if result["issuer"] - else result["account_name"] - ) - return [ - Result( - title=f"✓ Added '{display_name}'", - subtitle="OTP account added from URI", - icon_name="emblem-ok-symbolic", - action=lambda: self._trigger_refresh(), - relevance=1.0, - plugin_name=self.display_name, - data={"type": "success", "keep_launcher_open": True}, - ) - ] diff --git a/src/window/launcher/plugins/password.py b/src/window/launcher/plugins/password.py deleted file mode 100644 index 1019fac..0000000 --- a/src/window/launcher/plugins/password.py +++ /dev/null @@ -1,689 +0,0 @@ -import base64 -import json -import subprocess -import threading -from datetime import datetime -from pathlib import Path -from typing import Dict, List, Optional - -from fabric.utils import GLib, get_relative_path, time - -from window.launcher.plugin_base import PluginBase -from window.launcher.result import Result - - -class PasswordManager: - """Simple password manager with basic encryption and caching.""" - - def __init__(self, storage_file: Path): - self.storage_file = storage_file - self.passwords: Dict[str, Dict] = {} - self._cache_lock = threading.Lock() - self._last_loaded = 0 - self._cache_ttl = 30 # Cache for 30 seconds - self._load_passwords() - - def _simple_encrypt(self, text: str, key: str = "modus_pass") -> str: - """Simple encryption using XOR with base64 encoding.""" - key_bytes = key.encode("utf-8") - text_bytes = text.encode("utf-8") - - # XOR encryption - encrypted = bytearray() - for i, byte in enumerate(text_bytes): - encrypted.append(byte ^ key_bytes[i % len(key_bytes)]) - - # Base64 encode - return base64.b64encode(encrypted).decode("utf-8") - - def _simple_decrypt(self, encrypted_text: str, key: str = "modus_pass") -> str: - """Simple decryption using XOR with base64 decoding.""" - try: - key_bytes = key.encode("utf-8") - - # Base64 decode - encrypted_bytes = base64.b64decode(encrypted_text.encode("utf-8")) - - # XOR decryption - decrypted = bytearray() - for i, byte in enumerate(encrypted_bytes): - decrypted.append(byte ^ key_bytes[i % len(key_bytes)]) - - return decrypted.decode("utf-8") - except Exception: - return encrypted_text # Return as-is if decryption fails - - def _load_passwords(self): - """Load passwords from JSON file with caching.""" - with self._cache_lock: - current_time = time.time() - - # Check if cache is still valid - if (current_time - self._last_loaded) < self._cache_ttl and self.passwords: - return - - try: - if self.storage_file.exists(): - with open(self.storage_file, "r", encoding="utf-8") as f: - data = json.load(f) - self.passwords = data.get("passwords", {}) - else: - self.passwords = {} - - self._last_loaded = current_time - except Exception as e: - print(f"Error loading passwords: {e}") - self.passwords = {} - - def _save_passwords(self): - """Save passwords to JSON file.""" - with self._cache_lock: - try: - self.storage_file.parent.mkdir(parents=True, exist_ok=True) - data = { - "passwords": self.passwords, - "last_modified": datetime.now().isoformat(), - } - with open(self.storage_file, "w", encoding="utf-8") as f: - json.dump(data, f, indent=2) - - # Update cache timestamp - self._last_loaded = time.time() - except Exception as e: - print(f"Error saving passwords: {e}") - - def add_password(self, name: str, password: str, description: str = "") -> bool: - """Add a new password entry.""" - try: - encrypted_password = self._simple_encrypt(password) - self.passwords[name] = { - "password": encrypted_password, - "description": description, - "created": datetime.now().isoformat(), - "last_accessed": None, - } - self._save_passwords() - return True - except Exception as e: - print(f"Error adding password: {e}") - return False - - def get_password(self, name: str, update_access_time: bool = True) -> Optional[str]: - """Get decrypted password by name.""" - # Ensure we have fresh data - self._load_passwords() - - if name in self.passwords: - try: - encrypted = self.passwords[name]["password"] - decrypted = self._simple_decrypt(encrypted) - - # Update last accessed time only if requested (to avoid frequent saves) - if update_access_time: - self.passwords[name]["last_accessed"] = datetime.now().isoformat() - # Don't save immediately - batch saves for better performance - - return decrypted - except Exception as e: - print(f"Error decrypting password: {e}") - return None - return None - - def remove_password(self, name: str) -> bool: - """Remove a password entry.""" - if name in self.passwords: - del self.passwords[name] - self._save_passwords() - return True - return False - - def list_passwords(self) -> List[str]: - """Get list of all password names.""" - # Ensure we have fresh data - self._load_passwords() - return list(self.passwords.keys()) - - def get_password_info(self, name: str) -> Optional[Dict]: - """Get password metadata without decrypting.""" - if name in self.passwords: - info = self.passwords[name].copy() - info.pop("password", None) # Remove encrypted password - return info - return None - - -class PasswordPlugin(PluginBase): - """ - Password manager plugin for the launcher. - Stores passwords securely and allows easy access. - """ - - def __init__(self): - super().__init__() - self.display_name = "Password Manager" - self.description = "Secure password storage and management" - - # Initialize password manager - self.password_file = Path( - get_relative_path("../../../../config/passwords.json") - ) - self.password_manager = PasswordManager(self.password_file) - - # State for password visibility - self.revealed_passwords: Dict[str, str] = {} - - # Cache for results to avoid repeated queries - self._results_cache: Dict[str, List[Result]] = {} - self._cache_timestamps: Dict[str, float] = {} - self._cache_ttl = 5 # Cache results for 5 seconds - - # Track launcher state for auto-hiding passwords - self._launcher_instance = None - - def initialize(self): - """Initialize the password plugin.""" - self.set_triggers(["pass"]) - self._setup_launcher_hooks() - - def cleanup(self): - """Cleanup the password plugin.""" - self.revealed_passwords.clear() - self._results_cache.clear() - self._cache_timestamps.clear() - self._cleanup_launcher_hooks() - - def query(self, query_string: str) -> List[Result]: - """Process password manager queries with caching.""" - query_key = query_string.strip() - current_time = time.time() - - # Check cache first (except for add/remove commands which should always execute) - if ( - not query_key.startswith(("add ", "remove ", "delete ")) - and query_key in self._results_cache - and (current_time - self._cache_timestamps.get(query_key, 0)) - < self._cache_ttl - ): - return self._results_cache[query_key] - - results = [] - query = query_key.lower() - - # Handle different commands - if not query: - # Show all passwords - results.extend(self._list_all_passwords()) - elif query.startswith("add "): - # Add new password (don't cache) - results.extend(self._handle_add_command(query_string)) - elif query.startswith("remove ") or query.startswith("delete "): - # Remove password (don't cache) - results.extend(self._handle_remove_command(query_string)) - else: - # Search for specific password - results.extend(self._search_passwords(query)) - - # Cache results (except for add/remove commands) - if not query.startswith(("add ", "remove ", "delete ")): - self._results_cache[query_key] = results - self._cache_timestamps[query_key] = current_time - - return results - - def _list_all_passwords(self) -> List[Result]: - """List all stored passwords.""" - results = [] - password_names = self.password_manager.list_passwords() - - if not password_names: - results.append( - Result( - title="No passwords stored", - subtitle="Use 'pass add <name> <password>' to add your first password", - icon_name="password-symbolic", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "empty", "keep_launcher_open": True}, - ) - ) - results.append( - Result( - title="Available commands:", - subtitle="add <name> <password> | remove <name> | <name> (to search)", - icon_name="info", - action=lambda: None, - relevance=0.9, - plugin_name=self.display_name, - data={"type": "help", "keep_launcher_open": True}, - ) - ) - return results - - # Sort passwords alphabetically - password_names.sort() - - for name in password_names: - info = self.password_manager.get_password_info(name) - description = info.get("description", "") if info else "" - - # Check if password is revealed - if name in self.revealed_passwords: - title = f"{name}: {self.revealed_passwords[name]}" - subtitle = "Password revealed - Enter: copy | Shift+Enter: hide" - else: - title = f"{name}: {'*' * 8}" - subtitle = "Enter: copy | Shift+Enter: reveal password" - - if description: - subtitle += f" | {description}" - - results.append( - Result( - title=title, - subtitle=subtitle, - icon_name="key", - action=lambda n=name: self._copy_password_to_clipboard(n), - relevance=1.0, - plugin_name=self.display_name, - data={ - "type": "password", - "name": name, - "keep_launcher_open": False, - "alt_action": lambda n=name: self._toggle_password_visibility( - n - ), - }, - ) - ) - - return results - - def _handle_add_command(self, query_string: str) -> List[Result]: - """Handle add password command.""" - results = [] - parts = query_string.strip().split(" ", 3) - - if len(parts) < 3: - results.append( - Result( - title="Add Password - Invalid format", - subtitle="Usage: add <name> <password> [description]", - icon_name="cancel", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "error", "keep_launcher_open": True}, - ) - ) - return results - - name = parts[1] - password = parts[2] - description = parts[3] if len(parts) > 3 else "" - - # Check if password already exists - if name in self.password_manager.list_passwords(): - results.append( - Result( - title=f"Update password for '{name}'?", - subtitle="Password already exists. Click to update it.", - icon_name="key", - action=lambda: self._add_password_action( - name, password, description, update=True - ), - relevance=1.0, - plugin_name=self.display_name, - data={"type": "update", "name": name, "keep_launcher_open": False}, - ) - ) - else: - results.append( - Result( - title=f"Add password for '{name}'", - subtitle="Click to save password" - + (f" | {description}" if description else ""), - icon_name="plus", - action=lambda: self._add_password_action( - name, password, description - ), - relevance=1.0, - plugin_name=self.display_name, - data={"type": "add", "name": name, "keep_launcher_open": False}, - ) - ) - - return results - - def _handle_remove_command(self, query_string: str) -> List[Result]: - """Handle remove password command.""" - results = [] - parts = query_string.strip().split(" ", 1) - - if len(parts) < 2: - results.append( - Result( - title="Remove Password - Invalid format", - subtitle="Usage: remove <name>", - icon_name="cancel", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "error", "keep_launcher_open": True}, - ) - ) - return results - - name = parts[1] - - if name not in self.password_manager.list_passwords(): - results.append( - Result( - title=f"Password '{name}' not found", - subtitle="Check the name and try again", - icon_name="cancel", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "error", "keep_launcher_open": True}, - ) - ) - else: - results.append( - Result( - title=f"Remove password '{name}'?", - subtitle="Click to confirm deletion (this cannot be undone)", - icon_name="trash", - action=lambda: self._remove_password_action(name), - relevance=1.0, - plugin_name=self.display_name, - data={"type": "remove", "name": name, "keep_launcher_open": False}, - ) - ) - - return results - - def _search_passwords(self, query: str) -> List[Result]: - """Search for passwords by name.""" - results = [] - password_names = self.password_manager.list_passwords() - - # Filter passwords that match the query - matching_passwords = [ - name for name in password_names if query.lower() in name.lower() - ] - - if not matching_passwords: - results.append( - Result( - title=f"No passwords found matching '{query}'", - subtitle="Try a different search term or use 'pass' to see all passwords", - icon_name="magnifier", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "no_results", "keep_launcher_open": True}, - ) - ) - return results - - # Sort by relevance (exact match first, then starts with, then contains) - def get_relevance(name: str) -> float: - name_lower = name.lower() - query_lower = query.lower() - - if name_lower == query_lower: - return 1.0 - elif name_lower.startswith(query_lower): - return 0.9 - else: - return 0.7 - - matching_passwords.sort(key=get_relevance, reverse=True) - - for name in matching_passwords: - info = self.password_manager.get_password_info(name) - description = info.get("description", "") if info else "" - - # Check if password is revealed - if name in self.revealed_passwords: - title = f"{name}: {self.revealed_passwords[name]}" - subtitle = "Password revealed - Enter: copy | Shift+Enter: hide" - else: - title = f"{name}: {'*' * 8}" - subtitle = "Enter: copy | Shift+Enter: reveal password" - - if description: - subtitle += f" | {description}" - - results.append( - Result( - title=title, - subtitle=subtitle, - icon_name="key", - action=lambda n=name: self._copy_password_to_clipboard(n), - relevance=get_relevance(name), - plugin_name=self.display_name, - data={ - "type": "password", - "name": name, - "keep_launcher_open": False, - "alt_action": lambda n=name: self._toggle_password_visibility( - n - ), - }, - ) - ) - - return results - - def _add_password_action( - self, name: str, password: str, description: str = "", update: bool = False - ): - """Action to add/update a password.""" - try: - success = self.password_manager.add_password(name, password, description) - if success: - action_word = "updated" if update else "added" - # Clear cache to force refresh - self._results_cache.clear() - - # Send notification if available (non-blocking) - try: - subprocess.Popen( - [ - "notify-send", - "Password Manager", - f"Password '{name}' {action_word} successfully", - ] - ) - except Exception: - pass - else: - print(f"Failed to add password '{name}'") - except Exception as e: - print(f"Error adding password: {e}") - - def _remove_password_action(self, name: str): - """Action to remove a password.""" - try: - success = self.password_manager.remove_password(name) - if success: - # Remove from revealed passwords if present - self.revealed_passwords.pop(name, None) - - # Clear cache to force refresh - self._results_cache.clear() - - # Send notification if available (non-blocking) - try: - subprocess.Popen( - [ - "notify-send", - "Password Manager", - f"Password '{name}' removed successfully", - ] - ) - except Exception: - pass - else: - print(f"Failed to remove password '{name}'") - except Exception as e: - print(f"Error removing password: {e}") - - def _copy_password_to_clipboard(self, name: str): - """Copy password to clipboard and reveal it temporarily.""" - try: - password = self.password_manager.get_password( - name, update_access_time=False - ) - if password: - # Copy to clipboard (use timeout to avoid hanging) - try: - subprocess.run( - ["wl-copy"], input=password.encode(), check=True, timeout=2 - ) - except subprocess.SubprocessError: - # Fall back to X11 - subprocess.run( - ["xclip", "-selection", "clipboard"], - input=password.encode(), - check=True, - timeout=2, - ) - - # Reveal password temporarily - self.revealed_passwords[name] = password - - # Send notification if available (non-blocking) - try: - subprocess.Popen( - [ - "notify-send", - "Password Manager", - f"Password for '{name}' copied to clipboard", - ] - ) - except Exception: - pass - - # Clear cache to force refresh - self._results_cache.clear() - - else: - print(f"Failed to retrieve password for '{name}'") - except Exception as e: - print(f"Error copying password: {e}") - - def _reveal_password(self, name: str): - """Reveal password without copying to clipboard.""" - try: - password = self.password_manager.get_password( - name, update_access_time=False - ) - if password: - self.revealed_passwords[name] = password - # Clear cache to force refresh with revealed password - self._results_cache.clear() - else: - print(f"Failed to retrieve password for '{name}'") - except Exception as e: - print(f"Error revealing password: {e}") - - def _hide_password(self, name: str): - """Hide revealed password.""" - self.revealed_passwords.pop(name, None) - - def _hide_all_passwords(self): - """Hide all revealed passwords.""" - if self.revealed_passwords: - self.revealed_passwords.clear() - # Clear cache to force refresh with hidden passwords - self._results_cache.clear() - - def _setup_launcher_hooks(self): - """Setup hooks to monitor launcher state.""" - try: - # Try to find the launcher instance - import gc - - for obj in gc.get_objects(): - if ( - hasattr(obj, "__class__") - and obj.__class__.__name__ == "Launcher" - and hasattr(obj, "close_launcher") - ): - self._launcher_instance = obj - # Store original close_launcher method - self._original_close_launcher = obj.close_launcher - # Replace with our wrapper - obj.close_launcher = self._wrapped_close_launcher - break - except Exception as e: - print(f"Warning: Could not setup launcher hooks: {e}") - - def _cleanup_launcher_hooks(self): - """Cleanup launcher hooks.""" - try: - if self._launcher_instance and hasattr(self, "_original_close_launcher"): - # Restore original close_launcher method - self._launcher_instance.close_launcher = self._original_close_launcher - self._launcher_instance = None - except Exception as e: - print(f"Warning: Could not cleanup launcher hooks: {e}") - - def _wrapped_close_launcher(self): - """Wrapper for launcher close that hides passwords.""" - # Hide all passwords when launcher closes - self._hide_all_passwords() - # Call original close_launcher method - if hasattr(self, "_original_close_launcher"): - self._original_close_launcher() - - def _toggle_password_visibility(self, name: str): - """Toggle password visibility when Shift+Enter is pressed.""" - if name in self.revealed_passwords: - # Hide password - self.revealed_passwords.pop(name, None) - self._results_cache.clear() - else: - # Reveal password - try: - password = self.password_manager.get_password( - name, update_access_time=False - ) - if password: - self.revealed_passwords[name] = password - self._results_cache.clear() - else: - print(f"Failed to retrieve password for '{name}'") - except Exception as e: - print(f"Error revealing password: {e}") - - # Force refresh of the launcher to show updated state - self._force_launcher_refresh() - - def _force_launcher_refresh(self): - """Force the launcher to refresh and show updated results.""" - try: - if self._launcher_instance and hasattr( - self._launcher_instance, "_perform_search" - ): - # Get current search text - current_text = "" - if hasattr(self._launcher_instance, "search_entry"): - current_text = self._launcher_instance.search_entry.get_text() - - # Trigger a search to refresh results - try: - - def refresh(): - self._launcher_instance._perform_search(current_text) - return False - - GLib.timeout_add(50, refresh) - except ImportError: - # Fallback: direct call if GLib not available - self._launcher_instance._perform_search(current_text) - except Exception as e: - print(f"Could not force launcher refresh: {e}") diff --git a/src/window/launcher/plugins/reminders.py b/src/window/launcher/plugins/reminders.py deleted file mode 100644 index 4cd1357..0000000 --- a/src/window/launcher/plugins/reminders.py +++ /dev/null @@ -1,448 +0,0 @@ -import re -import subprocess -import threading -from datetime import datetime, timedelta -from typing import Dict, List, Optional - -from window.launcher.plugin_base import PluginBase -from window.launcher.result import Result - - -class Reminder: - """ - Represents a single reminder with its timer and metadata. - """ - - def __init__( - self, - reminder_id: int, - message: str, - target_time: datetime, - timer: threading.Timer, - ): - self.id = reminder_id - self.message = message - self.target_time = target_time - self.timer = timer - self.created_time = datetime.now() - - def cancel(self): - """Cancel this reminder.""" - if self.timer: - self.timer.cancel() - - def get_time_remaining(self) -> str: - """Get formatted time remaining until reminder.""" - now = datetime.now() - if self.target_time <= now: - return "Overdue" - - delta = self.target_time - now - total_seconds = int(delta.total_seconds()) - - if total_seconds < 60: - return f"{total_seconds}s" - elif total_seconds < 3600: - minutes = total_seconds // 60 - seconds = total_seconds % 60 - return f"{minutes}m {seconds}s" if seconds > 0 else f"{minutes}m" - else: - hours = total_seconds // 3600 - minutes = (total_seconds % 3600) // 60 - return f"{hours}h {minutes}m" if minutes > 0 else f"{hours}h" - - def get_target_time_str(self) -> str: - """Get formatted target time.""" - return self.target_time.strftime("%H:%M") - - -class RemindersPlugin(PluginBase): - """ - Time-based reminders plugin for the launcher. - """ - - def __init__(self): - super().__init__() - self.display_name = "Reminders" - self.description = "Set time-based reminders with notifications" - self.reminders: Dict[int, Reminder] = {} - self.next_id = 1 - - # Regex patterns for time parsing - self.time_patterns = { - "relative_time": re.compile(r"^(\d+)([smhd])$"), # 5m, 30s, 2h, 1d - "absolute_time": re.compile(r"^(\d{1,2}):(\d{2})$"), # 14:30, 9:15 - "relative_with_unit": re.compile( - r"^(\d+)\s*(min|mins|minute|minutes|hour|hours|sec|seconds|day|days)$", - re.IGNORECASE, - ), - } - - def initialize(self): - """Initialize the reminders plugin.""" - self.set_triggers(["remind"]) - - def cleanup(self): - """Cleanup the reminders plugin.""" - # Cancel all active reminders - for reminder in self.reminders.values(): - reminder.cancel() - self.reminders.clear() - - def _send_notification(self, title: str, message: str): - """Send a desktop notification using notify-send.""" - try: - subprocess.run( - ["notify-send", "-a", "Reminders", "-i", "alarm-clock", title, message], - check=False, - ) - except Exception as e: - print(f"Failed to send notification: {e}") - - def _parse_time_input(self, time_str: str) -> Optional[datetime]: - """ - Parse various time input formats and return target datetime. - - Supported formats: - - 5m, 30s, 2h, 1d (relative time) - - 14:30, 9:15 (absolute time today) - - 5 minutes, 2 hours (relative with full unit names) - """ - time_str = time_str.strip().lower() - - # Try relative time format (5m, 30s, 2h, 1d) - match = self.time_patterns["relative_time"].match(time_str) - if match: - value, unit = match.groups() - value = int(value) - - if unit == "s": - delta = timedelta(seconds=value) - elif unit == "m": - delta = timedelta(minutes=value) - elif unit == "h": - delta = timedelta(hours=value) - elif unit == "d": - delta = timedelta(days=value) - else: - return None - - return datetime.now() + delta - - # Try absolute time format (14:30, 9:15) - match = self.time_patterns["absolute_time"].match(time_str) - if match: - hour, minute = map(int, match.groups()) - if 0 <= hour <= 23 and 0 <= minute <= 59: - target = datetime.now().replace( - hour=hour, minute=minute, second=0, microsecond=0 - ) - # If the time has already passed today, schedule for tomorrow - if target <= datetime.now(): - target += timedelta(days=1) - return target - - # Try relative time with full unit names - match = self.time_patterns["relative_with_unit"].match(time_str) - if match: - value, unit = match.groups() - value = int(value) - unit = unit.lower() - - if unit in ["sec", "seconds"]: - delta = timedelta(seconds=value) - elif unit in ["min", "mins", "minute", "minutes"]: - delta = timedelta(minutes=value) - elif unit in ["hour", "hours"]: - delta = timedelta(hours=value) - elif unit in ["day", "days"]: - delta = timedelta(days=value) - else: - return None - - return datetime.now() + delta - - return None - - def _create_reminder(self, time_str: str, message: str) -> Optional[Reminder]: - """Create a new reminder with the given time and message.""" - target_time = self._parse_time_input(time_str) - if not target_time: - return None - - # Calculate delay in seconds - delay = (target_time - datetime.now()).total_seconds() - if delay <= 0: - return None - - # Create timer that will trigger the notification - timer = threading.Timer(delay, self._trigger_reminder, [self.next_id, message]) - - # Create reminder object - reminder = Reminder(self.next_id, message, target_time, timer) - - # Store reminder and start timer - self.reminders[self.next_id] = reminder - timer.start() - - # Increment ID for next reminder - self.next_id += 1 - - return reminder - - def _trigger_reminder(self, reminder_id: int, message: str): - """Trigger a reminder notification and remove it from active reminders.""" - # Send notification - self._send_notification("⏰ Reminder", message) - - # Remove from active reminders - if reminder_id in self.reminders: - del self.reminders[reminder_id] - - def _cancel_reminder(self, reminder_id: Optional[int] = None) -> int: - """Cancel a specific reminder or all reminders. Returns number of cancelled reminders.""" - if reminder_id is not None: - if reminder_id in self.reminders: - self.reminders[reminder_id].cancel() - del self.reminders[reminder_id] - return 1 - return 0 - else: - # Cancel all reminders - count = len(self.reminders) - for reminder in self.reminders.values(): - reminder.cancel() - self.reminders.clear() - return count - - def _format_time_remaining(self, total_seconds: float) -> str: - """Format time remaining in a human-readable way.""" - total_seconds = int(total_seconds) - - if total_seconds < 60: - return f"{total_seconds}s" - elif total_seconds < 3600: - minutes = total_seconds // 60 - seconds = total_seconds % 60 - return f"{minutes}m {seconds}s" if seconds > 0 else f"{minutes}m" - else: - hours = total_seconds // 3600 - minutes = (total_seconds % 3600) // 60 - return f"{hours}h {minutes}m" if minutes > 0 else f"{hours}h" - - def _create_and_confirm_reminder(self, time_str: str, message: str): - """Actually create the reminder when the user presses Enter.""" - reminder = self._create_reminder(time_str, message) - if reminder: - time_remaining = reminder.get_time_remaining() - self._send_notification( - "✅ Reminder Created", f"Reminder set for {time_remaining}: {message}" - ) - else: - self._send_notification( - "❌ Failed to Create Reminder", "The specified time may be in the past" - ) - - def query(self, query_string: str) -> List[Result]: - """Process reminder queries.""" - results = [] - query = query_string.strip() - - if not query: - # Show help and active reminders count - active_count = len(self.reminders) - results.append( - Result( - title="Reminders Help", - subtitle=f"Active reminders: { - active_count - } | Usage: remind 5m Take a break", - icon_name="alarm-timer", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "help"}, - ) - ) - - # Show quick examples - examples = [ - ("remind 5m Take a break", "Set 5 minute reminder"), - ("remind 14:30 Meeting", "Set reminder for 2:30 PM"), - ("remind list", "List active reminders"), - ("remind cancel", "Cancel all reminders"), - ] - - for example, desc in examples: - results.append( - Result( - title=example, - subtitle=desc, - icon_name="alarm-timer", - action=lambda: None, - relevance=0.8, - plugin_name=self.display_name, - data={"type": "example"}, - ) - ) - - return results - - # Handle list command - if query.lower() in ["list", "ls", "show"]: - if not self.reminders: - results.append( - Result( - title="No Active Reminders", - subtitle="Use 'remind 5m message' to set a reminder", - icon_name="timer-off", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "empty_list"}, - ) - ) - else: - for reminder in sorted( - self.reminders.values(), key=lambda r: r.target_time - ): - time_remaining = reminder.get_time_remaining() - target_time = reminder.get_target_time_str() - - results.append( - Result( - title=f"#{reminder.id}: {reminder.message}", - subtitle=f"In {time_remaining} (at {target_time})", - icon_name="alarm-timer", - action=lambda rid=reminder.id: self._cancel_reminder(rid), - relevance=1.0, - plugin_name=self.display_name, - data={"type": "active_reminder", "id": reminder.id}, - ) - ) - - return results - - # Handle cancel command - if query.lower().startswith("cancel") or query.lower().startswith("stop"): - parts = query.split() - if len(parts) == 1: - # Cancel all reminders - count = self._cancel_reminder() - results.append( - Result( - title=f"Cancelled {count} Reminders", - subtitle="All active reminders have been cancelled", - icon_name="timer-off", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "cancel_all"}, - ) - ) - else: - # Try to cancel specific reminder by ID - try: - reminder_id = int(parts[1]) - count = self._cancel_reminder(reminder_id) - if count > 0: - results.append( - Result( - title=f"Cancelled Reminder #{reminder_id}", - subtitle="Reminder has been cancelled", - icon_name="timer-off", - action=lambda: None, - relevance=1.0, - plugin_name=self.display_name, - data={"type": "cancel_specific"}, - ) - ) - else: - results.append( - Result( - title="Reminder Not Found", - subtitle=f"No reminder with ID #{reminder_id}", - icon_name="alert", - action=lambda: None, - relevance=0.5, - plugin_name=self.display_name, - data={"type": "error"}, - ) - ) - except ValueError: - results.append( - Result( - title="Invalid Reminder ID", - subtitle="Please provide a valid reminder ID number", - icon_name="alert", - action=lambda: None, - relevance=0.5, - plugin_name=self.display_name, - data={"type": "error"}, - ) - ) - - return results - - # Handle setting new reminders - parts = query.split(None, 1) - if len(parts) >= 1: - time_str = parts[0] - message = parts[1] if len(parts) > 1 else "Reminder" - - # Try to parse the time (but don't create the reminder yet!) - target_time = self._parse_time_input(time_str) - if target_time: - # Calculate delay and check if it's valid - delay = (target_time - datetime.now()).total_seconds() - if delay > 0: - # Show what would happen, but don't create the reminder yet - time_remaining = self._format_time_remaining(delay) - target_time_str = target_time.strftime("%H:%M") - - results.append( - Result( - title=f"Set Reminder: {message}", - subtitle=f"Will remind in {time_remaining} (at { - target_time_str - })", - icon_name="alarm-timer", - action=lambda ts=time_str, msg=message: ( - self._create_and_confirm_reminder(ts, msg) - ), - relevance=1.0, - plugin_name=self.display_name, - data={ - "type": "preview", - "time_str": time_str, - "message": message, - }, - ) - ) - else: - results.append( - Result( - title="Time is in the Past", - subtitle="Please specify a future time", - icon_name="alert", - action=lambda: None, - relevance=0.5, - plugin_name=self.display_name, - data={"type": "error"}, - ) - ) - else: - # Invalid time format - results.append( - Result( - title="Invalid Time Format", - subtitle="Use formats like: 5m, 30s, 2h, 14:30, or '5 minutes'", - icon_name="alert", - action=lambda: None, - relevance=0.5, - plugin_name=self.display_name, - data={"type": "error"}, - ) - ) - - return results diff --git a/src/window/launcher/plugins/system.py b/src/window/launcher/plugins/system.py deleted file mode 100644 index e850921..0000000 --- a/src/window/launcher/plugins/system.py +++ /dev/null @@ -1,240 +0,0 @@ -import json -import threading -from typing import List, Set, Union - -from fabric.utils import exec_shell_command_async, os, shlex, time - -import shared.data as data -from window.launcher.plugin_base import PluginBase -from window.launcher.result import Result - - -class SystemPlugin(PluginBase): - """ - Plugin for system commands and actions. - """ - - def __init__(self): - super().__init__() - self.display_name = "System" - self.description = "System commands and actions" - - # JSON cache file for system binaries - self.bin_cache_file = os.path.join(data.CACHE_DIR, "system_binaries.json") - - # In-memory cache for system binaries - self._bin_cache: Set[str] = set() - self._last_bin_update = 0 - self._bin_update_interval = 300 # 5 minutes - - # Background cache building - self._cache_building = False - self._cache_thread = None - - def initialize(self): - """Initialize the system plugin.""" - self.set_triggers(["bin"]) - self._load_bin_cache() - self._start_background_cache_update() - - def cleanup(self): - """Cleanup the system plugin.""" - self._bin_cache.clear() - if self._cache_thread and self._cache_thread.is_alive(): - # Note: We don't join the thread to avoid blocking cleanup - pass - - def _load_bin_cache(self): - """Load binary cache from JSON file.""" - try: - if os.path.exists(self.bin_cache_file): - with open(self.bin_cache_file, "r", encoding="utf-8") as f: - cache_data = json.load(f) - self._bin_cache = set(cache_data.get("binaries", [])) - self._last_bin_update = cache_data.get("last_update", 0) - else: - print( - "SystemPlugin: No cache file found, will build cache in background" - ) - except Exception as e: - print(f"SystemPlugin: Error loading binary cache: {e}") - self._bin_cache = set() - self._last_bin_update = 0 - - def _save_bin_cache(self): - """Save binary cache to JSON file.""" - try: - # Ensure the cache directory exists - os.makedirs(data.CACHE_DIR, exist_ok=True) - - cache_data = { - "binaries": sorted(list(self._bin_cache)), - "last_update": self._last_bin_update, - "cache_version": "1.0", - } - - with open(self.bin_cache_file, "w", encoding="utf-8") as f: - json.dump(cache_data, f, indent=2) - except Exception as e: - print(f"SystemPlugin: Error saving binary cache: {e}") - - def _start_background_cache_update(self): - """Start background thread to update binary cache.""" - current_time = time.time() - - # Check if cache needs updating - if ( - current_time - self._last_bin_update > self._bin_update_interval - or not self._bin_cache - ): - if not self._cache_building: - self._cache_building = True - self._cache_thread = threading.Thread( - target=self._build_bin_cache_background, daemon=True - ) - self._cache_thread.start() - - def _build_bin_cache_background(self): - """Build binary cache in background thread.""" - try: - new_cache = set() - processed_paths = set() # Avoid duplicate paths - - for path in os.environ["PATH"].split(":"): - # Skip empty paths and duplicates - if not path or path in processed_paths: - continue - processed_paths.add(path) - - if os.path.exists(path) and os.path.isdir(path): - try: - # Use os.scandir for better performance than os.listdir - with os.scandir(path) as entries: - for entry in entries: - if entry.is_file(follow_symlinks=False) and os.access( - entry.path, os.X_OK - ): - new_cache.add(entry.name) - except (PermissionError, FileNotFoundError, OSError): - continue - - # Update cache atomically - self._bin_cache = new_cache - self._last_bin_update = time.time() - - # Save to disk - self._save_bin_cache() - - except Exception as e: - print(f"SystemPlugin: Error building binary cache: {e}") - finally: - self._cache_building = False - - def query(self, query_string: str) -> List[Result]: - """Search for system commands matching the query.""" - query = query_string.strip() - - if not query: - return [] - - results = [] - - # Parse the query to extract binary name and arguments - query_parts = query.split() - if not query_parts: - return [] - - binary_query = query_parts[0].lower() - full_command = query # Keep the original case and spacing - - # Check system binaries - # Start background update if needed (non-blocking) - but only if cache is empty or very old - if not self._bin_cache or ( - time.time() - self._last_bin_update > self._bin_update_interval - ): - self._start_background_cache_update() - - # Optimize search with early termination and result limiting - exact_matches = [] - prefix_matches = [] - partial_matches = [] - max_results = 20 # Limit total results for performance - - for binary in self._bin_cache: - # Pre-compute lowercase once - binary_lower = binary.lower() - - # Skip if no match at all - if binary_query not in binary_lower: - continue - - # Categorize matches for better sorting - if binary_lower == binary_query: - # Exact match - highest priority - display_command = full_command - command_to_execute = full_command - relevance = 1.0 - exact_matches.append( - (binary, display_command, command_to_execute, relevance) - ) - elif binary_lower.startswith(binary_query): - # Prefix match - high priority - display_command = binary - command_to_execute = binary - relevance = 0.9 - prefix_matches.append( - (binary, display_command, command_to_execute, relevance) - ) - else: - # Partial match - lower priority - display_command = binary - command_to_execute = binary - relevance = 0.7 - partial_matches.append( - (binary, display_command, command_to_execute, relevance) - ) - - # Early termination if we have enough good matches - if len(exact_matches) + len(prefix_matches) >= max_results: - break - - # Combine results in priority order - all_matches = exact_matches + prefix_matches + partial_matches - - # Convert to Result objects (limit to max_results) - for binary, display_command, command_to_execute, relevance in all_matches[ - :max_results - ]: - result = Result( - title=display_command, - subtitle=f"Execute: {display_command}", - icon_name="terminal", - action=self._create_action(command_to_execute), - relevance=relevance, - plugin_name=self.display_name, - data={"command": command_to_execute, "id": binary}, - ) - results.append(result) - - return results # Already sorted by priority - - def _create_action(self, command: Union[str, List[str]]): - """Create an action function for the given command.""" - - def action(): - self._execute_command(command) - - return action - - def _execute_command(self, command: Union[str, List[str]]): - """Execute a system command.""" - try: - if isinstance(command, str): - # Handle string commands with arguments - split into list for proper execution - command_list = shlex.split(command) - exec_shell_command_async(command_list) - else: - # Handle list commands (backward compatibility) - exec_shell_command_async(command) - except Exception as e: - print(f"SystemPlugin: Error executing command '{command}': {e}") diff --git a/src/window/launcher/plugins/tmux.py b/src/window/launcher/plugins/tmux.py deleted file mode 100644 index 00d96b6..0000000 --- a/src/window/launcher/plugins/tmux.py +++ /dev/null @@ -1,334 +0,0 @@ -import subprocess -import threading -from typing import List - -from fabric.utils import exec_shell_command_async, time - -import shared.data as data -from window.launcher.plugin_base import PluginBase -from window.launcher.result import Result - - -class TmuxPlugin(PluginBase): - """ - Plugin for managing tmux sessions through the launcher. - """ - - def __init__(self): - super().__init__() - self.display_name = "Tmux Manager" - self.description = "Manage tmux sessions - create, attach, rename, and kill" - - # Cache for sessions to avoid repeated subprocess calls - self._sessions_cache = [] - self._last_cache_update = 0 - # Cache sessions for 10 seconds (increased from 2) - self._cache_ttl = 10 - - # Threading for auto-refresh - only when actively used - self.refresh_thread = None - self.stop_refresh = threading.Event() - self._last_query_time = 0 - # Stop refreshing after 30 seconds of inactivity - self._active_refresh_timeout = 30 - - def initialize(self): - """Initialize the tmux plugin.""" - self.set_triggers(["tmux"]) - # Don't start refresh thread immediately - start it when first used - - def cleanup(self): - """Cleanup the tmux plugin.""" - self.stop_refresh.set() - if self.refresh_thread: - self.refresh_thread.join(timeout=1) - self._sessions_cache.clear() - - def _start_refresh_thread(self): - """Start background thread to refresh session cache.""" - if not self.refresh_thread or not self.refresh_thread.is_alive(): - self.refresh_thread = threading.Thread( - target=self._refresh_sessions_background, daemon=True - ) - self.refresh_thread.start() - - def _refresh_sessions_background(self): - """Background thread to refresh sessions cache only when actively used.""" - while not self.stop_refresh.is_set(): - try: - current_time = time.time() - - # Stop refreshing if plugin hasn't been used recently - if current_time - self._last_query_time > self._active_refresh_timeout: - print("TmuxPlugin: Stopping background refresh due to inactivity") - break - - if current_time - self._last_cache_update > self._cache_ttl: - self._sessions_cache = self._get_tmux_sessions() - self._last_cache_update = current_time - - self.stop_refresh.wait(5) - except Exception as e: - print(f"TmuxPlugin: Error in refresh thread: {e}") - self.stop_refresh.wait(10) # Wait longer on error - - def _get_tmux_sessions(self): - """Get list of tmux sessions.""" - try: - result = subprocess.run( - ["tmux", "list-sessions", "-F", "#{session_name}"], - capture_output=True, - text=True, - timeout=5, - ) - if result.returncode == 0: - return [ - s.strip() for s in result.stdout.strip().split("\n") if s.strip() - ] - return [] - except ( - subprocess.TimeoutExpired, - subprocess.CalledProcessError, - FileNotFoundError, - ) as e: - print(f"TmuxPlugin: Error getting tmux sessions: {e}") - return [] - - def query(self, query_string: str) -> List[Result]: - """Process tmux queries.""" - query = query_string.strip().lower() - results = [] - - # Track usage and start refresh thread if needed - current_time = time.time() - self._last_query_time = current_time - - # Start refresh thread if not running and plugin is being used - if not self.refresh_thread or not self.refresh_thread.is_alive(): - self._start_refresh_thread() - - # Get current sessions (use cache if recent) - if current_time - self._last_cache_update > self._cache_ttl: - self._sessions_cache = self._get_tmux_sessions() - self._last_cache_update = current_time - - sessions = self._sessions_cache - - # Handle specific commands - if query.startswith("new ") or query.startswith("create "): - session_name = query.split(" ", 1)[1].strip() if " " in query else "" - results.append(self._create_new_session_result(session_name)) - - elif query.startswith("kill ") or query.startswith("delete "): - session_name = query.split(" ", 1)[1].strip() if " " in query else "" - if session_name: - matching_sessions = [ - s for s in sessions if session_name.lower() in s.lower() - ] - for session in matching_sessions: - results.append(self._create_kill_session_result(session)) - - elif query.startswith("rename "): - parts = query.split(" ", 2) - if len(parts) >= 3: - old_name, new_name = parts[1], parts[2] - if old_name in sessions: - results.append( - self._create_rename_session_result(old_name, new_name) - ) - - else: - # Show existing sessions for attachment - if sessions: - # Filter sessions based on query - if query: - filtered_sessions = [s for s in sessions if query in s.lower()] - else: - filtered_sessions = sessions - - for session in filtered_sessions: - results.append(self._create_attach_session_result(session)) - - # Always show option to create new session - if not query or "new" in query or "create" in query: - results.append( - self._create_new_session_result( - query - if query and not any(cmd in query for cmd in ["new", "create"]) - else "" - ) - ) - - return results - - def _create_attach_session_result(self, session_name: str) -> Result: - """Create result for attaching to a session.""" - return Result( - title=f"Attach to '{session_name}'", - subtitle=f"Connect to tmux session: {session_name}", - icon_name="terminal", - action=lambda: self._attach_to_session(session_name), - relevance=0.9, - data={"type": "attach", "session": session_name}, - ) - - def _create_new_session_result(self, session_name: str = "") -> Result: - """Create result for creating a new session.""" - display_name = session_name if session_name else "new session" - return Result( - title=f"Create '{display_name}'", - subtitle=f"Create new tmux session{ - f': {session_name}' if session_name else '' - }", - icon_name="plus", - action=lambda: self._create_session(session_name), - relevance=0.8, - data={"type": "create", "session": session_name}, - ) - - def _create_kill_session_result(self, session_name: str) -> Result: - """Create result for killing a session.""" - return Result( - title=f"Kill '{session_name}'", - subtitle=f"Terminate tmux session: {session_name}", - icon_name="trash", - action=lambda: self._kill_session(session_name), - relevance=0.7, - data={"type": "kill", "session": session_name}, - ) - - def _create_rename_session_result(self, old_name: str, new_name: str) -> Result: - """Create result for renaming a session.""" - return Result( - title=f"Rename '{old_name}' to '{new_name}'", - subtitle=f"Rename tmux session from {old_name} to {new_name}", - icon_name="config", - action=lambda: self._rename_session(old_name, new_name), - relevance=0.6, - data={"type": "rename", "old_session": old_name, "new_session": new_name}, - ) - - def _attach_to_session(self, session_name: str): - """Attach to an existing tmux session.""" - try: - terminal_cmd = self._get_terminal_command( - f"tmux attach-session -t '{session_name}'" - ) - exec_shell_command_async(terminal_cmd) - print(f"TmuxPlugin: Attaching to session '{session_name}'") - except Exception as e: - print(f"TmuxPlugin: Error attaching to session '{session_name}': {e}") - - def _create_session(self, session_name: str = ""): - """Create a new tmux session.""" - try: - if not session_name: - # Generate a default name - existing_sessions = self._get_tmux_sessions() - counter = 0 - while str(counter) in existing_sessions: - counter += 1 - session_name = str(counter) - - # Clean the session name - clean_name = session_name.strip().replace(" ", "_") - - # Create session - subprocess.run( - ["tmux", "new-session", "-d", "-s", clean_name], check=True, timeout=10 - ) - - # Launch terminal and attach - terminal_cmd = self._get_terminal_command( - f"tmux attach-session -t '{clean_name}'" - ) - exec_shell_command_async(terminal_cmd) - - # Refresh cache - self._sessions_cache = self._get_tmux_sessions() - self._last_cache_update = time.time() - - print(f"TmuxPlugin: Created and attached to session '{clean_name}'") - except Exception as e: - print(f"TmuxPlugin: Error creating session '{session_name}': {e}") - - def _kill_session(self, session_name: str): - """Kill a tmux session.""" - try: - subprocess.run( - ["tmux", "kill-session", "-t", session_name], check=True, timeout=10 - ) - - # Refresh cache - self._sessions_cache = self._get_tmux_sessions() - self._last_cache_update = time.time() - - print(f"TmuxPlugin: Killed session '{session_name}'") - except Exception as e: - print(f"TmuxPlugin: Error killing session '{session_name}': {e}") - - def _rename_session(self, old_name: str, new_name: str): - """Rename a tmux session.""" - try: - clean_name = new_name.strip().replace(" ", "_") - subprocess.run( - ["tmux", "rename-session", "-t", old_name, clean_name], - check=True, - timeout=10, - ) - - # Refresh cache - self._sessions_cache = self._get_tmux_sessions() - self._last_cache_update = time.time() - - print(f"TmuxPlugin: Renamed session '{old_name}' to '{clean_name}'") - except Exception as e: - print( - f"TmuxPlugin: Error renaming session '{old_name}' to '{new_name}': {e}" - ) - - def _get_terminal_command(self, cmd: str) -> str: - """Get terminal command based on configured terminal or available terminals.""" - # First try to use the configured terminal command - if hasattr(data, "TERMINAL_COMMAND") and data.TERMINAL_COMMAND: - parts = data.TERMINAL_COMMAND.split() - terminal = parts[0] - - try: - # Check if the configured terminal is available - subprocess.run( - ["which", terminal], - check=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - ) - return f"{data.TERMINAL_COMMAND} {cmd}" - except subprocess.CalledProcessError: - # If configured terminal is not available, fall back to defaults - pass - - # Fallback to checking available terminals - terminals = [ - ("kitty", f"kitty -e {cmd}"), - ("alacritty", f"alacritty -e {cmd}"), - ("foot", f"foot {cmd}"), - ("gnome-terminal", f"gnome-terminal -- {cmd}"), - ("konsole", f"konsole -e {cmd}"), - ("xfce4-terminal", f"xfce4-terminal -e '{cmd}'"), - ] - - for term, term_cmd in terminals: - try: - # Check if terminal is available - subprocess.run( - ["which", term], - check=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - ) - return term_cmd - except subprocess.CalledProcessError: - continue - - # Default fallback - return f"kitty -e {cmd}"