Skip to content

Instantly share code, notes, and snippets.

@qianlifeng
Created September 14, 2026 14:19
Show Gist options
  • Select an option

  • Save qianlifeng/b27ea5c3cc3f78d2f526c9b481ad9c24 to your computer and use it in GitHub Desktop.

Select an option

Save qianlifeng/b27ea5c3cc3f78d2f526c9b481ad9c24 to your computer and use it in GitHub Desktop.
Wox.Plugin.Droppy
# {
# "Id": "7c3e9a14-6b2d-4f81-9e5a-1d8c4b0f2a67",
# "Name": "i18n:plugin_name",
# "Author": "qianlifeng",
# "Version": "1.0.0",
# "MinWoxVersion": "2.4.4",
# "Runtime": "PYTHON",
# "Description": "i18n:plugin_description",
# "Icon": "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 48 48\"><rect width=\"48\" height=\"48\" rx=\"12\" fill=\"#F59E0B\"/><path fill=\"#FDE68A\" d=\"M10 20h28v16a6 6 0 0 1-6 6H16a6 6 0 0 1-6-6z\"/><path fill=\"#fff\" d=\"M10 28h8l4 5h4l4-5h8v8a6 6 0 0 1-6 6H16a6 6 0 0 1-6-6z\"/><path fill=\"none\" stroke=\"#B45309\" stroke-width=\"3\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M24 8v16M17 18l7 7 7-7\"/></svg>",
# "TriggerKeywords": ["droppy", "drop"],
# "SupportedOS": ["Windows", "Linux", "Macos"],
# "Commands": [
# { "Command": "clear", "Description": "i18n:cmd_clear" }
# ],
# "Features": [
# { "Name": "querySelection" },
# { "Name": "ignoreAutoScore" }
# ],
# "SettingDefinitions": [
# {
# "Type": "select",
# "Value": {
# "Key": "drop_action",
# "Label": "i18n:setting_drop_action",
# "Tooltip": "i18n:setting_drop_action_tip",
# "DefaultValue": "move",
# "Options": [
# { "Label": "i18n:setting_drop_action_move", "Value": "move" },
# { "Label": "i18n:setting_drop_action_copy", "Value": "copy" }
# ]
# }
# },
# {
# "Type": "textbox",
# "Value": {
# "Key": "box_folder",
# "Label": "i18n:setting_box_folder",
# "Tooltip": "i18n:setting_box_folder_tip",
# "DefaultValue": "",
# "Style": { "Width": 420 }
# },
# "IsPlatformSpecific": true
# }
# ],
# "I18n": {
# "en_US": {
# "plugin_name": "Droppy",
# "plugin_description": "A stash box for files. Drop files in, then drag them out later.",
# "cmd_clear": "Remove every item from the box",
# "setting_drop_action": "Drop into box",
# "setting_drop_action_tip": "What happens when files are dropped onto Droppy",
# "setting_drop_action_move": "Move (default)",
# "setting_drop_action_copy": "Copy",
# "setting_box_folder": "Box folder",
# "setting_box_folder_tip": "Where stashed files are stored. Leave empty to use ~/Droppy.",
# "empty_title": "Droppy is empty",
# "empty_subtitle": "Drop files here. They will be moved into the box.",
# "empty_subtitle_copy": "Drop files here. They will be copied into the box.",
# "item_from": "From {path}",
# "item_added": "Added {time}",
# "status_moved": "Moved {count} item(s) into Droppy",
# "status_copied": "Copied {count} item(s) into Droppy",
# "status_partial": "{ok} added, {failed} failed",
# "status_skipped": "Those files are already in Droppy",
# "status_taken_out": "Removed {count} item(s) from Droppy",
# "action_open": "Open",
# "action_reveal": "Show in folder",
# "action_copy_path": "Copy path",
# "action_restore": "Restore to original location",
# "action_delete": "Delete from box",
# "action_open_box": "Open box folder",
# "action_clear": "Clear box",
# "clear_title": "Clear Droppy",
# "clear_subtitle": "Delete all {count} item(s) from the box",
# "cleared": "Cleared {count} item(s) from Droppy",
# "restored": "Restored {name}",
# "deleted": "Removed {name} from Droppy",
# "open_failed": "Could not open {name}",
# "restore_failed": "Could not restore {name}",
# "delete_failed": "Could not delete {name}",
# "ingest_failed": "Could not add {name}"
# },
# "zh_CN": {
# "plugin_name": "Droppy",
# "plugin_description": "随时打开的文件盒子:拖进去暂存,再到别处拖出去。",
# "cmd_clear": "清空盒子里的全部文件",
# "setting_drop_action": "拖入盒子时",
# "setting_drop_action_tip": "把文件拖到 Droppy 时执行移动还是复制",
# "setting_drop_action_move": "移动(默认)",
# "setting_drop_action_copy": "复制",
# "setting_box_folder": "盒子目录",
# "setting_box_folder_tip": "暂存文件的存放位置。留空则使用 ~/Droppy。",
# "empty_title": "盒子是空的",
# "empty_subtitle": "把文件拖到这里,默认会移动进盒子。",
# "empty_subtitle_copy": "把文件拖到这里,会复制进盒子。",
# "item_from": "来自 {path}",
# "item_added": "加入于 {time}",
# "status_moved": "已将 {count} 个项目移入 Droppy",
# "status_copied": "已将 {count} 个项目复制进 Droppy",
# "status_partial": "成功 {ok} 个,失败 {failed} 个",
# "status_skipped": "这些文件已经在盒子里",
# "status_taken_out": "已从 Droppy 移出 {count} 个项目",
# "action_open": "打开",
# "action_reveal": "在文件夹中显示",
# "action_copy_path": "复制路径",
# "action_restore": "还原到原位置",
# "action_delete": "从盒子中删除",
# "action_open_box": "打开盒子目录",
# "action_clear": "清空盒子",
# "clear_title": "清空 Droppy",
# "clear_subtitle": "删除盒子中的全部 {count} 个项目",
# "cleared": "已从 Droppy 清除 {count} 个项目",
# "restored": "已还原 {name}",
# "deleted": "已从 Droppy 移除 {name}",
# "open_failed": "无法打开 {name}",
# "restore_failed": "无法还原 {name}",
# "delete_failed": "无法删除 {name}",
# "ingest_failed": "无法加入 {name}"
# }
# }
# }
"""
Droppy is a stash box for files.
Open it with `droppy` or `drop`, drag files onto Wox to move them in,
then drag results back out to Explorer, Finder, or another app.
"""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import sys
import threading
import time
from datetime import datetime
from typing import Any
from wox_plugin import (
ActionContext,
Context,
CopyParams,
CopyType,
LogLevel,
PluginInitParams,
Query,
QueryGridLayout,
QueryLayout,
QueryResponse,
QueryType,
RefreshQueryParam,
Result,
ResultAction,
ResultDragData,
DragOutEvent,
DragOutListenOption,
SelectionType,
WoxImage,
WoxImageType,
)
SETTING_DROP_ACTION = "drop_action"
SETTING_BOX_FOLDER = "box_folder"
DROP_ACTION_MOVE = "move"
DROP_ACTION_COPY = "copy"
INDEX_NAME = ".droppy-index.json"
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".ico"}
ACTION_OPEN = WoxImage.new_svg(
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" '
'stroke="var(--wox-theme-icon-color)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">'
'<path d="M14 5h5v5M19 5l-9 9"/><path d="M13 7H6a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2v-7"/></svg>'
)
ACTION_FOLDER = WoxImage.new_svg(
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" '
'stroke="var(--wox-theme-icon-color)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">'
'<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>'
)
ACTION_COPY = WoxImage.new_svg(
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" '
'stroke="var(--wox-theme-icon-color)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">'
'<rect x="8" y="8" width="12" height="12" rx="2"/>'
'<path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg>'
)
ACTION_DELETE = WoxImage.new_svg(
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" '
'stroke="var(--wox-theme-icon-color)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">'
'<path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/></svg>'
)
ACTION_RESTORE = WoxImage.new_svg(
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" '
'stroke="var(--wox-theme-icon-color)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">'
'<path d="M9 14H4V9"/><path d="M4.5 9A8 8 0 1 1 4 14"/></svg>'
)
PLUGIN_ICON = WoxImage.new_svg(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48">'
'<rect width="48" height="48" rx="12" fill="#F59E0B"/>'
'<path fill="#FDE68A" d="M10 20h28v16a6 6 0 0 1-6 6H16a6 6 0 0 1-6-6z"/>'
'<path fill="#fff" d="M10 28h8l4 5h4l4-5h8v8a6 6 0 0 1-6 6H16a6 6 0 0 1-6-6z"/>'
'<path fill="none" stroke="#B45309" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" '
'd="M24 8v16M17 18l7 7 7-7"/></svg>'
)
# Fully transparent so empty-grid placeholders occupy space without looking like files.
TRANSPARENT_ICON = WoxImage.new_svg(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48">'
'<rect width="48" height="48" fill="#000000" opacity="0"/></svg>'
)
# Use the same 5-column cell size as files. Three columns made each empty
# cell one-third of the launcher and pushed the drop icon below the fold.
ITEM_GRID_COLUMNS = 5
EMPTY_GRID_ROWS = 3
EMPTY_GRID_CELLS = ITEM_GRID_COLUMNS * EMPTY_GRID_ROWS
EMPTY_GRID_CENTER = ITEM_GRID_COLUMNS + ITEM_GRID_COLUMNS // 2
GRID_ITEM_PADDING = 16
GRID_ITEM_MARGIN = 8
GRID_ASPECT_RATIO = 1.0
EMPTY_CELL_SCORE_BASE = 1000
_I18N: dict[str, str] = {}
def _t(key: str, **kwargs: object) -> str:
text = _I18N.get(key) or key
if kwargs:
return text.format(**kwargs)
return text
def _is_selection(query: Query) -> bool:
return query.type == QueryType.SELECTION or str(query.type) == QueryType.SELECTION
def _is_file_selection(query: Query) -> bool:
selection = query.selection
if selection is None:
return False
return selection.type == SelectionType.FILE or str(selection.type) == SelectionType.FILE
def _default_box_folder() -> str:
return os.path.join(os.path.expanduser("~"), "Droppy")
def _same_path(left: str, right: str) -> bool:
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(os.path.abspath(right))
def _is_inside(path: str, folder: str) -> bool:
try:
relative = os.path.relpath(os.path.abspath(path), os.path.abspath(folder))
except ValueError:
return False
return relative == "." or not relative.startswith("..")
def _unique_name(folder: str, name: str) -> str:
stem, ext = os.path.splitext(name)
candidate = name
index = 1
while os.path.exists(os.path.join(folder, candidate)):
candidate = f"{stem} ({index}){ext}"
index += 1
return candidate
def _copy_path(source: str, destination: str) -> None:
if os.path.isdir(source) and not os.path.islink(source):
shutil.copytree(source, destination)
return
shutil.copy2(source, destination)
def _copy_complete(source: str, destination: str) -> bool:
if not os.path.exists(destination):
return False
if os.path.isdir(source) and not os.path.islink(source):
return os.path.isdir(destination)
try:
return os.path.getsize(source) == os.path.getsize(destination)
except OSError:
return False
def _move_path(source: str, destination: str) -> None:
try:
os.rename(source, destination)
except OSError:
pass
else:
if os.path.exists(destination):
return
raise OSError(f"rename reported success but destination is missing: {destination}")
_copy_path(source, destination)
if not _copy_complete(source, destination):
raise OSError(f"refusing to delete source; copy is incomplete: {source} -> {destination}")
_remove_path(source)
def _remove_path(path: str) -> None:
if os.path.isdir(path) and not os.path.islink(path):
shutil.rmtree(path)
return
os.remove(path)
def _open_path(path: str) -> None:
if sys.platform == "win32":
os.startfile(path) # type: ignore[attr-defined]
return
if sys.platform == "darwin":
subprocess.Popen(["open", path])
return
subprocess.Popen(["xdg-open", path])
def _reveal_path(path: str) -> None:
if sys.platform == "win32":
subprocess.Popen(["explorer", "/select,", os.path.normpath(path)])
return
if sys.platform == "darwin":
subprocess.Popen(["open", "-R", path])
return
parent = path if os.path.isdir(path) else os.path.dirname(path)
subprocess.Popen(["xdg-open", parent])
def _file_icon(path: str) -> WoxImage:
if os.path.isdir(path):
return PLUGIN_ICON
if os.path.splitext(path)[1].lower() in IMAGE_EXTS:
return WoxImage.new_absolute(path)
return WoxImage(image_type=WoxImageType.FILE_ICON, image_data=path)
def _format_added(timestamp: float) -> str:
return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M")
class DroppyPlugin:
def __init__(self) -> None:
self.api: Any = None
self._lock = threading.Lock()
self._drop_action = DROP_ACTION_MOVE
self._box_folder = ""
async def init(self, ctx: Context, params: PluginInitParams) -> None:
self.api = params.api
await self._load_translations(ctx)
await self._load_settings(ctx)
await self.api.on_setting_changed(ctx, self._on_setting_changed)
try:
await self.api.on_drag_out(ctx, DragOutListenOption(callback=self._on_drag_out))
except Exception as exc:
await self.api.log(ctx, LogLevel.WARNING, f"drag out listen unavailable: {exc}")
os.makedirs(self.box_dir(), exist_ok=True)
async def query(self, ctx: Context, query: Query) -> QueryResponse:
if _is_selection(query) and not (query.trigger_keyword or "").strip():
return QueryResponse(results=[])
if self._should_ingest(query):
await self._ingest(ctx, list(query.selection.file_paths))
if query.command == "clear":
return QueryResponse(results=[self._clear_result(ctx)])
items = self._reconcile()
search = (query.search or "").strip().lower()
if search:
items = [item for item in items if search in item["name"].lower()]
if not items:
return QueryResponse(
results=self._empty_results(ctx),
layout=QueryLayout(grid_layout=self._grid_layout(ITEM_GRID_COLUMNS)),
)
results = [self._item_result(ctx, item, index) for index, item in enumerate(items)]
return QueryResponse(
results=results,
layout=QueryLayout(grid_layout=self._grid_layout(ITEM_GRID_COLUMNS)),
)
async def _load_translations(self, ctx: Context) -> None:
keys = (
"empty_title",
"empty_subtitle",
"empty_subtitle_copy",
"item_from",
"item_added",
"status_moved",
"status_copied",
"status_partial",
"status_skipped",
"status_taken_out",
"action_open",
"action_reveal",
"action_copy_path",
"action_restore",
"action_delete",
"action_open_box",
"action_clear",
"clear_title",
"clear_subtitle",
"cleared",
"restored",
"deleted",
"open_failed",
"restore_failed",
"delete_failed",
"ingest_failed",
)
loaded: dict[str, str] = {}
for key in keys:
loaded[key] = await self.api.get_translation(ctx, key)
global _I18N
_I18N = loaded
async def _load_settings(self, ctx: Context) -> None:
action = (await self.api.get_setting(ctx, SETTING_DROP_ACTION) or "").strip().lower()
self._drop_action = DROP_ACTION_COPY if action == DROP_ACTION_COPY else DROP_ACTION_MOVE
self._box_folder = (await self.api.get_setting(ctx, SETTING_BOX_FOLDER) or "").strip()
async def _on_setting_changed(self, ctx: Context, key: str, value: str) -> None:
if key == SETTING_DROP_ACTION:
self._drop_action = DROP_ACTION_COPY if value.strip().lower() == DROP_ACTION_COPY else DROP_ACTION_MOVE
return
if key == SETTING_BOX_FOLDER:
self._box_folder = value.strip()
os.makedirs(self.box_dir(), exist_ok=True)
async def _on_drag_out(self, ctx: Context, event: DragOutEvent) -> None:
if event.status != "success" or not event.files:
return
removed = self._take_out_paths(list(event.files))
if removed:
await self.api.notify(ctx, _t("status_taken_out", count=removed))
await self.api.refresh_query(ctx, RefreshQueryParam(preserve_selected_index=False))
def _take_out_paths(self, paths: list[str]) -> int:
box_dir = self.box_dir()
removed_names: set[str] = set()
for raw_path in paths:
source = os.path.abspath(os.path.expanduser(raw_path))
if not _is_inside(source, box_dir) or _same_path(source, box_dir):
continue
name = os.path.basename(source.rstrip("\\/"))
if os.path.exists(source):
try:
_remove_path(source)
except OSError:
continue
if os.path.exists(source):
continue
removed_names.add(name)
if not removed_names:
return 0
with self._lock:
remaining = [item for item in self._read_index() if item.get("name") not in removed_names]
self._write_index(remaining)
return len(removed_names)
def box_dir(self) -> str:
folder = self._box_folder or _default_box_folder()
return os.path.abspath(os.path.expanduser(folder))
def _index_path(self) -> str:
return os.path.join(self.box_dir(), INDEX_NAME)
def _should_ingest(self, query: Query) -> bool:
# querySelection also delivers global drops. Only ingest when this query
# already carries Droppy's trigger keyword.
if not _is_selection(query) or not _is_file_selection(query):
return False
if not (query.trigger_keyword or "").strip():
return False
return bool(query.selection.file_paths)
async def _ingest(self, ctx: Context, paths: list[str]) -> None:
box_dir = self.box_dir()
os.makedirs(box_dir, exist_ok=True)
added = 0
failed = 0
skipped = 0
move = self._drop_action == DROP_ACTION_MOVE
with self._lock:
items = self._read_index()
for raw_path in paths:
source = os.path.abspath(os.path.expanduser(raw_path))
if not os.path.exists(source):
skipped += 1
continue
if _is_inside(source, box_dir):
skipped += 1
continue
stored_name = _unique_name(box_dir, os.path.basename(source.rstrip("\\/")))
destination = os.path.join(box_dir, stored_name)
try:
if move:
_move_path(source, destination)
else:
_copy_path(source, destination)
if not _copy_complete(source, destination):
raise OSError("copy is incomplete")
if not os.path.exists(destination):
raise OSError("destination is missing after transfer")
except Exception as exc:
failed += 1
await self.api.log(ctx, LogLevel.ERROR, f"ingest failed: {source} -> {destination}: {exc}")
continue
items.append(
{
"id": f"{int(time.time() * 1000)}-{stored_name}",
"name": stored_name,
"originalPath": source,
"addedAt": time.time(),
"mode": DROP_ACTION_MOVE if move else DROP_ACTION_COPY,
}
)
added += 1
self._write_index(items)
if added == 0 and failed == 0:
await self.api.notify(ctx, _t("status_skipped"))
return
if failed and added:
await self.api.notify(ctx, _t("status_partial", ok=added, failed=failed))
return
if failed:
await self.api.notify(ctx, _t("ingest_failed", name=os.path.basename(paths[0])))
return
key = "status_moved" if move else "status_copied"
await self.api.notify(ctx, _t(key, count=added))
def _reconcile(self) -> list[dict[str, Any]]:
box_dir = self.box_dir()
os.makedirs(box_dir, exist_ok=True)
with self._lock:
items = self._read_index()
by_name = {item["name"]: item for item in items if item.get("name")}
existing_names: set[str] = set()
try:
names = os.listdir(box_dir)
except OSError:
names = []
for name in names:
if name == INDEX_NAME:
continue
path = os.path.join(box_dir, name)
existing_names.add(name)
if name in by_name:
continue
try:
added_at = os.path.getmtime(path)
except OSError:
added_at = time.time()
by_name[name] = {
"id": f"disk-{name}",
"name": name,
"originalPath": "",
"addedAt": added_at,
"mode": "",
}
reconciled = [item for item in by_name.values() if item["name"] in existing_names]
reconciled.sort(key=lambda item: float(item.get("addedAt") or 0), reverse=True)
self._write_index(reconciled)
return reconciled
def _read_index(self) -> list[dict[str, Any]]:
path = self._index_path()
try:
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
except Exception:
return []
if not isinstance(data, list):
return []
return [item for item in data if isinstance(item, dict) and item.get("name")]
def _write_index(self, items: list[dict[str, Any]]) -> None:
path = self._index_path()
temporary = path + ".tmp"
with open(temporary, "w", encoding="utf-8") as handle:
json.dump(items, handle, ensure_ascii=False, indent=2)
os.replace(temporary, path)
def _stored_path(self, item: dict[str, Any]) -> str:
return os.path.join(self.box_dir(), item["name"])
def _grid_layout(self, columns: int) -> QueryGridLayout:
return QueryGridLayout(
columns=columns,
show_title=True,
item_padding=GRID_ITEM_PADDING,
item_margin=GRID_ITEM_MARGIN,
aspect_ratio=GRID_ASPECT_RATIO,
)
def _empty_results(self, ctx: Context) -> list[Result]:
# 5x3 pad: same cell size as files, drop prompt in the middle cell.
return [
self._empty_center_result(ctx, index) if index == EMPTY_GRID_CENTER else self._empty_placeholder(index)
for index in range(EMPTY_GRID_CELLS)
]
def _empty_cell_score(self, index: int) -> int:
return EMPTY_CELL_SCORE_BASE - index
def _empty_center_result(self, ctx: Context, index: int) -> Result:
subtitle_key = "empty_subtitle_copy" if self._drop_action == DROP_ACTION_COPY else "empty_subtitle"
return Result(
id="droppy-empty-center",
title=_t("empty_title"),
sub_title=_t(subtitle_key),
icon=PLUGIN_ICON,
score=self._empty_cell_score(index),
actions=[
ResultAction(
name=_t("action_open_box"),
icon=ACTION_FOLDER,
is_default=True,
action=self._action_open_box,
)
],
)
def _empty_placeholder(self, index: int) -> Result:
return Result(
id=f"droppy-empty-slot-{index}",
title="",
icon=TRANSPARENT_ICON,
score=self._empty_cell_score(index),
)
def _item_result(self, ctx: Context, item: dict[str, Any], index: int) -> Result:
path = self._stored_path(item)
original = (item.get("originalPath") or "").strip()
subtitle = _t("item_added", time=_format_added(float(item.get("addedAt") or time.time())))
if original:
subtitle = _t("item_from", path=original)
actions = [
ResultAction(
name=_t("action_open"),
icon=ACTION_OPEN,
is_default=True,
action=self._action_open_item(path, item["name"]),
),
ResultAction(
name=_t("action_reveal"),
icon=ACTION_FOLDER,
action=self._action_reveal_item(path, item["name"]),
),
ResultAction(
name=_t("action_copy_path"),
icon=ACTION_COPY,
action=self._action_copy_path(path),
),
ResultAction(
name=_t("action_delete"),
icon=ACTION_DELETE,
prevent_hide_after_action=True,
action=self._action_delete_item(item["name"]),
),
]
if original:
actions.insert(
3,
ResultAction(
name=_t("action_restore"),
icon=ACTION_RESTORE,
prevent_hide_after_action=True,
action=self._action_restore_item(item["name"]),
),
)
return Result(
title=item["name"],
sub_title=subtitle,
icon=_file_icon(path),
score=1_000_000 - index,
drag_data=ResultDragData.files_data([path], prevent_hide_after_drag=True),
actions=actions,
)
def _clear_result(self, ctx: Context) -> Result:
count = len(self._reconcile())
return Result(
title=_t("clear_title"),
sub_title=_t("clear_subtitle", count=count),
icon=PLUGIN_ICON,
score=2_000_000,
actions=[
ResultAction(
name=_t("action_clear"),
icon=ACTION_DELETE,
is_default=True,
prevent_hide_after_action=True,
action=self._action_clear,
),
ResultAction(
name=_t("action_open_box"),
icon=ACTION_FOLDER,
action=self._action_open_box,
),
],
)
def _action_open_item(self, path: str, name: str):
async def handle(ctx: Context, _action: ActionContext) -> None:
try:
_open_path(path)
except Exception as exc:
await self.api.log(ctx, LogLevel.ERROR, f"open failed: {path}: {exc}")
await self.api.notify(ctx, _t("open_failed", name=name))
return handle
def _action_reveal_item(self, path: str, name: str):
async def handle(ctx: Context, _action: ActionContext) -> None:
try:
_reveal_path(path)
except Exception as exc:
await self.api.log(ctx, LogLevel.ERROR, f"reveal failed: {path}: {exc}")
await self.api.notify(ctx, _t("open_failed", name=name))
return handle
def _action_copy_path(self, path: str):
async def handle(ctx: Context, _action: ActionContext) -> None:
await self.api.copy(ctx, CopyParams(type=CopyType.TEXT, text=path))
return handle
def _action_delete_item(self, name: str):
async def handle(ctx: Context, _action: ActionContext) -> None:
path = os.path.join(self.box_dir(), name)
try:
if os.path.exists(path):
_remove_path(path)
if os.path.exists(path):
raise OSError("file still exists after delete")
with self._lock:
items = [item for item in self._read_index() if item.get("name") != name]
self._write_index(items)
await self.api.notify(ctx, _t("deleted", name=name))
except Exception as exc:
await self.api.log(ctx, LogLevel.ERROR, f"delete failed: {path}: {exc}")
await self.api.notify(ctx, _t("delete_failed", name=name))
return
await self.api.refresh_query(ctx, RefreshQueryParam(preserve_selected_index=False))
return handle
def _action_restore_item(self, name: str):
async def handle(ctx: Context, _action: ActionContext) -> None:
with self._lock:
items = self._read_index()
item = next((entry for entry in items if entry.get("name") == name), None)
if item is None:
await self.api.notify(ctx, _t("restore_failed", name=name))
return
source = self._stored_path(item)
original = (item.get("originalPath") or "").strip()
if not original:
await self.api.notify(ctx, _t("restore_failed", name=name))
return
destination_dir = os.path.dirname(original)
try:
os.makedirs(destination_dir, exist_ok=True)
destination = original
if os.path.exists(destination):
destination = os.path.join(destination_dir, _unique_name(destination_dir, os.path.basename(original)))
_move_path(source, destination)
if not os.path.exists(destination):
raise OSError("destination is missing after restore")
with self._lock:
remaining = [entry for entry in self._read_index() if entry.get("name") != name]
self._write_index(remaining)
await self.api.notify(ctx, _t("restored", name=name))
except Exception as exc:
await self.api.log(ctx, LogLevel.ERROR, f"restore failed: {source} -> {original}: {exc}")
await self.api.notify(ctx, _t("restore_failed", name=name))
return
await self.api.refresh_query(ctx, RefreshQueryParam(preserve_selected_index=False))
return handle
async def _action_open_box(self, ctx: Context, _action: ActionContext) -> None:
folder = self.box_dir()
os.makedirs(folder, exist_ok=True)
try:
_open_path(folder)
except Exception as exc:
await self.api.log(ctx, LogLevel.ERROR, f"open box failed: {folder}: {exc}")
await self.api.notify(ctx, _t("open_failed", name=folder))
async def _action_clear(self, ctx: Context, _action: ActionContext) -> None:
items = self._reconcile()
failed = 0
remaining: list[dict[str, Any]] = []
with self._lock:
for item in items:
path = self._stored_path(item)
try:
if os.path.exists(path):
_remove_path(path)
if os.path.exists(path):
remaining.append(item)
failed += 1
except Exception as exc:
remaining.append(item)
failed += 1
await self.api.log(ctx, LogLevel.ERROR, f"clear failed: {path}: {exc}")
self._write_index(remaining)
if failed:
await self.api.notify(ctx, _t("status_partial", ok=len(items) - failed, failed=failed))
else:
await self.api.notify(ctx, _t("cleared", count=len(items)))
await self.api.refresh_query(ctx, RefreshQueryParam(preserve_selected_index=False))
plugin = DroppyPlugin()
@qianlifeng

Copy link
Copy Markdown
Author
droppy

@qianlifeng

Copy link
Copy Markdown
Author
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment