feat(spotlight): add plugin system with core engine and examples
- Plugin API (plugin.py, context.py, result.py) - Core engine (search.py, manager.py, registry.py, loader.py) - Built-in plugins: app, calculator, clipboard, emoji, power_menu, query, wallpapers - Spotlight docs and example plugins - Spotlight CSS styling
This commit is contained in:
24 files changed
+3130
-20
No files matched your search
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
Modus Launcher plugins package.
|
||||
|
||||
Built-in plugins are auto-discovered via pkgutil.
|
||||
Each plugin module exposes a PLUGIN variable pointing to its class.
|
||||
"""
|
||||
|
||||
import importlib
|
||||
import pkgutil
|
||||
|
||||
__all__ = []
|
||||
|
||||
for module_info in pkgutil.iter_modules(__path__):
|
||||
module_name = module_info.name
|
||||
if module_name.startswith("_"):
|
||||
continue
|
||||
try:
|
||||
module = importlib.import_module(f"{__name__}.{module_name}")
|
||||
plugin_class = getattr(module, "PLUGIN", None)
|
||||
if plugin_class is not None:
|
||||
globals()[module_name] = plugin_class
|
||||
__all__.append(module_name)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,66 @@
|
||||
from typing import Any
|
||||
|
||||
from fabric.utils import DesktopApp, get_desktop_applications
|
||||
|
||||
from utils.functions import fuzzy_score
|
||||
from window.spotlight.api import SearchResult, SpotlightPlugin
|
||||
|
||||
|
||||
class ApplicationPlugin(SpotlightPlugin):
|
||||
id = "applications"
|
||||
name = "Applications"
|
||||
icon = "system-search-symbolic"
|
||||
keywords: list[str] = []
|
||||
searchable = True
|
||||
priority = 10
|
||||
|
||||
def __init__(self, context):
|
||||
super().__init__(context)
|
||||
self._desktop_apps: list[DesktopApp] = []
|
||||
|
||||
def initialize(self) -> None:
|
||||
self._desktop_apps = get_desktop_applications()
|
||||
|
||||
def cleanup(self) -> None:
|
||||
self._desktop_apps = []
|
||||
|
||||
def search(self, query: str, token: Any) -> list[SearchResult]:
|
||||
if not query:
|
||||
return []
|
||||
|
||||
results: list[SearchResult] = []
|
||||
for app in self._desktop_apps:
|
||||
display_name = getattr(app, "display_name", "") or ""
|
||||
if not display_name:
|
||||
continue
|
||||
|
||||
raw_score = fuzzy_score(query, display_name)
|
||||
if raw_score <= 0:
|
||||
continue
|
||||
|
||||
score = raw_score / 100.0
|
||||
|
||||
results.append(
|
||||
SearchResult(
|
||||
id=getattr(app, "desktop_id", "") or display_name,
|
||||
title=display_name,
|
||||
subtitle=getattr(app, "description", "") or "",
|
||||
icon_name="",
|
||||
score=score,
|
||||
action=lambda a=app: self._launch_app(a),
|
||||
render_type="app",
|
||||
plugin_name=self.name,
|
||||
plugin_id=self.id,
|
||||
metadata={"desktop_app": app},
|
||||
)
|
||||
)
|
||||
|
||||
results.sort(key=lambda r: r.score, reverse=True)
|
||||
return results[:10]
|
||||
|
||||
@staticmethod
|
||||
def _launch_app(app: DesktopApp) -> None:
|
||||
app.launch()
|
||||
|
||||
|
||||
PLUGIN = ApplicationPlugin
|
||||
@@ -0,0 +1,93 @@
|
||||
from typing import Any
|
||||
|
||||
from utils.functions import run_command, spawn_detached
|
||||
from window.spotlight.api import PluginContext, SearchResult, SpotlightPlugin
|
||||
|
||||
|
||||
class CalculatorPlugin(SpotlightPlugin):
|
||||
id = "calculator"
|
||||
name = "calculator"
|
||||
icon = "accessories-calculator-symbolic"
|
||||
keywords = ["calc"]
|
||||
searchable = True
|
||||
priority = 90
|
||||
|
||||
def __init__(self, context: PluginContext) -> None:
|
||||
super().__init__(context)
|
||||
|
||||
def initialize(self) -> None:
|
||||
pass
|
||||
|
||||
def cleanup(self) -> None:
|
||||
pass
|
||||
|
||||
def detect(self, text: str) -> bool:
|
||||
s = text.strip()
|
||||
if not s:
|
||||
return False
|
||||
has_digit = any(c.isdigit() for c in s)
|
||||
has_op = any(c in "+-*/^%()" for c in s)
|
||||
return has_digit and has_op
|
||||
|
||||
def search(self, query: str, token: Any) -> list[SearchResult]:
|
||||
s = query.strip()
|
||||
if not s:
|
||||
return []
|
||||
|
||||
if s.lower().startswith("calc "):
|
||||
s = s[5:].strip()
|
||||
elif s.lower() == "calc":
|
||||
return [
|
||||
SearchResult(
|
||||
id="calc_hint",
|
||||
title="Calculator",
|
||||
subtitle="Type a math expression (e.g. 2+2)",
|
||||
icon_name="accessories-calculator-symbolic",
|
||||
score=100.0,
|
||||
render_type="calc",
|
||||
)
|
||||
]
|
||||
|
||||
if not s:
|
||||
return []
|
||||
|
||||
has_digit = any(c.isdigit() for c in s)
|
||||
has_op = any(c in "+-*/^%()" for c in s)
|
||||
if not (has_digit and has_op):
|
||||
return []
|
||||
|
||||
result = self._run_qalc(s)
|
||||
if not result or not result.strip():
|
||||
return []
|
||||
|
||||
if " = " in result:
|
||||
answer = result.split(" = ")[-1].strip()
|
||||
else:
|
||||
answer = result.strip()
|
||||
|
||||
return [
|
||||
SearchResult(
|
||||
id=f"calc_{s}",
|
||||
title=f"{s} =",
|
||||
subtitle=answer,
|
||||
icon_name="accessories-calculator-symbolic",
|
||||
score=90.0,
|
||||
render_type="calc",
|
||||
action=lambda s=s: self._run_qalc_async(s),
|
||||
metadata={},
|
||||
)
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def _run_qalc(expression: str) -> str:
|
||||
result = run_command(["qalc", "-t", expression], timeout=10)
|
||||
if result.returncode not in [0, -1]:
|
||||
return ""
|
||||
return result.stdout or ""
|
||||
|
||||
@staticmethod
|
||||
def _run_qalc_async(expression: str) -> None:
|
||||
spawn_detached(["qalc", expression])
|
||||
|
||||
|
||||
PLUGIN = CalculatorPlugin
|
||||
@@ -0,0 +1,223 @@
|
||||
import os
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
from fabric.utils import Gio, GLib
|
||||
|
||||
from shared.data import CLIPBOARD_DB_PATH, CLIPBOARD_THUMBS_DIR
|
||||
from utils.functions import copy_image, copy_text, run_command, trigger_paste_shortcut
|
||||
from window.spotlight.api import PluginContext, SearchResult, SpotlightPlugin
|
||||
|
||||
|
||||
class ClipboardPlugin(SpotlightPlugin):
|
||||
id = "clipboard"
|
||||
name = "Clipboard"
|
||||
icon = "edit-paste-symbolic"
|
||||
searchable = True
|
||||
priority = 80
|
||||
|
||||
MAX_RESULTS: int = 30
|
||||
|
||||
def __init__(self, context: PluginContext):
|
||||
super().__init__(context)
|
||||
self._history: list[dict] = []
|
||||
self._history_lock: threading.Lock = threading.Lock()
|
||||
self._cache_dir: str = CLIPBOARD_THUMBS_DIR
|
||||
self._monitor: Gio.FileMonitor | None = None
|
||||
self._db_debounce_id: int = 0
|
||||
|
||||
def initialize(self) -> None:
|
||||
os.makedirs(self._cache_dir, exist_ok=True)
|
||||
self._load_history()
|
||||
self._setup_file_monitor()
|
||||
|
||||
def cleanup(self) -> None:
|
||||
if self._monitor:
|
||||
self._monitor.cancel()
|
||||
self._monitor = None
|
||||
if self._db_debounce_id:
|
||||
GLib.source_remove(self._db_debounce_id)
|
||||
self._db_debounce_id = 0
|
||||
|
||||
def release_memory(self) -> None:
|
||||
with self._history_lock:
|
||||
self._history.clear()
|
||||
|
||||
def search(self, query: str, token: Any) -> list[SearchResult]:
|
||||
q = query.strip()
|
||||
if q.lower().startswith("clip "):
|
||||
q = q[5:].strip()
|
||||
elif q.lower() == "clip":
|
||||
q = ""
|
||||
|
||||
self._ensure_history()
|
||||
return self._build_results(self._filter_entries(q), q)
|
||||
|
||||
def _ensure_history(self) -> None:
|
||||
with self._history_lock:
|
||||
if self._history:
|
||||
return
|
||||
self._load_history()
|
||||
|
||||
def _setup_file_monitor(self) -> None:
|
||||
if not os.path.exists(CLIPBOARD_DB_PATH):
|
||||
return
|
||||
f = Gio.File.new_for_path(CLIPBOARD_DB_PATH)
|
||||
self._monitor = f.monitor_file(Gio.FileMonitorFlags.NONE, None)
|
||||
self._monitor.connect("changed", self._on_db_changed)
|
||||
|
||||
def _on_db_changed(self, _monitor, _file, _other_file, event_type):
|
||||
if event_type not in (
|
||||
Gio.FileMonitorEvent.CHANGES_DONE_HINT,
|
||||
Gio.FileMonitorEvent.CREATED,
|
||||
):
|
||||
return
|
||||
if self._db_debounce_id:
|
||||
GLib.source_remove(self._db_debounce_id)
|
||||
self._db_debounce_id = GLib.timeout_add(300, self._on_debounced_db_change)
|
||||
|
||||
def _on_debounced_db_change(self):
|
||||
self._db_debounce_id = 0
|
||||
self._load_history()
|
||||
|
||||
def _load_history(self) -> None:
|
||||
result = run_command(["cliphist", "list"], timeout=5)
|
||||
raw = result.stdout if isinstance(result.stdout, str) else ""
|
||||
lines = raw.splitlines()
|
||||
new_entries = []
|
||||
for line in lines[:100]:
|
||||
if "\t" not in line:
|
||||
continue
|
||||
identifier, content = line.split("\t", 1)
|
||||
content = content.strip()
|
||||
entry = {
|
||||
"type": "text",
|
||||
"identifier": identifier,
|
||||
"raw": line,
|
||||
"content": content,
|
||||
}
|
||||
if "binary data" in content:
|
||||
entry["type"] = "image"
|
||||
new_entries.append(entry)
|
||||
with self._history_lock:
|
||||
self._history.clear()
|
||||
self._history.extend(new_entries)
|
||||
|
||||
def _filter_entries(self, query: str) -> list[dict]:
|
||||
q = query.strip().lower()
|
||||
with self._history_lock:
|
||||
if not q:
|
||||
return [
|
||||
e
|
||||
for e in self._history
|
||||
if not self._is_toml_data(e.get("content", ""))
|
||||
]
|
||||
return [
|
||||
e
|
||||
for e in self._history
|
||||
if q in e.get("content", "").lower()
|
||||
and not self._is_toml_data(e.get("content", ""))
|
||||
]
|
||||
|
||||
def _build_results(
|
||||
self, entries: list[dict], query: str = ""
|
||||
) -> list[SearchResult]:
|
||||
results: list[SearchResult] = []
|
||||
for entry in entries[: self.MAX_RESULTS]:
|
||||
content = entry["content"]
|
||||
is_image = entry["type"] == "image"
|
||||
render_type = "clipboard_image" if is_image else "clipboard_text"
|
||||
display = content[:50] + "..." if len(content) > 50 else content
|
||||
|
||||
metadata: dict[str, Any] = {
|
||||
"raw": entry["raw"],
|
||||
"identifier": entry["identifier"],
|
||||
"type": entry["type"],
|
||||
"image_path": "",
|
||||
}
|
||||
|
||||
if is_image:
|
||||
image_path = entry.get("path", "")
|
||||
if not image_path or not os.path.exists(image_path):
|
||||
image_path = (
|
||||
self._cache_image(entry["raw"], entry["identifier"]) or ""
|
||||
)
|
||||
if image_path:
|
||||
entry["path"] = image_path
|
||||
if image_path:
|
||||
metadata["image_path"] = image_path
|
||||
|
||||
results.append(
|
||||
SearchResult(
|
||||
id=f"clip_{entry['identifier']}",
|
||||
title="Image" if is_image and not image_path else display,
|
||||
subtitle=content[:80],
|
||||
icon_name="edit-paste-symbolic",
|
||||
score=self._score_entry(entry, query),
|
||||
render_type=render_type,
|
||||
plugin_id=self.id,
|
||||
action=self._make_action(entry),
|
||||
metadata=metadata,
|
||||
)
|
||||
)
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
def _score_entry(entry: dict, query: str) -> float:
|
||||
if not query.strip():
|
||||
return 80.0
|
||||
content_lower = entry["content"].lower()
|
||||
q = query.lower()
|
||||
pos = content_lower.find(q)
|
||||
if pos == -1:
|
||||
return 60.0
|
||||
if pos == 0:
|
||||
return 100.0
|
||||
return max(60.0, 95.0 - pos * 0.5)
|
||||
|
||||
@staticmethod
|
||||
def _cliphist_decode(raw: str) -> bytes | None:
|
||||
result = run_command(["cliphist", "decode"], input=raw.encode(), text=False)
|
||||
return result.stdout if isinstance(result.stdout, (bytes, bytearray)) else None
|
||||
|
||||
def _cache_image(self, raw_data: str, identifier: str) -> str | None:
|
||||
img_path = os.path.join(self._cache_dir, f"{identifier}.png")
|
||||
if os.path.exists(img_path):
|
||||
return img_path
|
||||
decoded = self._cliphist_decode(raw_data)
|
||||
if not decoded:
|
||||
return None
|
||||
with open(img_path, "wb") as f:
|
||||
f.write(decoded)
|
||||
return str(img_path)
|
||||
|
||||
def _make_action(self, entry: dict):
|
||||
def _action():
|
||||
if entry["type"] == "image" and entry.get("path"):
|
||||
copy_image(entry["path"])
|
||||
else:
|
||||
decoded = self._cliphist_decode(entry["raw"])
|
||||
if not decoded:
|
||||
return
|
||||
copy_text(decoded.decode())
|
||||
GLib.timeout_add(5, lambda: (trigger_paste_shortcut(), False)[1])
|
||||
|
||||
return _action
|
||||
|
||||
@staticmethod
|
||||
def _is_toml_data(content: str) -> bool:
|
||||
lines = content.strip().splitlines()
|
||||
if len(lines) < 2:
|
||||
return False
|
||||
bracket_lines = sum(
|
||||
1 for ln in lines if ln.strip().startswith("[") and "]" in ln
|
||||
)
|
||||
equals_lines = sum(
|
||||
1
|
||||
for ln in lines
|
||||
if "=" in ln and ln.strip() and not ln.strip().startswith("[")
|
||||
)
|
||||
return bracket_lines >= 1 and equals_lines >= 2
|
||||
|
||||
|
||||
PLUGIN = ClipboardPlugin
|
||||
@@ -0,0 +1,225 @@
|
||||
import contextlib
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from fabric.utils import GLib, logger
|
||||
|
||||
import shared.data as data
|
||||
from utils.functions import copy_text, read_json_file, trigger_paste_shortcut
|
||||
from window.spotlight.api import PluginContext, SearchResult, SpotlightPlugin
|
||||
|
||||
|
||||
class EmojiPlugin(SpotlightPlugin):
|
||||
id = "emoji"
|
||||
name = "Emoji"
|
||||
icon = "face-smile-symbolic"
|
||||
keywords = ["emoji", "em"]
|
||||
searchable = True
|
||||
priority = 70
|
||||
|
||||
def __init__(self, context: PluginContext):
|
||||
super().__init__(context)
|
||||
self._emoji_data: dict[str, dict[str, Any]] = {}
|
||||
|
||||
def initialize(self) -> None:
|
||||
self._ensure_data()
|
||||
|
||||
def cleanup(self) -> None:
|
||||
self._emoji_data.clear()
|
||||
|
||||
def release_memory(self) -> None:
|
||||
self._emoji_data.clear()
|
||||
|
||||
def _ensure_data(self):
|
||||
if self._emoji_data:
|
||||
return
|
||||
cldr = self._load_cldr_annotations()
|
||||
self._emoji_data = cldr or {}
|
||||
logger.info(f"[Emoji] Loaded {len(self._emoji_data)} emojis")
|
||||
|
||||
def detect(self, text: str) -> bool:
|
||||
s = text.strip()
|
||||
if not s:
|
||||
return False
|
||||
for ch in s:
|
||||
cp = ord(ch)
|
||||
if (
|
||||
0x1F600 <= cp <= 0x1F64F
|
||||
or 0x1F300 <= cp <= 0x1F5FF
|
||||
or 0x1F680 <= cp <= 0x1F6FF
|
||||
or 0x1F1E0 <= cp <= 0x1F1FF
|
||||
or 0x2600 <= cp <= 0x27BF
|
||||
or 0xFE00 <= cp <= 0xFE0F
|
||||
or 0x1F900 <= cp <= 0x1F9FF
|
||||
or cp == 0x200D
|
||||
or cp == 0x20E3
|
||||
or 0xE0020 <= cp <= 0xE007F
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
def search(self, query: str, token: Any) -> list[SearchResult]:
|
||||
q = query.strip()
|
||||
if not q:
|
||||
return []
|
||||
|
||||
for prefix in ("emoji ", "em "):
|
||||
if q.lower().startswith(prefix):
|
||||
q = q[len(prefix) :].strip()
|
||||
break
|
||||
if q.lower() in ("emoji", "em"):
|
||||
q = ""
|
||||
|
||||
if not q:
|
||||
return []
|
||||
|
||||
self._ensure_data()
|
||||
if not self._emoji_data:
|
||||
logger.warning("[Emoji] No emoji data available")
|
||||
return []
|
||||
return self._query_emojis(q)
|
||||
|
||||
def _query_emojis(self, text: str) -> list[SearchResult]:
|
||||
query = text.lower().strip()
|
||||
scored: list[tuple[str, dict, float]] = []
|
||||
|
||||
for emoji_char, info in self._emoji_data.items():
|
||||
relevance = 0.0
|
||||
name = info.get("name", "").lower()
|
||||
keywords = info.get("keywords", [])
|
||||
|
||||
if query == emoji_char:
|
||||
relevance = 1.0
|
||||
elif query == name:
|
||||
relevance = 0.95
|
||||
elif name.startswith(query):
|
||||
relevance = 0.9
|
||||
elif query in name:
|
||||
relevance = 0.8
|
||||
elif any(query == k.lower() for k in keywords):
|
||||
relevance = 0.7
|
||||
elif any(query in k.lower() for k in keywords):
|
||||
relevance = 0.6
|
||||
|
||||
if relevance > 0:
|
||||
scored.append((emoji_char, info, relevance))
|
||||
|
||||
if not scored:
|
||||
return []
|
||||
|
||||
scored.sort(key=lambda x: x[2], reverse=True)
|
||||
|
||||
results: list[SearchResult] = []
|
||||
for emoji_char, info, relevance in scored[:20]:
|
||||
name = info.get("name", "Unknown").replace("_", " ").title()
|
||||
keyword_list = info.get("keywords", [])
|
||||
|
||||
results.append(
|
||||
SearchResult(
|
||||
id=emoji_char,
|
||||
title=emoji_char,
|
||||
subtitle=name,
|
||||
icon_name="",
|
||||
score=relevance * 100,
|
||||
render_type="emoji",
|
||||
action=lambda e=emoji_char: self._copy_to_clipboard(e),
|
||||
plugin_name=self.name,
|
||||
plugin_id=self.id,
|
||||
metadata={
|
||||
"emoji": emoji_char,
|
||||
"name": name,
|
||||
"keywords": keyword_list,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
return results
|
||||
|
||||
def _copy_to_clipboard(self, emoji_char: str) -> None:
|
||||
copy_text(emoji_char)
|
||||
GLib.timeout_add(5, lambda: (trigger_paste_shortcut(), False)[1])
|
||||
|
||||
def handle_external(self, command: str, args: str) -> None:
|
||||
pass
|
||||
|
||||
def _load_cldr_annotations(self) -> dict[str, dict[str, Any]] | None:
|
||||
try:
|
||||
lang = "en"
|
||||
annotations_path = self._get_annotations_path(lang)
|
||||
|
||||
if not annotations_path.exists():
|
||||
url = (
|
||||
"https://raw.githubusercontent.com/unicode-org/cldr-json/main/"
|
||||
f"cldr-json/cldr-annotations-full/annotations/{lang}/annotations.json"
|
||||
)
|
||||
logger.info(f"[Emoji] Downloading CLDR annotations from {url}")
|
||||
if not self._download_annotations(url, annotations_path):
|
||||
logger.error("[Emoji] Failed to download CLDR annotations")
|
||||
return None
|
||||
|
||||
raw = self._read_annotations_file(annotations_path)
|
||||
if raw is None:
|
||||
logger.error("[Emoji] Failed to read annotations file")
|
||||
return None
|
||||
|
||||
result = self._normalize_annotations(raw) or None
|
||||
if result:
|
||||
logger.info(f"[Emoji] Normalized {len(result)} emojis")
|
||||
else:
|
||||
logger.error("[Emoji] Normalization returned empty")
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.error(f"[Emoji] Error loading CLDR annotations: {e}")
|
||||
return None
|
||||
|
||||
def _get_annotations_path(self, lang: str) -> Path:
|
||||
cache_dir = Path(data.CACHE_DIR) / "emoji"
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
return cache_dir / f"annotations_full_{lang}.json"
|
||||
|
||||
def _download_annotations(self, url: str, dest: Path) -> bool:
|
||||
headers = {"User-Agent": "Mozilla/5.0"}
|
||||
try:
|
||||
req = Request(url, headers=headers)
|
||||
with urlopen(req, timeout=10) as response:
|
||||
if response.status == 200:
|
||||
dest.write_bytes(response.read())
|
||||
return True
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.error(f"[Emoji] Download error: {e}")
|
||||
return False
|
||||
|
||||
def _read_annotations_file(self, path: Path) -> dict[str, Any] | None:
|
||||
raw = read_json_file(str(path))
|
||||
if raw:
|
||||
return raw
|
||||
with contextlib.suppress(OSError):
|
||||
path.unlink()
|
||||
return None
|
||||
|
||||
def _normalize_annotations(self, raw: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||||
annotations = (
|
||||
raw.get("annotations", {}).get("annotations", {})
|
||||
if isinstance(raw, dict)
|
||||
else {}
|
||||
)
|
||||
|
||||
if not annotations:
|
||||
return {}
|
||||
|
||||
normalized: dict[str, dict[str, Any]] = {}
|
||||
for emoji_char, info in annotations.items():
|
||||
if not isinstance(info, dict):
|
||||
continue
|
||||
tts_list = info.get("tts", []) or []
|
||||
default_list = info.get("default", []) or []
|
||||
|
||||
title = tts_list[0] if tts_list else ""
|
||||
normalized[emoji_char] = {
|
||||
"name": title,
|
||||
"keywords": default_list,
|
||||
}
|
||||
|
||||
return {k: v for k, v in normalized.items() if v.get("name")}
|
||||
@@ -0,0 +1,138 @@
|
||||
from typing import Any
|
||||
|
||||
from fabric.utils import exec_shell_command_async
|
||||
|
||||
from window.spotlight.api import SearchResult, SpotlightPlugin
|
||||
|
||||
|
||||
class PowerMenuPlugin(SpotlightPlugin):
|
||||
id = "power_menu"
|
||||
name = "Power Menu"
|
||||
icon = "system-shutdown-symbolic"
|
||||
keywords = ["powermenu", "pm"]
|
||||
searchable = True
|
||||
priority = 95
|
||||
|
||||
POWER_OPTIONS = [
|
||||
{
|
||||
"id": "shutdown",
|
||||
"name": "Shutdown",
|
||||
"icon": "system-shutdown",
|
||||
"command": "systemctl poweroff",
|
||||
"description": "Shutdown the system",
|
||||
},
|
||||
{
|
||||
"id": "restart",
|
||||
"name": "Restart",
|
||||
"icon": "system-reboot",
|
||||
"command": "systemctl reboot",
|
||||
"description": "Restart the system",
|
||||
},
|
||||
{
|
||||
"id": "suspend",
|
||||
"name": "Suspend",
|
||||
"icon": "system-suspend",
|
||||
"command": "systemctl suspend",
|
||||
"description": "Suspend the system to RAM",
|
||||
},
|
||||
{
|
||||
"id": "hibernate",
|
||||
"name": "Hibernate",
|
||||
"icon": "system-hibernate",
|
||||
"command": "systemctl hibernate",
|
||||
"description": "Hibernate the system to disk",
|
||||
},
|
||||
{
|
||||
"id": "logout",
|
||||
"name": "Logout",
|
||||
"icon": "system-log-out",
|
||||
"command": "pkill -SIGTERM Hyprland",
|
||||
"description": "Logout from the current session",
|
||||
},
|
||||
{
|
||||
"id": "lock",
|
||||
"name": "Lock Screen",
|
||||
"icon": "system-lock-screen",
|
||||
"command": "hyprlock",
|
||||
"description": "Lock the screen",
|
||||
},
|
||||
]
|
||||
|
||||
def initialize(self) -> None:
|
||||
pass
|
||||
|
||||
def cleanup(self) -> None:
|
||||
pass
|
||||
|
||||
def search(self, query: str, token: Any) -> list[SearchResult]:
|
||||
q = query.lower().strip()
|
||||
if not q:
|
||||
return []
|
||||
|
||||
for prefix in ("powermenu ", "pm "):
|
||||
if q.startswith(prefix):
|
||||
q = q[len(prefix) :].strip()
|
||||
break
|
||||
if q in ("powermenu", "pm"):
|
||||
q = ""
|
||||
|
||||
if not q:
|
||||
return [
|
||||
SearchResult(
|
||||
id=f"power_{option['id']}",
|
||||
title=option["name"],
|
||||
subtitle=option["description"],
|
||||
icon_name=option["icon"],
|
||||
score=100.0 - i,
|
||||
render_type="power",
|
||||
action=lambda cmd=option["command"]: exec_shell_command_async(cmd),
|
||||
metadata={"power_option": option},
|
||||
)
|
||||
for i, option in enumerate(self.POWER_OPTIONS)
|
||||
]
|
||||
|
||||
results: list[SearchResult] = []
|
||||
|
||||
for option in self.POWER_OPTIONS:
|
||||
score = 0.0
|
||||
name = option["name"].lower()
|
||||
desc = option["description"].lower()
|
||||
|
||||
if q == name:
|
||||
score = 100.0
|
||||
elif name.startswith(q):
|
||||
score = 90.0
|
||||
elif len(q) >= 3 and q in name:
|
||||
score = 80.0
|
||||
elif len(q) >= 3 and q in desc:
|
||||
score = 60.0
|
||||
|
||||
if score > 0:
|
||||
results.append(
|
||||
SearchResult(
|
||||
id=f"power_{option['id']}",
|
||||
title=option["name"],
|
||||
subtitle=option["description"],
|
||||
icon_name=option["icon"],
|
||||
score=score,
|
||||
render_type="power",
|
||||
action=lambda cmd=option["command"]: exec_shell_command_async(
|
||||
cmd
|
||||
),
|
||||
metadata={"power_option": option},
|
||||
)
|
||||
)
|
||||
|
||||
results.sort(key=lambda r: r.score, reverse=True)
|
||||
return results
|
||||
|
||||
def handle_external(self, command: str, args: str) -> None:
|
||||
if not args:
|
||||
return
|
||||
for option in self.POWER_OPTIONS:
|
||||
if args.lower() == option["name"].lower():
|
||||
exec_shell_command_async(option["command"])
|
||||
return
|
||||
|
||||
|
||||
PLUGIN = PowerMenuPlugin
|
||||
@@ -0,0 +1,134 @@
|
||||
import urllib.parse
|
||||
from typing import Any
|
||||
|
||||
from utils.functions import spawn_detached
|
||||
from window.spotlight.api import PluginContext, SearchResult, SpotlightPlugin
|
||||
|
||||
|
||||
class QueryPlugin(SpotlightPlugin):
|
||||
id = "query"
|
||||
name = "Query"
|
||||
icon = "system-search-symbolic"
|
||||
keywords = ["gg", "yt", "lk"]
|
||||
keyword_icons = {
|
||||
"gg": "edit-find-symbolic",
|
||||
"yt": "video-x-generic-symbolic",
|
||||
"lk": "insert-link-symbolic",
|
||||
}
|
||||
searchable = False
|
||||
priority = 100
|
||||
|
||||
def __init__(self, context: PluginContext):
|
||||
super().__init__(context)
|
||||
|
||||
def initialize(self) -> None:
|
||||
pass
|
||||
|
||||
def cleanup(self) -> None:
|
||||
pass
|
||||
|
||||
def release_memory(self) -> None:
|
||||
pass
|
||||
|
||||
def search(self, query: str, token: Any) -> list[SearchResult]:
|
||||
q = query.strip()
|
||||
if not q:
|
||||
return []
|
||||
|
||||
bare = q.lower()
|
||||
if bare in ("gg", "yt", "lk"):
|
||||
hints = {
|
||||
"gg": ("Google Search", "Type 'gg <query>' to search"),
|
||||
"yt": ("YouTube Search", "Type 'yt <query>' to search"),
|
||||
"lk": ("Open Link", "Type 'lk <url>' to open"),
|
||||
}
|
||||
title, subtitle = hints[bare]
|
||||
return [
|
||||
SearchResult(
|
||||
id=f"query_{bare}_hint",
|
||||
title=title,
|
||||
subtitle=subtitle,
|
||||
icon_name=self.keyword_icons.get(bare, self.icon),
|
||||
score=100.0,
|
||||
render_type="default",
|
||||
)
|
||||
]
|
||||
|
||||
if q.lower().startswith("gg "):
|
||||
search_q = q[3:].strip()
|
||||
if not search_q:
|
||||
return []
|
||||
return [
|
||||
SearchResult(
|
||||
id="query_gg",
|
||||
title=f"Google: {search_q}",
|
||||
subtitle="Open in browser",
|
||||
icon_name="system-search-symbolic",
|
||||
score=100.0,
|
||||
render_type="default",
|
||||
action=lambda: self._google_search(search_q),
|
||||
)
|
||||
]
|
||||
if q.lower().startswith("yt "):
|
||||
search_q = q[3:].strip()
|
||||
if not search_q:
|
||||
return []
|
||||
return [
|
||||
SearchResult(
|
||||
id="query_yt",
|
||||
title=f"YouTube: {search_q}",
|
||||
subtitle="Open in browser",
|
||||
icon_name="system-search-symbolic",
|
||||
score=100.0,
|
||||
render_type="default",
|
||||
action=lambda: self._youtube_search(search_q),
|
||||
)
|
||||
]
|
||||
if q.lower().startswith("lk "):
|
||||
link = q[3:].strip()
|
||||
if not link:
|
||||
return []
|
||||
if not link.startswith("http"):
|
||||
link = "https://" + link
|
||||
return [
|
||||
SearchResult(
|
||||
id="query_lk",
|
||||
title=f"Open: {link}",
|
||||
subtitle="Open in browser",
|
||||
icon_name="system-search-symbolic",
|
||||
score=100.0,
|
||||
render_type="default",
|
||||
action=lambda: self._link_open(link),
|
||||
)
|
||||
]
|
||||
return []
|
||||
|
||||
def on_submit(self, query: str) -> None:
|
||||
q = query.strip()
|
||||
if q.startswith("gg "):
|
||||
self._google_search(q[3:].strip())
|
||||
elif q.startswith("yt "):
|
||||
self._youtube_search(q[3:].strip())
|
||||
elif q.startswith("lk "):
|
||||
self._link_open(q.split(" ", 1)[1].strip())
|
||||
|
||||
def _google_search(self, query: str) -> None:
|
||||
url = f"https://www.google.com/search?q={urllib.parse.quote(query)}"
|
||||
spawn_detached(["xdg-open", url])
|
||||
|
||||
def _youtube_search(self, query: str) -> None:
|
||||
url = (
|
||||
f"https://www.youtube.com/results?search_query={urllib.parse.quote(query)}"
|
||||
)
|
||||
spawn_detached(["xdg-open", url])
|
||||
|
||||
def _link_open(self, link: str) -> None:
|
||||
if not link.startswith(("http://", "https://")):
|
||||
link = "https://" + link
|
||||
spawn_detached(["xdg-open", link])
|
||||
|
||||
def handle_external(self, command: str, args: str) -> None:
|
||||
pass
|
||||
|
||||
|
||||
PLUGIN = QueryPlugin
|
||||
@@ -0,0 +1,118 @@
|
||||
import gc
|
||||
import os
|
||||
import random
|
||||
from typing import Any
|
||||
|
||||
from services.wallpaper import WallpaperService, create_thumbnail
|
||||
from shared.data import WALLPAPERS_THUMBNAILS_SIZE
|
||||
from utils.functions import fuzzy_filter
|
||||
from window.spotlight.api import SearchResult, SpotlightPlugin
|
||||
|
||||
MAX_THUMBS_PER_SEARCH = 5
|
||||
|
||||
|
||||
class WallpaperPlugin(SpotlightPlugin):
|
||||
id = "wallpaper"
|
||||
name = "Wallpaper"
|
||||
icon = "wallpaper"
|
||||
keywords = ["wall", "wr"]
|
||||
searchable = True
|
||||
priority = 85
|
||||
|
||||
def __init__(self, context):
|
||||
super().__init__(context)
|
||||
self._wallpaper_service: WallpaperService | None = None
|
||||
|
||||
def initialize(self) -> None:
|
||||
self._wallpaper_service = WallpaperService()
|
||||
|
||||
def cleanup(self) -> None:
|
||||
self._wallpaper_service = None
|
||||
gc.collect()
|
||||
|
||||
def release_memory(self) -> None:
|
||||
if self._wallpaper_service:
|
||||
self._wallpaper_service.invalidate_cache()
|
||||
|
||||
def search(self, query: str, token: Any) -> list[SearchResult]:
|
||||
service = self._wallpaper_service
|
||||
if not service:
|
||||
return []
|
||||
|
||||
q = query.strip()
|
||||
for prefix in ("wall ", "wr "):
|
||||
if q.lower().startswith(prefix):
|
||||
q = q[len(prefix) :].strip()
|
||||
break
|
||||
if q.lower() in ("wall", "wr"):
|
||||
q = ""
|
||||
|
||||
all_files = service.get_all_wallpapers()
|
||||
if not all_files:
|
||||
return []
|
||||
|
||||
if q:
|
||||
filtered = fuzzy_filter(q, all_files, key=os.path.basename, limit=50)
|
||||
else:
|
||||
filtered = all_files[:50]
|
||||
|
||||
results: list[SearchResult] = []
|
||||
thumbs_created = 0
|
||||
|
||||
for image_path in filtered:
|
||||
if token.is_cancelled or not self._wallpaper_service:
|
||||
return []
|
||||
|
||||
thumbnail_path = service.get_thumbnail_path(image_path)
|
||||
|
||||
if not service.has_thumbnail(image_path):
|
||||
if thumbs_created >= MAX_THUMBS_PER_SEARCH:
|
||||
continue
|
||||
try:
|
||||
create_thumbnail(
|
||||
image_path, thumbnail_path, WALLPAPERS_THUMBNAILS_SIZE
|
||||
)
|
||||
thumbs_created += 1
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
filename = os.path.basename(image_path)
|
||||
results.append(
|
||||
SearchResult(
|
||||
id=f"wall_{filename}",
|
||||
title=filename,
|
||||
subtitle=image_path,
|
||||
icon_name="",
|
||||
score=80.0,
|
||||
render_type="wallpaper",
|
||||
action=lambda p=image_path: self._set_wallpaper(p),
|
||||
metadata={
|
||||
"image_path": image_path,
|
||||
"thumbnail_path": thumbnail_path,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
return results
|
||||
|
||||
def _set_wallpaper(self, path: str) -> None:
|
||||
service = self._wallpaper_service
|
||||
if service:
|
||||
service.set_wallpaper(path)
|
||||
service.invalidate_cache()
|
||||
|
||||
def apply_random_wallpaper(self) -> None:
|
||||
service = self._wallpaper_service
|
||||
if not service:
|
||||
return
|
||||
service.invalidate_cache()
|
||||
files = service.get_all_wallpapers()
|
||||
if files:
|
||||
service.set_wallpaper(random.choice(files))
|
||||
|
||||
def handle_external(self, command: str, args: str) -> None:
|
||||
if command == "wr":
|
||||
self.apply_random_wallpaper()
|
||||
|
||||
|
||||
PLUGIN = WallpaperPlugin
|
||||
Reference in new issue
Block a user