diff --git a/integrations/flow-launcher/Images/app.png b/integrations/flow-launcher/Images/app.png new file mode 100644 index 00000000..815a3b06 Binary files /dev/null and b/integrations/flow-launcher/Images/app.png differ diff --git a/integrations/flow-launcher/README.md b/integrations/flow-launcher/README.md new file mode 100644 index 00000000..f9dbe2eb --- /dev/null +++ b/integrations/flow-launcher/README.md @@ -0,0 +1,23 @@ +# Flow Launcher Plugin for WindowTabs + +Control [WindowTabs](https://windowtabs.app) directly from Flow Launcher: restore saved workspaces and run any WindowTabs command without leaving your keyboard. + +## Usage + +- `wt` — List saved workspaces and common commands. +- `wt ` — Search workspaces and WindowTabs commands by name or id. +- `wt ws ` — Filter workspaces only. +- `wt cmd [choice]` — Run a command with an optional choice (for example `wt cmd tab-color Blue`). + +The plugin talks directly to a running WindowTabs instance over its local named pipe (`BemoSoftware.WindowTabs.`) and falls back to `WindowTabs.exe` CLI when WindowTabs is not running. + +## Local testing on Windows + +1. Copy this folder to `%APPDATA%\FlowLauncher\Plugins\Flow.Launcher.Plugin.WindowTabs-1.0.0\`. +2. Restart Flow Launcher (or run `Restart Flow Launcher` from Flow Launcher). +3. Type `wt` to test. + +## Publishing to the Flow Launcher Plugin Store + +1. Host this folder in a dedicated GitHub repository (for example `leafOfTree/Flow.Launcher.Plugin.WindowTabs`) and attach a release `.zip` containing `plugin.json`, `main.py`, `wt_client.py`, `SettingsTemplate.yaml`, and `Images\app.png`. +2. Open a Pull Request to [Flow-Launcher/Flow.Launcher.PluginsManifest](https://github.com/Flow-Launcher/Flow.Launcher.PluginsManifest) adding `plugins/WindowTabs-8F3A4B6C9D124E8BA7C32D5E6F1A9B04.json`. diff --git a/integrations/flow-launcher/SettingsTemplate.yaml b/integrations/flow-launcher/SettingsTemplate.yaml new file mode 100644 index 00000000..ab1f8cf9 --- /dev/null +++ b/integrations/flow-launcher/SettingsTemplate.yaml @@ -0,0 +1,13 @@ +body: + - type: input + attributes: + name: executable_path + label: WindowTabs.exe path (optional) + description: Leave blank to auto-detect from PATH, startup entry, or default folders. + defaultValue: "" + - type: input + attributes: + name: command_delay_ms + label: Focus delay before running commands (ms) + description: Brief pause after Flow Launcher hides so commands act on your previous window. + defaultValue: "120" diff --git a/integrations/flow-launcher/main.py b/integrations/flow-launcher/main.py new file mode 100644 index 00000000..05777e73 --- /dev/null +++ b/integrations/flow-launcher/main.py @@ -0,0 +1,204 @@ +import json +import os +import sys +import webbrowser + +import wt_client + +ICON = "Images\\app.png" +WEBSITE = "https://windowtabs.app" +PINNED_COMMANDS = [ + "command-palette", + "search-tabs", + "edit-groups", + "split-next", + "save-workspace", + "settings", +] + + +def _load_settings(request: dict) -> dict: + path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "settings.json") + try: + with open(path, "r", encoding="utf-8") as f: + local = json.load(f) + except (OSError, json.JSONDecodeError): + local = {} + supplied = request.get("settings") + return { + **(local if isinstance(local, dict) else {}), + **(supplied if isinstance(supplied, dict) else {}), + } + + +def _find_executable(settings: dict) -> str | None: + configured = settings.get("executable_path") + return wt_client.find_executable(configured if isinstance(configured, str) else "") + + +def _command_delay(settings: dict) -> int: + try: + return max(0, int(settings.get("command_delay_ms", 120))) + except (TypeError, ValueError, OverflowError): + return 120 + + +def _score(query: str, text: str) -> int: + q = query.lower() + t = text.lower() + if t == q: + return 100 + if t.startswith(q): + return 80 + if q in t: + return 60 + words = q.split() + if words and all(w in t for w in words): + return 45 + return 0 + + +def _workspace_item(name: str, score: int = 70) -> dict: + return { + "Title": name, + "SubTitle": f"Restore workspace: {name}", + "IcoPath": ICON, + "Score": score, + "JsonRPCAction": { + "method": "restore_workspace", + "parameters": [name], + }, + } + + +def _command_item(cmd_id: str, caption: str, choice: str = "", score: int = 50) -> dict: + title = f"{caption} ({choice})" if choice else caption + subtitle = f"WindowTabs command: --command {cmd_id}" + (f" {choice}" if choice else "") + return { + "Title": title, + "SubTitle": subtitle, + "IcoPath": ICON, + "Score": score, + "JsonRPCAction": { + "method": "run_command", + "parameters": [cmd_id, choice], + }, + } + + +def _download_item() -> dict: + return { + "Title": "WindowTabs not found — Download from windowtabs.app", + "SubTitle": "Open https://windowtabs.app or set WindowTabs.exe path in plugin settings", + "IcoPath": ICON, + "Score": 100, + "JsonRPCAction": { + "method": "open_url", + "parameters": [WEBSITE], + }, + } + + +def handle_query(raw_query: str, exe: str | None) -> list[dict]: + workspaces = wt_client.list_workspaces(exe) + commands = wt_client.list_commands(exe) + + if not workspaces and not commands: + if exe: + return [ + { + "Title": "Start WindowTabs", + "SubTitle": exe, + "IcoPath": ICON, + "Score": 100, + "JsonRPCAction": {"method": "launch_app", "parameters": [exe]}, + } + ] + return [_download_item()] + + query = raw_query.strip() + results: list[dict] = [] + + # Prefix: "ws " lists workspaces only. + if query.lower().startswith("ws ") or query.lower() == "ws": + sub = query[2:].strip() + for ws in workspaces: + s = 80 if not sub else _score(sub, ws) + if s > 0: + results.append(_workspace_item(ws, s)) + return results + + # Prefix: "cmd [choice]" passes an explicit command and optional choice. + if query.lower().startswith("cmd "): + rest = query[4:].strip().split(None, 1) + if rest: + wanted = rest[0] + choice = rest[1].strip() if len(rest) > 1 else "" + for cmd_id, caption in commands: + s = _score(wanted, cmd_id) + if s > 0: + results.append(_command_item(cmd_id, caption, choice, s)) + return results + + # Empty query: show workspaces first, then frequently used commands. + if not query: + for ws in workspaces: + results.append(_workspace_item(ws, 90)) + by_id = {cmd_id: caption for cmd_id, caption in commands} + for cmd_id in PINNED_COMMANDS: + if cmd_id in by_id: + results.append(_command_item(cmd_id, by_id[cmd_id], score=60)) + if not results: + for cmd_id, caption in commands[:10]: + results.append(_command_item(cmd_id, caption, score=50)) + return results + + # General query: search both workspaces and commands. + for ws in workspaces: + s = _score(query, ws) + if s > 0: + results.append(_workspace_item(ws, s + 15)) + for cmd_id, caption in commands: + s = max(_score(query, caption), _score(query, cmd_id)) + if s > 0: + results.append(_command_item(cmd_id, caption, score=s)) + results.sort(key=lambda item: item.get("Score", 0), reverse=True) + return results[:25] + + +def main() -> None: + request = json.loads(sys.argv[1]) if len(sys.argv) > 1 else {} + method = request.get("method", "query") + params = request.get("parameters", []) + if method == "query": + settings = _load_settings(request) + exe = _find_executable(settings) + delay_ms = _command_delay(settings) + results = handle_query(params[0] if params else "", exe) + # Flow supplies settings to queries, but forwards result actions as returned. + for result in results: + action = result["JsonRPCAction"] + if action["method"] == "restore_workspace": + action["parameters"].append(exe or "") + elif action["method"] == "run_command": + action["parameters"].extend([exe or "", delay_ms]) + print(json.dumps({"result": results})) + elif method == "restore_workspace" and params: + exe = (params[1] or None) if len(params) > 1 else _find_executable(_load_settings(request)) + wt_client.restore_workspace(exe, params[0]) + elif method == "run_command" and params: + choice = params[1] if len(params) > 1 else "" + if len(params) > 3: + exe, delay_ms = params[2] or None, params[3] + else: + settings = _load_settings(request) + exe, delay_ms = _find_executable(settings), _command_delay(settings) + wt_client.run_command(exe, params[0], choice, delay_ms) + elif method == "launch_app" and params: + wt_client.launch_app(params[0]) + elif method == "open_url" and params: + webbrowser.open(params[0]) + + +if __name__ == "__main__": + main() diff --git a/integrations/flow-launcher/plugin.json b/integrations/flow-launcher/plugin.json new file mode 100644 index 00000000..c73cd670 --- /dev/null +++ b/integrations/flow-launcher/plugin.json @@ -0,0 +1,12 @@ +{ + "ID": "8F3A4B6C9D124E8BA7C32D5E6F1A9B04", + "ActionKeyword": "wt", + "Name": "WindowTabs", + "Description": "Switch workspaces and run WindowTabs commands", + "Author": "leafOfTree", + "Version": "1.0.0", + "Language": "python", + "Website": "https://windowtabs.app", + "IcoPath": "Images\\app.png", + "ExecuteFileName": "main.py" +} diff --git a/integrations/flow-launcher/tests/test_flow_settings.py b/integrations/flow-launcher/tests/test_flow_settings.py new file mode 100644 index 00000000..73586945 --- /dev/null +++ b/integrations/flow-launcher/tests/test_flow_settings.py @@ -0,0 +1,89 @@ +import contextlib +import io +import json +import pathlib +import sys +import tempfile +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +import main as flow + + +class FlowSettingsTests(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.directory = pathlib.Path(directory.name) + module_path = patch.object(flow, "__file__", str(self.directory / "main.py")) + module_path.start() + self.addCleanup(module_path.stop) + + def invoke(self, request): + output = io.StringIO() + with patch.object(sys, "argv", ["main.py", json.dumps(request)]): + with contextlib.redirect_stdout(output): + flow.main() + return json.loads(output.getvalue()) if output.getvalue() else None + + def test_flow_settings_survive_separate_result_actions(self): + exe = r"C:\Portable Apps\WindowTabs.exe" + (self.directory / "settings.json").write_text( + json.dumps({"executable_path": "old.exe", "command_delay_ms": 50}), + encoding="utf-8", + ) + with ( + patch.object(flow.wt_client, "find_executable", return_value=exe) as find, + patch.object(flow.wt_client, "list_workspaces", return_value=["项目 A"]) as workspaces, + patch.object(flow.wt_client, "list_commands", return_value=[("next-tab", "Next tab")]) as commands, + patch.object(flow.wt_client, "restore_workspace") as restore, + patch.object(flow.wt_client, "run_command") as run, + ): + result = self.invoke({ + "method": "query", + "parameters": ["a"], + "settings": {"executable_path": exe, "command_delay_ms": "350"}, + })["result"] + actions = {row["JsonRPCAction"]["method"]: row["JsonRPCAction"] for row in result} + self.assertEqual(actions["restore_workspace"]["parameters"], ["项目 A", exe]) + self.invoke(actions["restore_workspace"]) + self.invoke(actions["run_command"]) + find.assert_called_once_with(exe) + workspaces.assert_called_once_with(exe) + commands.assert_called_once_with(exe) + restore.assert_called_once_with(exe, "项目 A") + run.assert_called_once_with(exe, "next-tab", "", 350) + + def test_legacy_action_keeps_local_settings(self): + (self.directory / "settings.json").write_text( + json.dumps({"executable_path": "local.exe", "command_delay_ms": 0}), + encoding="utf-8", + ) + with ( + patch.object(flow.wt_client, "find_executable", return_value="local.exe") as find, + patch.object(flow.wt_client, "run_command") as run, + ): + self.invoke({"method": "run_command", "parameters": ["next-tab", ""]}) + find.assert_called_once_with("local.exe") + run.assert_called_once_with("local.exe", "next-tab", "", 0) + + def test_invalid_flow_delay_uses_default(self): + with ( + patch.object(flow.wt_client, "find_executable", return_value=None) as find, + patch.object(flow.wt_client, "list_workspaces", return_value=[]), + patch.object(flow.wt_client, "list_commands", return_value=[("next-tab", "Next tab")]), + patch.object(flow.wt_client, "run_command") as run, + ): + result = self.invoke({ + "method": "query", + "parameters": ["cmd next-tab"], + "settings": {"executable_path": None, "command_delay_ms": "invalid"}, + })["result"] + self.invoke(result[0]["JsonRPCAction"]) + find.assert_called_once_with("") + run.assert_called_once_with(None, "next-tab", "", 120) + + +if __name__ == "__main__": + unittest.main() diff --git a/integrations/flow-launcher/tests/test_wt_client.py b/integrations/flow-launcher/tests/test_wt_client.py new file mode 100644 index 00000000..fa14ed40 --- /dev/null +++ b/integrations/flow-launcher/tests/test_wt_client.py @@ -0,0 +1,49 @@ +import ctypes +import pathlib +import subprocess +import sys +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +import wt_client as wt + + +class ClientTests(unittest.TestCase): + @unittest.skipUnless(sys.platform == "win32", "Win32 ABI") + def test_handle_types(self): + from ctypes import wintypes as W + k = wt._kernel32() + self.assertIs(k.CreateFileW.restype, W.HANDLE) + for fn in (k.ReadFile, k.WriteFile, k.CloseHandle): + self.assertIs(fn.argtypes[0], W.HANDLE) + self.assertEqual(wt.INVALID_HANDLE_VALUE, ctypes.c_void_p(-1).value) + + def test_listing(self): + names = ["项目 A", "仕事用", "업무 공간", "مشروع", "Cafe\u0301", " 🚀 "] + for reply in [(True, "\n".join(names)), (True, ""), (False, "error")]: + with patch.object(wt, "send_pipe", return_value=reply), patch.object(wt, "_run_cli") as cli: + self.assertEqual(wt.list_workspaces("wt.exe"), names if reply[0] and reply[1] else []) + cli.assert_not_called() + with patch.object(wt, "send_pipe", return_value=None), patch.object(wt, "_run_cli", return_value="\r\n".join(names)) as cli: + self.assertEqual(wt.list_workspaces("wt.exe"), names) + cli.assert_called_once_with("wt.exe", ["--workspaces"]) + + def test_cli_failure(self): + with patch.object(wt, "send_pipe", return_value=None), patch.object(wt, "_run_cli", side_effect=subprocess.CalledProcessError(1, "wt")): + self.assertEqual(wt.list_workspaces("wt.exe"), []) + + def test_no_replay(self): + with patch.object(wt, "send_pipe", return_value=(False, "reply lost")), patch.object(wt.subprocess, "Popen") as spawn: + wt.restore_workspace("wt.exe", "项目 🚀") + wt.run_command("wt.exe", "next-tab", delay_ms=0) + spawn.assert_not_called() + + def test_missing_pipe_restore(self): + with patch.object(wt, "send_pipe", return_value=None), patch.object(wt.subprocess, "Popen") as spawn: + wt.restore_workspace("wt.exe", "项目 🚀") + self.assertEqual(spawn.call_args.args[0], ["wt.exe", "--workspace", "项目 🚀"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/integrations/flow-launcher/wt_client.py b/integrations/flow-launcher/wt_client.py new file mode 100644 index 00000000..a6c3ab39 --- /dev/null +++ b/integrations/flow-launcher/wt_client.py @@ -0,0 +1,213 @@ +import ctypes +from ctypes import wintypes as W +import os +import shutil +import subprocess +import sys +import time + +CREATE_NO_WINDOW = 0x08000000 +GENERIC_READ = 0x80000000 +GENERIC_WRITE = 0x40000000 +OPEN_EXISTING = 3 +INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value + + +def _kernel32(): + k = ctypes.WinDLL("kernel32", use_last_error=True) + k.ProcessIdToSessionId.argtypes = [W.DWORD, ctypes.POINTER(W.DWORD)] + k.ProcessIdToSessionId.restype = W.BOOL + k.WaitNamedPipeW.argtypes = [W.LPCWSTR, W.DWORD] + k.WaitNamedPipeW.restype = W.BOOL + k.CreateFileW.argtypes = [W.LPCWSTR, W.DWORD, W.DWORD, W.LPVOID, W.DWORD, W.DWORD, W.HANDLE] + k.CreateFileW.restype = W.HANDLE + k.WriteFile.argtypes = [W.HANDLE, W.LPCVOID, W.DWORD, ctypes.POINTER(W.DWORD), W.LPVOID] + k.WriteFile.restype = W.BOOL + k.ReadFile.argtypes = [W.HANDLE, W.LPVOID, W.DWORD, ctypes.POINTER(W.DWORD), W.LPVOID] + k.ReadFile.restype = W.BOOL + k.CloseHandle.argtypes = [W.HANDLE] + k.CloseHandle.restype = W.BOOL + return k + + +def _session_id() -> int: + if sys.platform != "win32": + return 0 + kernel32 = _kernel32() + sid = W.DWORD(0) + if kernel32.ProcessIdToSessionId(os.getpid(), ctypes.byref(sid)): + return sid.value + return 0 + + +def pipe_name() -> str: + return rf"\\.\pipe\BemoSoftware.WindowTabs.{_session_id()}" + + +def send_pipe(args: list[str], timeout_ms: int = 1500) -> tuple[bool, str] | None: + """Send CLI args to a running WindowTabs instance over its named pipe.""" + if sys.platform != "win32": + return None + kernel32 = _kernel32() + name = pipe_name() + if not kernel32.WaitNamedPipeW(name, timeout_ms): + return None + handle = kernel32.CreateFileW( + name, + GENERIC_READ | GENERIC_WRITE, + 0, + None, + OPEN_EXISTING, + 0, + None, + ) + if handle == INVALID_HANDLE_VALUE: + return None + try: + payload = ("\r\n".join(args) + "\r\n\r\n").encode("utf-8") + written = W.DWORD(0) + if not kernel32.WriteFile(handle, payload, len(payload), ctypes.byref(written), None) or written.value != len(payload): + return False, "Pipe write failed; command outcome unknown" + chunks: list[bytes] = [] + buf = ctypes.create_string_buffer(4096) + read = W.DWORD(0) + while True: + if not kernel32.ReadFile(handle, buf, 4096, ctypes.byref(read), None): + if ctypes.get_last_error() == 109: + break + return False, "Pipe read failed; command outcome unknown" + if not read.value: + break + chunks.append(buf.raw[:read.value]) + try: + text = b"".join(chunks).decode("utf-8") + except UnicodeDecodeError: + return False, "Invalid UTF-8 response" + status, sep, body = text.partition("\n") + status = status.removesuffix("\r") + if not sep or status not in ("ok", "error"): + return False, "Invalid pipe response; command outcome unknown" + ok = status == "ok" + body = body.removesuffix("\n").removesuffix("\r") + return ok, body + finally: + kernel32.CloseHandle(handle) + + +def _startup_registry_exe() -> str | None: + if sys.platform != "win32": + return None + try: + import winreg + + with winreg.OpenKey( + winreg.HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Run", + ) as key: + value, _ = winreg.QueryValueEx(key, "WindowTabs") + candidate = str(value).strip().strip('"').split('"')[0] + if os.path.isfile(candidate): + return candidate + except OSError: + return None + return None + + +def find_executable(configured: str = "") -> str | None: + candidates: list[str] = [] + if configured: + candidates.append(os.path.expandvars(configured.strip().strip('"'))) + from_path = shutil.which("WindowTabs.exe") + if from_path: + candidates.append(from_path) + from_reg = _startup_registry_exe() + if from_reg: + candidates.append(from_reg) + for base_env in ("LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"): + base = os.environ.get(base_env) + if base: + candidates.append(os.path.join(base, "WindowTabs", "WindowTabs.exe")) + for path in candidates: + if path and os.path.isfile(path): + return path + return None + + +def _run_cli(exe: str, args: list[str], timeout_s: float = 8.0) -> str: + result = subprocess.run( + [exe, *args], + capture_output=True, + text=True, + encoding="utf-8", + errors="strict", + check=True, + timeout=timeout_s, + creationflags=CREATE_NO_WINDOW if sys.platform == "win32" else 0, + ) + return result.stdout + + +def list_commands(exe: str | None) -> list[tuple[str, str]]: + reply = send_pipe(["--commands"]) + if reply is not None: + raw = reply[1] if reply[0] else "" + elif exe: + try: + raw = _run_cli(exe, ["--commands"]) + except (OSError, subprocess.SubprocessError, UnicodeError): + return [] + else: + return [] + commands: list[tuple[str, str]] = [] + for line in raw.splitlines(): + line = line.strip() + if not line: + continue + parts = line.split(None, 1) + cmd_id = parts[0] + caption = parts[1].strip() if len(parts) > 1 else cmd_id + commands.append((cmd_id, caption)) + return commands + + +def list_workspaces(exe: str | None) -> list[str]: + reply = send_pipe(["--workspaces"]) + if reply is not None: + raw = reply[1] if reply[0] else "" + elif exe: + try: + raw = _run_cli(exe, ["--workspaces"]) + except (OSError, subprocess.SubprocessError, UnicodeError): + return [] + else: + return [] + return [line for line in raw.splitlines() if line] + + +def restore_workspace(exe: str | None, name: str) -> None: + if send_pipe(["--workspace", name]) is not None: + return + if exe: + subprocess.Popen( + [exe, "--workspace", name], + creationflags=CREATE_NO_WINDOW if sys.platform == "win32" else 0, + ) + + +def run_command(exe: str | None, cmd_id: str, choice: str = "", delay_ms: int = 120) -> None: + if delay_ms > 0: + time.sleep(delay_ms / 1000.0) + args = ["--command", cmd_id] + if choice: + args.append(choice) + if send_pipe(args) is not None: + return + if exe: + subprocess.Popen( + [exe, *args], + creationflags=CREATE_NO_WINDOW if sys.platform == "win32" else 0, + ) + + +def launch_app(exe: str) -> None: + subprocess.Popen([exe]) diff --git a/integrations/utools/README.md b/integrations/utools/README.md new file mode 100644 index 00000000..99fe7025 --- /dev/null +++ b/integrations/utools/README.md @@ -0,0 +1,20 @@ +# uTools Plugin for WindowTabs + +Control [WindowTabs](https://windowtabs.app) workspaces and commands directly from uTools using its native list mode. + +## Triggers + +- `wt`, `windowtabs`, `窗口标签`, `标签分组`, `窗口分屏` — Search all saved workspaces and commands. +- `工作区`, `wt ws`, `workspaces` — Search and restore saved workspaces. + +## How it works + +- Connects directly to a running WindowTabs instance over its local named pipe (`BemoSoftware.WindowTabs.`). +- Falls back to invoking `WindowTabs.exe` CLI when WindowTabs is not running. +- Hides the uTools window briefly before sending `--command` so the action applies to your previously focused app window. + +## Local debugging and publishing + +1. Install **uTools Developer Tools** (`uTools 开发者工具`) from the uTools plugin marketplace. +2. Import `plugin.json` from this folder to debug locally on Windows. +3. Package and submit this folder from uTools Developer Tools to publish to the uTools marketplace. diff --git a/integrations/utools/logo.png b/integrations/utools/logo.png new file mode 100644 index 00000000..815a3b06 Binary files /dev/null and b/integrations/utools/logo.png differ diff --git a/integrations/utools/plugin.json b/integrations/utools/plugin.json new file mode 100644 index 00000000..8b8f3237 --- /dev/null +++ b/integrations/utools/plugin.json @@ -0,0 +1,22 @@ +{ + "pluginName": "WindowTabs", + "description": "Control WindowTabs workspaces and window-tabbing commands / 控制 WindowTabs 工作区与窗口标签命令", + "author": "leafOfTree", + "homepage": "https://windowtabs.app", + "version": "1.0.0", + "logo": "logo.png", + "preload": "preload.js", + "platform": ["win32"], + "features": [ + { + "code": "wt_all", + "explain": "搜索 WindowTabs 工作区与命令", + "cmds": ["wt", "windowtabs", "窗口标签", "标签分组", "窗口分屏"] + }, + { + "code": "wt_workspaces", + "explain": "快速恢复 WindowTabs 工作区", + "cmds": ["工作区", "wt ws", "workspaces"] + } + ] +} diff --git a/integrations/utools/preload.js b/integrations/utools/preload.js new file mode 100644 index 00000000..23b89386 --- /dev/null +++ b/integrations/utools/preload.js @@ -0,0 +1,260 @@ +const { execFile, execFileSync, spawn } = require("child_process"); +const fs = require("fs"); +const net = require("net"); +const path = require("path"); + +const WEBSITE = "https://windowtabs.app"; +const EXE_KEY = "wt_exe_path"; +const COMMAND_DELAY_MS = 120; + +let cachedSessionId = null; +let cachedItems = []; + +function getSessionId() { + if (cachedSessionId !== null) return cachedSessionId; + try { + const out = execFileSync( + "tasklist", + ["/FI", `PID eq ${process.pid}`, "/FO", "CSV", "/NH"], + { encoding: "utf8", windowsHide: true, timeout: 1500 } + ); + // CSV format: "image","pid","sessionName","session#","mem" + const cols = out.trim().split('","'); + if (cols.length >= 4) { + const sid = parseInt(cols[3], 10); + if (!Number.isNaN(sid)) { + cachedSessionId = sid; + return sid; + } + } + } catch (_) { + // Ignore and fall back to CLI. + } + return null; +} + +function sendPipe(args, timeoutMs = 1200) { + return new Promise((resolve) => { + const sid = getSessionId(); + if (sid === null) return resolve(null); + const pipePath = `\\\\.\\pipe\\BemoSoftware.WindowTabs.${sid}`; + let settled = false; + const done = (val) => { + if (!settled) { + settled = true; + resolve(val); + } + }; + const client = net.createConnection(pipePath); + let data = ""; + let sent = false; + const lost = () => sent ? { ok: false, body: "Pipe reply lost; command outcome unknown" } : null; + client.setEncoding("utf8"); + const timer = setTimeout(() => { + client.destroy(); + done(lost()); + }, timeoutMs); + + client.on("connect", () => { + sent = true; + client.write(args.join("\r\n") + "\r\n\r\n", "utf8"); + }); + client.on("data", (chunk) => { + data += chunk; + }); + client.on("end", () => { + clearTimeout(timer); + const lines = data.split(/\r?\n/); + if (!["ok", "error"].includes(lines[0]) || lines.length < 2) return done(lost()); + done({ + ok: lines[0].trim() === "ok", + body: lines.slice(1).join("\n").replace(/\n$/, ""), + }); + }); + client.on("error", () => { + clearTimeout(timer); + done(lost()); + }); + client.on("close", () => { + clearTimeout(timer); + done(lost()); + }); + }); +} + +function findExecutable() { + const candidates = []; + try { + const saved = utools.dbStorage.getItem(EXE_KEY); + if (saved) candidates.push(saved); + } catch (_) {} + + try { + const whereOut = execFileSync("where", ["WindowTabs.exe"], { + encoding: "utf8", + windowsHide: true, + timeout: 1000, + }); + const first = whereOut.split(/\r?\n/).find((l) => l.trim()); + if (first) candidates.push(first.trim()); + } catch (_) {} + + for (const envKey of ["LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"]) { + if (process.env[envKey]) { + candidates.push(path.join(process.env[envKey], "WindowTabs", "WindowTabs.exe")); + } + } + + return candidates.find((p) => p && fs.existsSync(p)) || null; +} + +function runCli(exe, args) { + return new Promise((resolve) => { + if (!exe) return resolve(""); + execFile(exe, args, { encoding: "utf8", windowsHide: true, timeout: 8000 }, (err, stdout) => { + resolve(err ? "" : (stdout || "")); + }); + }); +} + +async function fetchWorkspaces(exe) { + const reply = await sendPipe(["--workspaces"]); + const raw = reply ? (reply.ok ? reply.body : "") : await runCli(exe, ["--workspaces"]); + return raw + .split(/\r?\n/) + .filter(Boolean); +} + +async function fetchCommands(exe) { + const reply = await sendPipe(["--commands"]); + const raw = reply ? (reply.ok ? reply.body : "") : await runCli(exe, ["--commands"]); + return raw + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean) + .map((line) => { + const match = line.match(/^(\S+)\s+(.*)$/); + return match ? { id: match[1], caption: match[2].trim() } : { id: line, caption: line }; + }); +} + +function buildFooterItems(exe) { + const items = []; + if (!exe) { + items.push({ + title: "下载 WindowTabs (windowtabs.app)", + description: "未检测到运行中的 WindowTabs,点击前往官网下载", + action: "open_url", + payload: WEBSITE, + }); + } + items.push({ + title: "配置 WindowTabs.exe 路径", + description: exe ? `当前路径:${exe}` : "手动选择本地 WindowTabs.exe", + action: "pick_exe", + }); + return items; +} + +async function loadItems(workspacesOnly) { + const exe = findExecutable(); + const workspaces = await fetchWorkspaces(exe); + const commands = workspacesOnly ? [] : await fetchCommands(exe); + + const items = []; + for (const ws of workspaces) { + items.push({ + title: ws, + description: `恢复工作区 · --workspace "${ws}"`, + action: "workspace", + payload: ws, + searchText: `${ws} workspace 工作区`, + }); + } + for (const cmd of commands) { + items.push({ + title: cmd.caption, + description: `执行命令 · --command ${cmd.id}`, + action: "command", + payload: cmd.id, + searchText: `${cmd.caption} ${cmd.id}`, + }); + } + items.push(...buildFooterItems(exe)); + cachedItems = items; + return items; +} + +function filterItems(query) { + const q = (query || "").trim().toLowerCase(); + if (!q) return cachedItems; + const words = q.split(/\s+/); + return cachedItems.filter((item) => { + const haystack = `${item.title} ${item.description} ${item.searchText || ""}`.toLowerCase(); + return words.every((w) => haystack.includes(w)); + }); +} + +async function executeItem(item) { + const exe = findExecutable(); + if (item.action === "open_url") { + utools.shellOpenExternal(item.payload); + utools.outPlugin(); + return; + } + if (item.action === "pick_exe") { + const files = utools.showOpenDialog({ + title: "选择 WindowTabs.exe", + filters: [{ name: "Executable", extensions: ["exe"] }], + properties: ["openFile"], + }); + if (files && files[0]) { + utools.dbStorage.setItem(EXE_KEY, files[0]); + utools.showNotification("已保存 WindowTabs.exe 路径"); + } + return; + } + if (item.action === "workspace") { + utools.hideMainWindow(); + const reply = await sendPipe(["--workspace", item.payload]); + if (!reply && exe) { + spawn(exe, ["--workspace", item.payload], { detached: true, stdio: "ignore", windowsHide: true }).unref(); + } + utools.outPlugin(); + return; + } + if (item.action === "command") { + // Hide uTools first so the previous foreground window receives the WindowTabs command. + utools.hideMainWindow(); + setTimeout(async () => { + const reply = await sendPipe(["--command", item.payload]); + if (!reply && exe) { + spawn(exe, ["--command", item.payload], { detached: true, stdio: "ignore", windowsHide: true }).unref(); + } + utools.outPlugin(); + }, COMMAND_DELAY_MS); + } +} + +function makeListFeature(workspacesOnly, placeholder) { + return { + mode: "list", + args: { + placeholder, + enter: async (_action, callbackSetList) => { + callbackSetList(await loadItems(workspacesOnly)); + }, + search: (_action, searchWord, callbackSetList) => { + callbackSetList(filterItems(searchWord)); + }, + select: (_action, itemData) => { + executeItem(itemData); + }, + }, + }; +} + +window.exports = { + wt_all: makeListFeature(false, "搜索 WindowTabs 工作区或命令..."), + wt_workspaces: makeListFeature(true, "搜索要恢复的 WindowTabs 工作区..."), +}; diff --git a/integrations/utools/tests/pipe.test.js b/integrations/utools/tests/pipe.test.js new file mode 100644 index 00000000..947ae51b --- /dev/null +++ b/integrations/utools/tests/pipe.test.js @@ -0,0 +1,60 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { EventEmitter } = require("node:events"); +const { StringDecoder } = require("node:string_decoder"); +const fs = require("node:fs"); +const vm = require("node:vm"); + +function client(chunks, failure) { + let calls = 0; + const socket = new EventEmitter(); + let decoder; + socket.setEncoding = encoding => { decoder = new StringDecoder(encoding); }; + socket.destroy = () => socket.emit("close"); + socket.write = () => { + if (failure === "after") return socket.emit("error", new Error("lost")); + for (const chunk of chunks) socket.emit("data", decoder ? decoder.write(chunk) : chunk); + if (decoder) socket.emit("data", decoder.end()); + socket.emit("end"); + }; + const context = { + window: {}, setTimeout, clearTimeout, process, + require(name) { + if (name === "net") return { createConnection() { + queueMicrotask(() => failure === "before" ? socket.emit("error", new Error("missing")) : socket.emit("connect")); + return socket; + }}; + if (name === "child_process") return { + execFileSync: () => '"node","1","Console","1","0"', + execFile: (_exe, _args, _opts, cb) => { calls++; cb(null, "fallback\r\n"); } + }; + return require(name); + } + }; + vm.runInNewContext(fs.readFileSync(require("node:path").join(__dirname, "../preload.js"), "utf8"), context); + return { context, calls: () => calls }; +} + +test("all UTF-8 split boundaries preserve workspace names", async () => { + const name = " 项目 仕事 업무 مشروع Cafe\u0301 🚀 "; + const bytes = Buffer.from("ok\r\n" + name + "\r\n"); + for (let i = 1; i < bytes.length; i++) { + const c = client([bytes.subarray(0,i), bytes.subarray(i)]); + const names = await c.context.fetchWorkspaces("wt.exe"); + assert.deepEqual(Array.from(names), [name]); + assert.equal(c.calls(), 0); + } +}); + +test("fallback only before sending; empty and error replies are final", async () => { + for (const [chunks, failure, expected, count] of [ + [[], "before", ["fallback"], 1], + [[], "after", [], 0], + [[Buffer.from("ok\r\n\r\n")], null, [], 0], + [[Buffer.from("error\r\nunknown\r\n")], null, [], 0] + ]) { + const c = client(chunks, failure); + assert.deepEqual(Array.from(await c.context.fetchWorkspaces("wt.exe")), expected); + assert.equal(c.calls(), count); + } +});