This repository has no description
13 kB
456 lines
1/* Workspace Tabs - Firefox extension for workspace-manager integration
2 *
3 * - Saves tabs to ~/workspaces/<name>.json via native host on every tab change
4 * - Restores tabs from workspace file when switching to a workspace
5 * - Maintains a hidden anchor window to keep Firefox alive
6 * - Provides "Send to workspace" context menu
7 */
8
9const HOST_NAME = "workspace_tabs";
10const ANCHOR_TITLE = "workspace-anchor";
11
12let port = null;
13let pendingRequests = new Map();
14let requestId = 0;
15let lastWorkspace = null;
16let anchorWindowId = null;
17let restoringWorkspaces = new Set();
18let pendingNewWorkspaceTabId = null;
19let savePending = false;
20let initialized = false;
21
22// ── Native messaging ────────────────────────────────────────
23
24function connectNative() {
25 try {
26 port = browser.runtime.connectNative(HOST_NAME);
27 port.onMessage.addListener(handleNativeMessage);
28 port.onDisconnect.addListener(() => {
29 console.warn("Native host disconnected, reconnecting in 2s...");
30 port = null;
31 setTimeout(connectNative, 2000);
32 });
33 } catch (e) {
34 console.error("Failed to connect to native host:", e);
35 setTimeout(connectNative, 5000);
36 }
37}
38
39function sendNative(cmd, params = {}) {
40 return new Promise((resolve, reject) => {
41 if (!port) {
42 reject(new Error("Native host not connected"));
43 return;
44 }
45 const id = ++requestId;
46 pendingRequests.set(id, { resolve, reject });
47 port.postMessage({ id, cmd, ...params });
48 setTimeout(() => {
49 if (pendingRequests.has(id)) {
50 pendingRequests.delete(id);
51 reject(new Error("Request timed out"));
52 }
53 }, 5000);
54 });
55}
56
57function handleNativeMessage(msg) {
58 if (msg.event === "workspace_change") {
59 onWorkspaceChange(msg.workspace);
60 return;
61 }
62 if (msg.id && pendingRequests.has(msg.id)) {
63 const { resolve } = pendingRequests.get(msg.id);
64 pendingRequests.delete(msg.id);
65 resolve(msg);
66 }
67}
68
69// ── Workspace queries ───────────────────────────────────────
70
71async function getCurrentWorkspace() {
72 try {
73 const resp = await sendNative("current_workspace");
74 return resp.workspace || null;
75 } catch (e) {
76 return null;
77 }
78}
79
80async function listWorkspaces() {
81 try {
82 const resp = await sendNative("list_workspaces");
83 return resp.workspaces || [];
84 } catch (e) {
85 return [];
86 }
87}
88
89// ── Firefox window <-> workspace mapping ────────────────────
90
91async function getFirefoxWindowMappings() {
92 try {
93 const resp = await sendNative("map_windows");
94 if (!resp.windows) return new Map();
95
96 const allWindows = await browser.windows.getAll({ populate: true });
97 const result = new Map();
98 const matched = new Set();
99
100 for (const mapping of resp.windows) {
101 const swayTitle = mapping.windowTitle || "";
102 for (const win of allWindows) {
103 if (matched.has(win.id) || win.id === anchorWindowId) continue;
104 const activeTab = win.tabs && win.tabs.find((t) => t.active);
105 if (
106 activeTab &&
107 activeTab.title &&
108 swayTitle.startsWith(activeTab.title)
109 ) {
110 result.set(mapping.workspace, win.id);
111 matched.add(win.id);
112 break;
113 }
114 }
115 }
116 return result;
117 } catch (e) {
118 return new Map();
119 }
120}
121
122async function getWorkspacesWithFirefox() {
123 try {
124 const resp = await sendNative("map_windows");
125 if (!resp.windows) return new Set();
126 return new Set(resp.windows.map((w) => w.workspace));
127 } catch (e) {
128 return new Set();
129 }
130}
131
132// ── Anchor window (keeps Firefox alive) ─────────────────────
133
134async function ensureAnchorWindow() {
135 if (anchorWindowId !== null) {
136 try {
137 await browser.windows.get(anchorWindowId);
138 return; // still exists
139 } catch (e) {
140 anchorWindowId = null;
141 }
142 }
143
144 // Close any existing windows (Firefox's default startup window)
145 const existingWindows = await browser.windows.getAll();
146
147 // Create anchor window with a page that sets the window title
148 const win = await browser.windows.create({
149 url: browser.runtime.getURL("anchor.html"),
150 });
151 anchorWindowId = win.id;
152
153 // Close Firefox's default window(s)
154 for (const w of existingWindows) {
155 if (w.id !== anchorWindowId) {
156 try {
157 await browser.windows.remove(w.id);
158 } catch (e) {
159 // already closed
160 }
161 }
162 }
163 // Daemon's for_window rule hides anchor when title updates to "workspace-anchor"
164}
165
166// Prevent anchor window from being closed
167browser.windows.onRemoved.addListener((windowId) => {
168 if (windowId === anchorWindowId) {
169 anchorWindowId = null;
170 ensureAnchorWindow();
171 }
172});
173
174// ── Tab saving (to workspace file) ─────────────────────────
175
176async function saveTabsForWorkspace(workspace) {
177 if (!workspace) return;
178
179 const mappings = await getFirefoxWindowMappings();
180 const windowId = mappings.get(workspace);
181 if (!windowId) return;
182
183 try {
184 const tabs = await browser.tabs.query({ windowId });
185 const tabData = tabs
186 .filter((t) => t.url && !t.url.startsWith("about:"))
187 .map((t) => ({
188 url: t.url,
189 pinned: t.pinned,
190 active: t.active,
191 }));
192
193 await sendNative("save_tabs", { workspace, tabs: tabData });
194 } catch (e) {
195 console.error(`Failed to save tabs for ${workspace}:`, e);
196 }
197}
198
199async function saveAllTabs() {
200 const mappings = await getFirefoxWindowMappings();
201 for (const [workspace] of mappings) {
202 await saveTabsForWorkspace(workspace);
203 }
204}
205
206// Debounced save: collects rapid changes, saves after 500ms idle
207function scheduleSave() {
208 if (savePending) return;
209 savePending = true;
210 setTimeout(async () => {
211 savePending = false;
212 if (lastWorkspace) {
213 await saveTabsForWorkspace(lastWorkspace);
214 }
215 }, 500);
216}
217
218// Listen to all tab events that should trigger a save
219browser.tabs.onCreated.addListener(scheduleSave);
220browser.tabs.onRemoved.addListener(scheduleSave);
221browser.tabs.onUpdated.addListener((_tabId, changeInfo) => {
222 // Save on URL changes and title changes (navigation complete)
223 if (changeInfo.url || changeInfo.title) {
224 scheduleSave();
225 }
226});
227browser.tabs.onMoved.addListener(scheduleSave);
228browser.tabs.onActivated.addListener(scheduleSave);
229browser.tabs.onAttached.addListener(scheduleSave);
230browser.tabs.onDetached.addListener(scheduleSave);
231
232// ── Tab restoring (from workspace file) ─────────────────────
233
234async function restoreWorkspace(workspace) {
235 if (restoringWorkspaces.has(workspace)) return;
236 restoringWorkspaces.add(workspace);
237
238 try {
239 const resp = await sendNative("get_tabs", { workspace });
240 const tabs = resp.tabs || [];
241 if (tabs.length === 0) return;
242
243 // Create window with the first tab to avoid a blank "new tab"
244 const first = tabs[0];
245 const newWindow = await browser.windows.create({ url: first.url });
246 const windowId = newWindow.id;
247
248 // Pin the first tab if needed
249 if (first.pinned && newWindow.tabs && newWindow.tabs[0]) {
250 await browser.tabs.update(newWindow.tabs[0].id, { pinned: true });
251 }
252
253 // Create remaining tabs
254 for (let i = 1; i < tabs.length; i++) {
255 await browser.tabs.create({
256 windowId,
257 url: tabs[i].url,
258 pinned: tabs[i].pinned,
259 active: tabs[i].active,
260 });
261 }
262 } catch (e) {
263 console.error(`Failed to restore workspace ${workspace}:`, e);
264 } finally {
265 restoringWorkspaces.delete(workspace);
266 }
267}
268
269// ── Workspace change handling ────────────────────────────────
270
271async function onWorkspaceChange(workspace) {
272 if (!workspace || workspace === lastWorkspace) return;
273
274 // Save tabs for the workspace we're leaving
275 if (lastWorkspace) {
276 await saveTabsForWorkspace(lastWorkspace);
277 }
278
279 lastWorkspace = workspace;
280
281 // Don't restore tabs during startup — only after user switches workspace
282 if (!initialized) return;
283
284 // Check if this workspace already has a Firefox window
285 const withFirefox = await getWorkspacesWithFirefox();
286 if (withFirefox.has(workspace)) return;
287
288 // No Firefox window — restore saved tabs
289 const resp = await sendNative("get_tabs", { workspace });
290 const tabs = resp.tabs || [];
291 if (tabs.length > 0) {
292 await restoreWorkspace(workspace);
293 }
294}
295
296// ── Send tab to workspace ───────────────────────────────────
297
298async function sendTabToWorkspace(tabId, targetWorkspace) {
299 try {
300 const mappings = await getFirefoxWindowMappings();
301 const targetWindowId = mappings.get(targetWorkspace);
302
303 if (targetWindowId) {
304 await browser.tabs.move(tabId, { windowId: targetWindowId, index: -1 });
305 } else {
306 const sourceWorkspace = await getCurrentWorkspace();
307 const newWindow = await browser.windows.create({ tabId });
308 await sendNative("move_to_workspace", { name: targetWorkspace });
309 if (sourceWorkspace) {
310 await sendNative("goto_workspace", { name: sourceWorkspace });
311 }
312 }
313 // Save both workspaces after move
314 scheduleSave();
315 } catch (e) {
316 console.error(`Failed to send tab to workspace ${targetWorkspace}:`, e);
317 }
318}
319
320// Handle messages from the new-workspace popup
321browser.runtime.onMessage.addListener((msg) => {
322 if (
323 msg.action === "sendToNewWorkspace" &&
324 msg.workspace &&
325 pendingNewWorkspaceTabId
326 ) {
327 const tabId = pendingNewWorkspaceTabId;
328 pendingNewWorkspaceTabId = null;
329 sendTabToWorkspace(tabId, msg.workspace);
330 }
331});
332
333// ── Context menu ────────────────────────────────────────────
334
335async function rebuildContextMenu() {
336 await browser.menus.removeAll();
337
338 browser.menus.create({
339 id: "send-to-workspace",
340 title: "Send to workspace",
341 contexts: ["tab"],
342 });
343
344 const allWorkspaces = await listWorkspaces();
345 const withFirefox = await getWorkspacesWithFirefox();
346 const wsWithFirefox = [];
347 const wsWithoutFirefox = [];
348
349 for (const ws of allWorkspaces) {
350 if (withFirefox.has(ws)) {
351 wsWithFirefox.push(ws);
352 } else {
353 wsWithoutFirefox.push(ws);
354 }
355 }
356
357 for (const ws of wsWithFirefox) {
358 browser.menus.create({
359 id: `ws-${ws}`,
360 parentId: "send-to-workspace",
361 title: `● ${ws}`,
362 contexts: ["tab"],
363 });
364 }
365
366 if (wsWithFirefox.length > 0 && wsWithoutFirefox.length > 0) {
367 browser.menus.create({
368 id: "ws-separator",
369 parentId: "send-to-workspace",
370 type: "separator",
371 contexts: ["tab"],
372 });
373 }
374
375 for (const ws of wsWithoutFirefox) {
376 browser.menus.create({
377 id: `ws-${ws}`,
378 parentId: "send-to-workspace",
379 title: `○ ${ws}`,
380 contexts: ["tab"],
381 });
382 }
383
384 browser.menus.create({
385 id: "ws-separator-new",
386 parentId: "send-to-workspace",
387 type: "separator",
388 contexts: ["tab"],
389 });
390
391 browser.menus.create({
392 id: "ws-new",
393 parentId: "send-to-workspace",
394 title: "New workspace…",
395 contexts: ["tab"],
396 });
397}
398
399browser.menus.onShown.addListener(async (info) => {
400 if (info.contexts.includes("tab")) {
401 await rebuildContextMenu();
402 browser.menus.refresh();
403 }
404});
405
406browser.menus.onClicked.addListener(async (info, tab) => {
407 if (!tab || !tab.id) return;
408
409 if (info.menuItemId === "ws-new") {
410 pendingNewWorkspaceTabId = tab.id;
411 browser.windows.create({
412 url: browser.runtime.getURL("new-workspace.html"),
413 type: "popup",
414 width: 320,
415 height: 60,
416 });
417 return;
418 }
419
420 if (info.menuItemId.startsWith("ws-")) {
421 const workspace = info.menuItemId.slice(3);
422 await sendTabToWorkspace(tab.id, workspace);
423 }
424});
425
426// ── Init ────────────────────────────────────────────────────
427
428async function init() {
429 // Create anchor window immediately — doesn't need native messaging
430 try {
431 await ensureAnchorWindow();
432 } catch (e) {
433 console.error("Failed to create anchor window:", e);
434 }
435
436 // Connect to native host for workspace integration
437 connectNative();
438 await new Promise((r) => setTimeout(r, 500));
439
440 try {
441 lastWorkspace = await getCurrentWorkspace();
442 } catch (e) {
443 console.warn("Failed to get current workspace:", e);
444 }
445
446 try {
447 await rebuildContextMenu();
448 } catch (e) {
449 console.warn("Failed to build context menu:", e);
450 }
451
452 // Mark init complete — workspace changes from now on will restore tabs
453 initialized = true;
454}
455
456init();