This repository has no description
13 kB
452 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 await saveAllTabs();
213 }, 500);
214}
215
216// Listen to all tab events that should trigger a save
217browser.tabs.onCreated.addListener(scheduleSave);
218browser.tabs.onRemoved.addListener(scheduleSave);
219browser.tabs.onUpdated.addListener((_tabId, changeInfo) => {
220 // Save on URL changes and title changes (navigation complete)
221 if (changeInfo.url || changeInfo.title) {
222 scheduleSave();
223 }
224});
225browser.tabs.onMoved.addListener(scheduleSave);
226browser.tabs.onActivated.addListener(scheduleSave);
227browser.tabs.onAttached.addListener(scheduleSave);
228browser.tabs.onDetached.addListener(scheduleSave);
229
230// ── Tab restoring (from workspace file) ─────────────────────
231
232async function restoreWorkspace(workspace) {
233 if (restoringWorkspaces.has(workspace)) return;
234 restoringWorkspaces.add(workspace);
235
236 try {
237 const resp = await sendNative("get_tabs", { workspace });
238 const tabs = resp.tabs || [];
239 if (tabs.length === 0) return;
240
241 // Create window with the first tab to avoid a blank "new tab"
242 const first = tabs[0];
243 const newWindow = await browser.windows.create({ url: first.url });
244 const windowId = newWindow.id;
245
246 // Pin the first tab if needed
247 if (first.pinned && newWindow.tabs && newWindow.tabs[0]) {
248 await browser.tabs.update(newWindow.tabs[0].id, { pinned: true });
249 }
250
251 // Create remaining tabs
252 for (let i = 1; i < tabs.length; i++) {
253 await browser.tabs.create({
254 windowId,
255 url: tabs[i].url,
256 pinned: tabs[i].pinned,
257 active: tabs[i].active,
258 });
259 }
260 } catch (e) {
261 console.error(`Failed to restore workspace ${workspace}:`, e);
262 } finally {
263 restoringWorkspaces.delete(workspace);
264 }
265}
266
267// ── Workspace change handling ────────────────────────────────
268
269async function onWorkspaceChange(workspace) {
270 if (!workspace || workspace === lastWorkspace) return;
271
272 // Save all workspaces' tabs before switching
273 await saveAllTabs();
274
275 lastWorkspace = workspace;
276
277 // Don't restore tabs during startup — only after user switches workspace
278 if (!initialized) return;
279
280 // Check if this workspace already has a Firefox window
281 const withFirefox = await getWorkspacesWithFirefox();
282 if (withFirefox.has(workspace)) return;
283
284 // No Firefox window — restore saved tabs
285 const resp = await sendNative("get_tabs", { workspace });
286 const tabs = resp.tabs || [];
287 if (tabs.length > 0) {
288 await restoreWorkspace(workspace);
289 }
290}
291
292// ── Send tab to workspace ───────────────────────────────────
293
294async function sendTabToWorkspace(tabId, targetWorkspace) {
295 try {
296 const mappings = await getFirefoxWindowMappings();
297 const targetWindowId = mappings.get(targetWorkspace);
298
299 if (targetWindowId) {
300 await browser.tabs.move(tabId, { windowId: targetWindowId, index: -1 });
301 } else {
302 const sourceWorkspace = await getCurrentWorkspace();
303 const newWindow = await browser.windows.create({ tabId });
304 await sendNative("move_to_workspace", { name: targetWorkspace });
305 if (sourceWorkspace) {
306 await sendNative("goto_workspace", { name: sourceWorkspace });
307 }
308 }
309 // Save both workspaces after move
310 scheduleSave();
311 } catch (e) {
312 console.error(`Failed to send tab to workspace ${targetWorkspace}:`, e);
313 }
314}
315
316// Handle messages from the new-workspace popup
317browser.runtime.onMessage.addListener((msg) => {
318 if (
319 msg.action === "sendToNewWorkspace" &&
320 msg.workspace &&
321 pendingNewWorkspaceTabId
322 ) {
323 const tabId = pendingNewWorkspaceTabId;
324 pendingNewWorkspaceTabId = null;
325 sendTabToWorkspace(tabId, msg.workspace);
326 }
327});
328
329// ── Context menu ────────────────────────────────────────────
330
331async function rebuildContextMenu() {
332 await browser.menus.removeAll();
333
334 browser.menus.create({
335 id: "send-to-workspace",
336 title: "Send to workspace",
337 contexts: ["tab"],
338 });
339
340 const allWorkspaces = await listWorkspaces();
341 const withFirefox = await getWorkspacesWithFirefox();
342 const wsWithFirefox = [];
343 const wsWithoutFirefox = [];
344
345 for (const ws of allWorkspaces) {
346 if (withFirefox.has(ws)) {
347 wsWithFirefox.push(ws);
348 } else {
349 wsWithoutFirefox.push(ws);
350 }
351 }
352
353 for (const ws of wsWithFirefox) {
354 browser.menus.create({
355 id: `ws-${ws}`,
356 parentId: "send-to-workspace",
357 title: `● ${ws}`,
358 contexts: ["tab"],
359 });
360 }
361
362 if (wsWithFirefox.length > 0 && wsWithoutFirefox.length > 0) {
363 browser.menus.create({
364 id: "ws-separator",
365 parentId: "send-to-workspace",
366 type: "separator",
367 contexts: ["tab"],
368 });
369 }
370
371 for (const ws of wsWithoutFirefox) {
372 browser.menus.create({
373 id: `ws-${ws}`,
374 parentId: "send-to-workspace",
375 title: `○ ${ws}`,
376 contexts: ["tab"],
377 });
378 }
379
380 browser.menus.create({
381 id: "ws-separator-new",
382 parentId: "send-to-workspace",
383 type: "separator",
384 contexts: ["tab"],
385 });
386
387 browser.menus.create({
388 id: "ws-new",
389 parentId: "send-to-workspace",
390 title: "New workspace…",
391 contexts: ["tab"],
392 });
393}
394
395browser.menus.onShown.addListener(async (info) => {
396 if (info.contexts.includes("tab")) {
397 await rebuildContextMenu();
398 browser.menus.refresh();
399 }
400});
401
402browser.menus.onClicked.addListener(async (info, tab) => {
403 if (!tab || !tab.id) return;
404
405 if (info.menuItemId === "ws-new") {
406 pendingNewWorkspaceTabId = tab.id;
407 browser.windows.create({
408 url: browser.runtime.getURL("new-workspace.html"),
409 type: "popup",
410 width: 320,
411 height: 60,
412 });
413 return;
414 }
415
416 if (info.menuItemId.startsWith("ws-")) {
417 const workspace = info.menuItemId.slice(3);
418 await sendTabToWorkspace(tab.id, workspace);
419 }
420});
421
422// ── Init ────────────────────────────────────────────────────
423
424async function init() {
425 // Create anchor window immediately — doesn't need native messaging
426 try {
427 await ensureAnchorWindow();
428 } catch (e) {
429 console.error("Failed to create anchor window:", e);
430 }
431
432 // Connect to native host for workspace integration
433 connectNative();
434 await new Promise((r) => setTimeout(r, 500));
435
436 try {
437 lastWorkspace = await getCurrentWorkspace();
438 } catch (e) {
439 console.warn("Failed to get current workspace:", e);
440 }
441
442 try {
443 await rebuildContextMenu();
444 } catch (e) {
445 console.warn("Failed to build context menu:", e);
446 }
447
448 // Mark init complete — workspace changes from now on will restore tabs
449 initialized = true;
450}
451
452init();