added launcher and fixes some error in config.py and in applications.py

This commit is contained in:
sankalp committed 2025-06-17 12:17:20 +05:45
1 parent 90ebffe6dd
commit 811c7d3449
30 files changed
+3459 -214

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
"""
Built-in plugins for the launcher.
"""
+195
View File
@@ -0,0 +1,195 @@
"""
Applications plugin for the launcher.
Searches and launches desktop applications.
"""
import re
import json
from typing import List
from fabric.utils.helpers import get_desktop_applications, get_relative_path
from ..plugin_base import PluginBase
from ..result import Result
from modules.dock.main import Dock
class ApplicationsPlugin(PluginBase):
"""
Plugin for searching and launching desktop applications.
"""
def __init__(self):
super().__init__()
self.display_name = "Applications"
self.description = "Search and launch desktop applications"
self.applications = []
def initialize(self):
"""Initialize the applications plugin."""
# Set up triggers for applications - both with and without spaces
self.set_triggers(["app", "app "])
print("Initializing Applications plugin...")
self._load_applications()
def cleanup(self):
"""Cleanup the applications plugin."""
self.applications = []
def _load_applications(self):
"""Load all desktop applications."""
try:
self.applications = get_desktop_applications(include_hidden=False)
print(f"Loaded {len(self.applications)} applications")
except Exception as e:
print(f"Failed to load applications: {e}")
self.applications = []
def _pin_application(self, app):
"""Pin an application to the dock."""
app_data = {
k: v
for k, v in {
"name": app.name,
"display_name": app.display_name,
"window_class": app.window_class,
"executable": app.executable,
"command_line": app.command_line,
"icon_name": app.icon_name,
}.items()
if v is not None
}
config_path = get_relative_path("../../../config/dock.json")
try:
with open(config_path, "r") as file:
data = json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
data = {"pinned_apps": []}
already_pinned = False
for pinned_app in data.get("pinned_apps", []):
if (
isinstance(pinned_app, dict)
and pinned_app.get("name") == app_data["name"]
):
already_pinned = True
pinned_app.update(app_data)
break
elif isinstance(pinned_app, str) and pinned_app == app_data["name"]:
already_pinned = True
data["pinned_apps"].remove(pinned_app)
data["pinned_apps"].append(app_data)
break
if not already_pinned:
data.setdefault("pinned_apps", []).append(app_data)
with open(config_path, "w") as file:
json.dump(data, file, indent=4)
Dock.notify_config_change()
def query(self, query_string: str) -> List[Result]:
"""Search applications based on query."""
if not query_string.strip():
return []
query = query_string.lower().strip()
results = []
for app in self.applications:
relevance = self._calculate_relevance(app, query)
if relevance > 0:
result = Result(
title=app.display_name or app.name,
subtitle=app.description or app.generic_name or "",
icon=app.get_icon_pixbuf(size=48),
action=lambda a=app: self._launch_application(a),
relevance=relevance,
plugin_name=self.display_name,
data={
"app": app,
"pin_action": lambda a=app: self._pin_application(a)
},
)
results.append(result)
return results
def _calculate_relevance(self, app, query: str) -> float:
"""Calculate relevance score for an application."""
if not query:
return 0.0
# Get searchable text
name = (app.name or "").lower()
display_name = (app.display_name or "").lower()
description = (app.description or "").lower()
generic_name = (app.generic_name or "").lower()
executable = (app.executable or "").lower()
# Exact matches get highest score
if query == name or query == display_name:
return 1.0
# Starts with matches get high score
if (
name.startswith(query)
or display_name.startswith(query)
or generic_name.startswith(query)
):
return 0.9
# Contains matches get medium score
if (
query in name
or query in display_name
or query in description
or query in generic_name
):
return 0.7
# Fuzzy matching for partial matches
if self._fuzzy_match(query, name) or self._fuzzy_match(query, display_name):
return 0.5
# Executable name matching
if executable and query in executable:
return 0.4
return 0.0
def _fuzzy_match(self, query: str, text: str) -> bool:
"""Simple fuzzy matching algorithm."""
if not query or not text:
return False
# Create regex pattern for fuzzy matching
pattern = ".*".join(re.escape(char) for char in query)
return bool(re.search(pattern, text, re.IGNORECASE))
def _launch_application(self, app):
"""Launch a desktop application."""
try:
success = app.launch()
if not success:
# Fallback to command line execution
if app.command_line:
import subprocess
subprocess.Popen(
app.command_line,
shell=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
elif app.executable:
import subprocess
subprocess.Popen(
[app.executable],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
print(f"Launched application: {app.name}")
except Exception as e:
print(f"Failed to launch application {app.name}: {e}")
+127
View File
@@ -0,0 +1,127 @@
"""
Caffeine plugin for the launcher.
Prevents system from going idle for a specified duration.
"""
import subprocess
import os
from typing import List
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GdkPixbuf, GLib
from ..plugin_base import PluginBase
from ..result import Result
from fabric.widgets.label import Label
import utils.icons as icons
class CaffeinePlugin(PluginBase):
"""
Plugin for preventing system idle using the inhibit script.
"""
def __init__(self):
super().__init__()
self.display_name = "Caffeine"
self.description = "Prevent system from going idle"
self.inhibit_script = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), "utils", "inhibit.py")
# Predefined durations
self.durations = {
"30m": "30 minutes",
"1h": "1 hour",
"2h": "2 hours",
"4h": "4 hours",
"8h": "8 hours",
"indefinite": "Indefinitely",
"off": "Off"
}
def initialize(self):
"""Initialize the caffeine plugin."""
self.set_triggers(["caffeine", "caffeine "])
def cleanup(self):
"""Cleanup the caffeine plugin."""
pass
def _create_inhibit_action(self, duration: str):
"""Create an inhibit action that properly captures the duration."""
def action():
try:
# Run the script in the background without waiting
subprocess.Popen(
["python3", self.inhibit_script, duration],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True # Run in a new session to prevent hanging
)
except Exception as e:
print(f"Error starting inhibit script: {e}")
return action
def _is_valid_duration(self, query: str) -> bool:
"""Check if the query is a valid duration format."""
if query in self.durations:
return True
if query.isdigit():
return True
if query.endswith(('h', 'm', 's')) and query[:-1].replace('.', '').isdigit():
return True
return False
def _get_default_action(self, query: str):
"""Get the default action for a direct duration input."""
if self._is_valid_duration(query):
return self._create_inhibit_action(query)
return None
def query(self, query_string: str) -> List[Result]:
"""Search caffeine durations based on query."""
if not query_string.strip():
return []
query = query_string.lower().strip()
results = []
# Handle direct search entry (e.g., "caffeine 30m" or just "30m")
if query.startswith("caffeine "):
query = query[9:].strip() # Remove "caffeine " prefix
elif query in self.durations or (query.endswith(('h', 'm', 's')) and query[:-1].replace('.', '').isdigit()):
# If query is a valid duration without prefix, use it directly
pass
else:
return []
# Add custom duration option
if query.isdigit() or (query.endswith(('h', 'm', 's')) and query[:-1].replace('.', '').isdigit()):
result = Result(
title=f"Custom: {query}",
subtitle="Set custom duration",
icon_markup=icons.coffee,
action=self._create_inhibit_action(query),
relevance=1.0,
plugin_name=self.display_name,
data={"duration": query}
)
results.append(result)
# Add predefined durations
for duration, description in self.durations.items():
if query in duration or query in description.lower():
result = Result(
title=description,
subtitle=f"Prevent idle for {description.lower()}",
icon_markup=icons.coffee,
action=self._create_inhibit_action(duration),
relevance=0.9 if query == duration else 0.7,
plugin_name=self.display_name,
data={"duration": duration}
)
results.append(result)
# Set default action for direct duration input
if results:
results[0].default_action = self._get_default_action(query)
return results
+156
View File
@@ -0,0 +1,156 @@
"""
Calculator plugin for the launcher.
Evaluates mathematical expressions and converts units.
"""
import re
import math
import time
import subprocess
from typing import List, Dict, Tuple
from ..plugin_base import PluginBase
from ..result import Result
from utils.conversion import Conversion
import utils.icons as icons
class CalculatorPlugin(PluginBase):
"""
Plugin for calculating mathematical expressions and converting units.
"""
def __init__(self):
super().__init__()
self.display_name = "Calculator"
self.description = "Evaluate mathematical expressions and convert units"
# Safe functions for evaluation
self.safe_functions = {
"abs": abs,
"round": round,
"min": min,
"max": max,
"sum": sum,
"pow": pow,
"sqrt": math.sqrt,
"sin": math.sin,
"cos": math.cos,
"tan": math.tan,
"asin": math.asin,
"acos": math.acos,
"atan": math.atan,
"log": math.log,
"log10": math.log10,
"exp": math.exp,
"pi": math.pi,
"e": math.e,
}
# Initialize conversion utility
self.converter = Conversion()
# Pre-compiled regex patterns
self.expression_pattern = re.compile(r"[\d+\-*/^()=]")
self.number_pattern = re.compile(r"\d")
self.conversion_pattern = re.compile(
r"(\d+(?:\.\d+)?)\s*([a-zA-Z]+)\s*(?:to|in|=)\s*([a-zA-Z]+)"
)
# Cache for conversion results
self._conversion_cache = {}
self._last_cache_cleanup = time.time()
self._cache_cleanup_interval = 300 # 5 minutes
def initialize(self):
"""Initialize the files plugin."""
self.set_triggers(["=", "= "])
def _cleanup_cache(self):
"""Clean up old cache entries."""
current_time = time.time()
if current_time - self._last_cache_cleanup > self._cache_cleanup_interval:
self._conversion_cache.clear()
self._last_cache_cleanup = current_time
def query(self, query: str) -> List[Result]:
"""Process a query and return results."""
if not query:
return []
# Clean up cache periodically
self._cleanup_cache()
# Check if it's a conversion query
conversion_match = self.conversion_pattern.match(query)
if conversion_match:
try:
value, from_unit, to_unit = conversion_match.groups()
value = float(value)
# Check cache first
cache_key = f"{value}_{from_unit}_{to_unit}"
if cache_key in self._conversion_cache:
result = self._conversion_cache[cache_key]
else:
# Use the conversion utility
result = self.converter.convert(value, from_unit, to_unit)
# Cache the result
self._conversion_cache[cache_key] = result
return [
Result(
title=f"{result:.6g} {to_unit}",
subtitle=f"{value} {from_unit} = {result:.6g} {to_unit}",
icon_markup=icons.calculator,
action=lambda r=f"{result:.6g}": self._copy_to_clipboard(r),
relevance=1.0,
plugin_name=self.display_name,
data={"from": (value, from_unit), "to": (result, to_unit)},
)
]
except ValueError as e:
return [
Result(
title="Invalid conversion",
subtitle=str(e),
icon_markup=icons.calculator,
relevance=0.0,
plugin_name=self.display_name,
)
]
# Check if it's a math expression
if self.expression_pattern.search(query):
try:
# Evaluate the expression
result = eval(query, {"__builtins__": {}}, self.safe_functions)
if isinstance(result, (int, float)):
return [
Result(
title=f"{result:.6g}",
subtitle=f"{query} = {result:.6g}",
icon_markup=icons.calculator,
action=lambda r=f"{result:.6g}": self._copy_to_clipboard(r),
relevance=1.0,
plugin_name=self.display_name,
)
]
except Exception:
pass
return []
def _copy_to_clipboard(self, text: str):
"""Copy text to clipboard using cliphist."""
try:
# First copy to clipboard
subprocess.run(["wl-copy"], input=text.encode(), check=True)
# Then store in cliphist
subprocess.run(["cliphist", "store"], input=text.encode(), check=True)
except subprocess.CalledProcessError:
# If cliphist fails, at least we have the text in clipboard
pass
def cleanup(self):
"""Clean up resources."""
self._conversion_cache.clear()
+207
View File
@@ -0,0 +1,207 @@
"""
Clipboard plugin using cliphist for clipboard history management.
"""
import os
import re
import subprocess
import sys
import tempfile
from typing import List, Dict
from ..plugin_base import PluginBase
from ..result import Result
from gi.repository import GdkPixbuf, GLib, Gdk
class ClipboardPlugin(PluginBase):
def __init__(self):
super().__init__()
self.name = "clipboard"
self.display_name = "Clipboard History"
self.description = "Search and manage clipboard history using cliphist"
self.set_triggers(["clip"])
# Initialize cache and temp directory
self.tmp_dir = tempfile.mkdtemp(prefix="cliphist-")
self.image_cache: Dict[str, GdkPixbuf.Pixbuf] = {}
self.clipboard_items = []
self._loading = False
self._pending_updates = False
def initialize(self):
"""Initialize the plugin."""
try:
subprocess.run(["cliphist", "list"], capture_output=True, check=True)
except (subprocess.SubprocessError, FileNotFoundError):
raise RuntimeError("cliphist is not installed or not working properly")
def cleanup(self):
"""Cleanup the plugin."""
try:
if os.path.exists(self.tmp_dir):
import shutil
shutil.rmtree(self.tmp_dir)
self.image_cache.clear()
except Exception as e:
print(f"Error cleaning up temporary files: {e}", file=sys.stderr)
def _load_clipboard_items(self) -> List[str]:
"""Load clipboard items from cliphist."""
try:
result = subprocess.run(
["cliphist", "list"], capture_output=True, check=True
)
stdout_str = result.stdout.decode("utf-8", errors="replace")
lines = stdout_str.strip().split("\n")
return [line for line in lines if line and "<meta http-equiv" not in line]
except subprocess.CalledProcessError as e:
print(f"Error loading clipboard history: {e}", file=sys.stderr)
return []
except Exception as e:
print(f"Unexpected error: {e}", file=sys.stderr)
return []
def _create_pixbuf_from_bytes(
self, image_data: bytes, max_size: int = 100
) -> GdkPixbuf.Pixbuf:
"""Create a GdkPixbuf from image bytes with size limit."""
try:
loader = GdkPixbuf.PixbufLoader()
loader.write(image_data)
loader.close()
pixbuf = loader.get_pixbuf()
# Scale image if needed
width, height = pixbuf.get_width(), pixbuf.get_height()
if width > height:
new_width = max_size
new_height = int(height * (max_size / width))
else:
new_height = max_size
new_width = int(width * (max_size / height))
return pixbuf.scale_simple(
new_width, new_height, GdkPixbuf.InterpType.BILINEAR
)
except GLib.Error:
return None
def _is_image_data(self, content: str) -> bool:
"""Determine if clipboard content is likely an image."""
return "binary" in content.lower() and any(
ext in content.lower() for ext in ["jpg", "jpeg", "png", "bmp", "gif"]
)
def _get_text_preview(self, content: str) -> str:
"""Get a text preview of the content."""
if len(content) > 50:
return content[:37] + "..."
return content
def _load_image_preview_async(self, item_id: str) -> GdkPixbuf.Pixbuf:
"""Load image preview asynchronously."""
if item_id in self.image_cache:
return self.image_cache[item_id]
try:
result = subprocess.run(
["cliphist", "decode", item_id], capture_output=True, check=True
)
pixbuf = self._create_pixbuf_from_bytes(result.stdout)
if pixbuf:
self.image_cache[item_id] = pixbuf
return pixbuf
except Exception as e:
print(f"Error loading image preview: {e}", file=sys.stderr)
return None
def query(self, query_string: str) -> List[Result]:
"""Search clipboard history using cliphist."""
results = []
# Handle query string
if query_string.lower() == "clip":
query_string = "" # Show all items
try:
# Load clipboard items
self.clipboard_items = self._load_clipboard_items()
# Filter items based on query
filtered_items = []
for item in self.clipboard_items:
parts = item.split("\t", 1)
content = parts[1] if len(parts) > 1 else item
if not query_string or query_string.lower() in content.lower():
filtered_items.append(item)
# Process all items without batching
for item in filtered_items:
parts = item.split("\t", 1)
item_id = parts[0] if len(parts) > 1 else "0"
content = parts[1] if len(parts) > 1 else item
# Handle image content
if self._is_image_data(content):
pixbuf = self._load_image_preview_async(item_id)
if pixbuf:
result = Result(
title="Image from clipboard",
subtitle="Click to copy image to clipboard",
description="Image content",
icon=pixbuf,
relevance=1.0,
plugin_name=self.name,
action=lambda id=item_id: self._copy_to_clipboard(id),
data={"bypass_max_results": True}
)
results.append(result)
continue
# Handle text content
display_text = self._get_text_preview(content)
result = Result(
title=display_text,
subtitle="Text from clipboard",
description=content,
icon_name="edit-paste",
relevance=1.0,
plugin_name=self.name,
action=lambda id=item_id: self._copy_to_clipboard(id),
data={"bypass_max_results": True}
)
results.append(result)
except Exception as e:
# Handle errors gracefully
results.append(
Result(
title="Error accessing clipboard history",
subtitle=str(e),
icon_name="dialog-error",
relevance=0.0,
plugin_name=self.name,
data={"bypass_max_results": True}
)
)
return results
def _copy_to_clipboard(self, entry_id: str):
"""Copy entry to clipboard using cliphist."""
try:
result = subprocess.run(
["cliphist", "decode", entry_id], capture_output=True, check=True
)
# Use wl-copy for Wayland or xclip for X11
try:
subprocess.run(["wl-copy"], input=result.stdout, check=True)
except subprocess.SubprocessError:
subprocess.run(
["xclip", "-selection", "clipboard"],
input=result.stdout,
check=True,
)
except subprocess.SubprocessError as e:
print(f"Error copying to clipboard: {e}", file=sys.stderr)
+354
View File
@@ -0,0 +1,354 @@
"""
Files plugin for the launcher.
High-performance file and directory search using advanced fuzzy matching.
"""
import os
import subprocess
import threading
import time
from typing import List, Dict, Set, Tuple
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
from thefuzz import fuzz
from ..plugin_base import PluginBase
from ..result import Result
import utils.icons as icons
class FilesPlugin(PluginBase):
"""
High-performance plugin for searching files and directories.
Uses advanced fuzzy matching, caching, and threading for optimal performance.
"""
def __init__(self):
super().__init__()
self.display_name = "Files"
self.description = "Search for files and directories"
# Performance-optimized search paths
self.search_paths = [
os.path.expanduser("~"),
os.path.expanduser("/"),
]
# Performance settings
self.max_results = 15
self.max_depth = 3
self.search_timeout = 0.8
self.min_query_length = 1
# Fuzzy search settings
self.fuzzy_thresholds = {
"ratio": 60,
"partial": 70,
"token_sort": 65,
"token_set": 65,
}
# Enhanced caching
self.file_cache: Dict[str, List[str]] = {}
self.cache_timestamp: Dict[str, float] = {}
self.cache_ttl = 300
self.cache_lock = threading.Lock()
# Thread pool for concurrent searches
self.executor = ThreadPoolExecutor(
max_workers=4, thread_name_prefix="files-search"
)
def initialize(self):
"""Initialize the files plugin."""
self.set_triggers(
[
"file",
"find",
"/",
"file ",
"find ",
"/ ",
]
)
print("Initializing Files plugin...")
self._warm_cache()
def cleanup(self):
"""Cleanup the files plugin."""
if hasattr(self, "executor"):
self.executor.shutdown(wait=False)
with self.cache_lock:
self.file_cache.clear()
self.cache_timestamp.clear()
def query(self, query_string: str) -> List[Result]:
"""Fast search for files matching the query."""
query = query_string.strip()
if len(query) < self.min_query_length:
return []
# Handle special path queries
if query.startswith("/") or query.startswith("~"):
return self._handle_path_query(query)
# Check if this is a file-only search
is_file_only = query.startswith("file ")
if is_file_only:
query = query[5:].strip()
# Use cached search for better performance
results = self._fast_search(query, file_only=is_file_only)
# Sort by relevance and limit results
results.sort(key=lambda r: r.relevance, reverse=True)
return results[: self.max_results]
def _warm_cache(self):
"""Pre-warm cache for common directories in background."""
def warm_directory(path):
try:
if os.path.exists(path) and os.path.isdir(path):
self._get_cached_files(path)
except:
pass
for path in self.search_paths:
threading.Thread(target=warm_directory, args=(path,), daemon=True).start()
def _handle_path_query(self, query: str) -> List[Result]:
"""Handle path-based queries like '/home' or '~/Documents'."""
try:
expanded_path = (
os.path.expanduser(query) if query.startswith("~") else query
)
if os.path.isdir(expanded_path):
return self._list_directory_contents(expanded_path)
parent_dir = os.path.dirname(expanded_path)
if os.path.isdir(parent_dir):
basename = os.path.basename(expanded_path)
return self._search_in_directory(parent_dir, basename, max_results=10)
except Exception:
pass
return []
def _fast_search(self, query: str, file_only: bool = False) -> List[Result]:
"""Fast search using cached file lists and concurrent processing."""
results = []
query_lower = query.lower()
# Search in cached directories
for search_path in self.search_paths:
if not os.path.exists(search_path):
continue
cached_files = self._get_cached_files(search_path)
for file_path in cached_files:
if file_only and os.path.isdir(file_path):
continue
filename = os.path.basename(file_path)
if self._simple_fuzzy_match(query_lower, filename):
relevance = self._calculate_relevance(filename, query_lower)
result = self._create_file_result(file_path, relevance)
if result:
results.append(result)
if len(results) >= self.max_results * 2:
break
if len(results) >= self.max_results * 2:
break
return results
def _get_cached_files(self, directory: str) -> List[str]:
"""Get cached file list for directory, refresh if needed."""
current_time = time.time()
with self.cache_lock:
if (
directory in self.file_cache
and directory in self.cache_timestamp
and current_time - self.cache_timestamp[directory] < self.cache_ttl
):
return self.file_cache[directory]
files = self._scan_directory_fast(directory)
self.file_cache[directory] = files
self.cache_timestamp[directory] = current_time
return files
def _scan_directory_fast(self, directory: str) -> List[str]:
"""Fast directory scan with improved depth and fuzzy search."""
files = []
current_depth = 0
def scan_dir(path: str, depth: int):
if depth > self.max_depth:
return
try:
with os.scandir(path) as entries:
for entry in entries:
try:
if entry.name.startswith("."):
continue
files.append(entry.path)
if entry.is_dir():
scan_dir(entry.path, depth + 1)
except (PermissionError, OSError):
continue
except (PermissionError, OSError):
pass
scan_dir(directory, current_depth)
return files
def _is_important_directory(self, dirname: str) -> bool:
"""Check if directory is important enough to scan deeper."""
important_dirs = {
"Documents",
"Downloads",
"Desktop",
"Pictures",
"Videos",
"Music",
"Projects",
"Code",
"Development",
"Work",
"src",
"bin",
}
return dirname in important_dirs
def _search_in_directory(
self, directory: str, query: str, max_results: int = 10
) -> List[Result]:
"""Search for files in a specific directory."""
results = []
query_lower = query.lower()
try:
with os.scandir(directory) as entries:
for entry in entries:
if self._simple_fuzzy_match(query_lower, entry.name):
relevance = self._calculate_relevance(entry.name, query_lower)
result = self._create_file_result(entry.path, relevance)
if result:
results.append(result)
if len(results) >= max_results:
break
except (PermissionError, OSError):
pass
return results
def _list_directory_contents(
self, directory: str, max_results: int = 15
) -> List[Result]:
"""List contents of a directory."""
results = []
try:
with os.scandir(directory) as entries:
for entry in entries:
if not entry.name.startswith("."):
result = self._create_file_result(entry.path, 0.8)
if result:
results.append(result)
if len(results) >= max_results:
break
except (PermissionError, OSError):
pass
return results
def _create_file_result(self, file_path: str, relevance: float) -> Result:
"""Create a Result object for a file or directory."""
try:
filename = os.path.basename(file_path)
is_dir = os.path.isdir(file_path)
return Result(
title=filename,
subtitle=file_path,
icon_markup=icons.file,
action=lambda p=file_path: self._open_path(p),
relevance=relevance,
plugin_name=self.display_name,
data={"path": file_path, "type": "directory" if is_dir else "file"},
)
except Exception:
return None
def _open_path(self, path: str):
"""Open a file or directory with the default application."""
try:
subprocess.Popen(
["xdg-open", path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
print(f"Opened: {path}")
except Exception as e:
print(f"Failed to open {path}: {e}")
def _open_file(self, file_path: str):
"""Open a file with the default application."""
self._open_path(file_path)
def _open_directory(self, dir_path: str):
"""Open a directory in the file manager."""
self._open_path(dir_path)
def _simple_fuzzy_match(self, query: str, text: str) -> bool:
"""Advanced fuzzy matching using multiple methods."""
text_lower = text.lower()
query_lower = query.lower()
if query_lower in text_lower:
return True
return (
fuzz.ratio(query_lower, text_lower) >= self.fuzzy_thresholds["ratio"]
or fuzz.partial_ratio(query_lower, text_lower)
>= self.fuzzy_thresholds["partial"]
or fuzz.token_sort_ratio(query_lower, text_lower)
>= self.fuzzy_thresholds["token_sort"]
or fuzz.token_set_ratio(query_lower, text_lower)
>= self.fuzzy_thresholds["token_set"]
)
def _calculate_relevance(self, filename: str, query: str) -> float:
"""Calculate relevance score using multiple fuzzy matching methods."""
filename_lower = filename.lower()
query_lower = query.lower()
ratio = fuzz.ratio(query_lower, filename_lower)
partial = fuzz.partial_ratio(query_lower, filename_lower)
token_sort = fuzz.token_sort_ratio(query_lower, filename_lower)
token_set = fuzz.token_set_ratio(query_lower, filename_lower)
relevance = (
ratio * 0.2 + partial * 0.4 + token_sort * 0.2 + token_set * 0.2
) / 100.0
if query_lower == filename_lower:
relevance = 1.0
elif filename_lower.startswith(query_lower):
relevance = max(relevance, 0.9)
elif query_lower in filename_lower:
relevance = max(relevance, 0.8)
return relevance
+111
View File
@@ -0,0 +1,111 @@
"""
Power management plugin for the launcher.
Handles system power operations like shutdown, restart, sleep, etc.
"""
import subprocess
from typing import List, Dict, Any
import os
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GdkPixbuf, GLib
from ..plugin_base import PluginBase
from ..result import Result
import utils.icons as icons
class PowerPlugin(PluginBase):
"""
Plugin for system power management operations.
"""
def __init__(self):
super().__init__()
self.display_name = "Power"
self.description = "System power management and control"
self.commands = {
"shutdown": {
"description": "Shutdown the system",
"icon": icons.shutdown,
"action": self.shutdown
},
"restart": {
"description": "Restart the system",
"icon": icons.reboot,
"action": self.restart
},
"sleep": {
"description": "Put system to sleep",
"icon": icons.suspend,
"action": self.sleep
},
"lock": {
"description": "Lock the screen",
"icon": icons.lock,
"action": self.lock
},
"suspend": {
"description": "Suspend the system",
"icon": icons.suspend,
"action": self.suspend
},
"logout": {
"description": "Logout from current session",
"icon": icons.logout,
"action": self.logout
}
}
def initialize(self):
"""Initialize the power plugin."""
self.set_triggers(["power", "power "])
def cleanup(self):
"""Cleanup the power plugin."""
pass
def query(self, query_string: str) -> List[Result]:
"""Search power commands based on query."""
if not query_string.strip():
return []
query = query_string.lower().strip()
results = []
for cmd, info in self.commands.items():
if query in cmd.lower() or query in info["description"].lower():
result = Result(
title=cmd.capitalize(),
subtitle=info["description"],
icon_markup=info["icon"],
action=info["action"],
relevance=1.0 if query == cmd else 0.7,
plugin_name=self.display_name,
data={"command": cmd}
)
results.append(result)
return results
def shutdown(self) -> None:
"""Shutdown the system"""
subprocess.run(["shutdown", "now"])
def restart(self) -> None:
"""Restart the system"""
subprocess.run(["shutdown", "-r", "now"])
def sleep(self) -> None:
"""Put system to sleep"""
subprocess.run(["systemctl", "suspend"])
def lock(self) -> None:
"""Lock the screen using hyprlock"""
subprocess.run(["hyprlock"])
def suspend(self) -> None:
"""Suspend the system"""
subprocess.run(["systemctl", "suspend"])
def logout(self) -> None:
"""Logout from current session"""
subprocess.run(["loginctl", "terminate-session", os.environ.get("XDG_SESSION_ID")])
+108
View File
@@ -0,0 +1,108 @@
"""
System plugin for the launcher.
Provides system commands and actions.
"""
import subprocess
import os
import time
from typing import List, Set
from ..plugin_base import PluginBase
from ..result import Result
import utils.icons as icons
class SystemPlugin(PluginBase):
"""
Plugin for system commands and actions.
"""
def __init__(self):
super().__init__()
self.display_name = "System"
self.description = "System commands and actions"
# Cache for system binaries
self._bin_cache = set()
self._last_bin_update = 0
self._bin_update_interval = 300 # 5 minutes
def initialize(self):
"""Initialize the system plugin."""
# Set up triggers for system commands
self.set_triggers(["bin", "bin "])
print("Initializing System plugin...")
self._update_bin_cache()
def cleanup(self):
"""Cleanup the system plugin."""
self._bin_cache.clear()
def _update_bin_cache(self):
"""Update the cache of available system binaries."""
current_time = time.time()
if current_time - self._last_bin_update > self._bin_update_interval:
self._bin_cache.clear()
for path in os.environ["PATH"].split(":"):
if os.path.exists(path):
try:
for file in os.listdir(path):
if os.access(os.path.join(path, file), os.X_OK):
self._bin_cache.add(file)
except (PermissionError, FileNotFoundError):
continue
self._last_bin_update = current_time
def query(self, query_string: str) -> List[Result]:
"""Search for system commands matching the query."""
query = query_string.lower().strip()
if not query:
return []
results = []
# Check system binaries
self._update_bin_cache()
for binary in self._bin_cache:
if query in binary.lower():
relevance = self._calculate_binary_relevance(binary, query)
if relevance > 0:
result = Result(
title=binary,
subtitle=f"Execute {binary}",
icon_markup=icons.terminal,
action=lambda b=binary: self._execute_command([b]),
relevance=relevance,
plugin_name=self.display_name,
data={"command": [binary], "id": binary},
)
results.append(result)
return sorted(results, key=lambda x: x.relevance, reverse=True)
def _calculate_binary_relevance(self, binary: str, query: str) -> float:
"""Calculate relevance score for a binary."""
binary_lower = binary.lower()
# Exact match
if query == binary_lower:
return 1.0
# Starts with query
if binary_lower.startswith(query):
return 0.9
# Contains query
if query in binary_lower:
return 0.7
return 0.0
def _execute_command(self, command: List[str]):
"""Execute a system command."""
try:
subprocess.Popen(command)
print(f"Executed command: {' '.join(command)}")
except Exception as e:
print(f"Failed to execute command {' '.join(command)}: {e}")