This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

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 tabs for the workspace we're leaving 273 if (lastWorkspace) { 274 await saveTabsForWorkspace(lastWorkspace); 275 } 276 277 lastWorkspace = workspace; 278 279 // Don't restore tabs during startup — only after user switches workspace 280 if (!initialized) return; 281 282 // Check if this workspace already has a Firefox window 283 const withFirefox = await getWorkspacesWithFirefox(); 284 if (withFirefox.has(workspace)) return; 285 286 // No Firefox window — restore saved tabs 287 const resp = await sendNative("get_tabs", { workspace }); 288 const tabs = resp.tabs || []; 289 if (tabs.length > 0) { 290 await restoreWorkspace(workspace); 291 } 292} 293 294// ── Send tab to workspace ─────────────────────────────────── 295 296async function sendTabToWorkspace(tabId, targetWorkspace) { 297 try { 298 const mappings = await getFirefoxWindowMappings(); 299 const targetWindowId = mappings.get(targetWorkspace); 300 301 if (targetWindowId) { 302 await browser.tabs.move(tabId, { windowId: targetWindowId, index: -1 }); 303 } else { 304 const sourceWorkspace = await getCurrentWorkspace(); 305 const newWindow = await browser.windows.create({ tabId }); 306 await sendNative("move_to_workspace", { name: targetWorkspace }); 307 if (sourceWorkspace) { 308 await sendNative("goto_workspace", { name: sourceWorkspace }); 309 } 310 } 311 // Save both workspaces after move 312 scheduleSave(); 313 } catch (e) { 314 console.error(`Failed to send tab to workspace ${targetWorkspace}:`, e); 315 } 316} 317 318// Handle messages from the new-workspace popup 319browser.runtime.onMessage.addListener((msg) => { 320 if ( 321 msg.action === "sendToNewWorkspace" && 322 msg.workspace && 323 pendingNewWorkspaceTabId 324 ) { 325 const tabId = pendingNewWorkspaceTabId; 326 pendingNewWorkspaceTabId = null; 327 sendTabToWorkspace(tabId, msg.workspace); 328 } 329}); 330 331// ── Context menu ──────────────────────────────────────────── 332 333async function rebuildContextMenu() { 334 await browser.menus.removeAll(); 335 336 browser.menus.create({ 337 id: "send-to-workspace", 338 title: "Send to workspace", 339 contexts: ["tab"], 340 }); 341 342 const allWorkspaces = await listWorkspaces(); 343 const withFirefox = await getWorkspacesWithFirefox(); 344 const wsWithFirefox = []; 345 const wsWithoutFirefox = []; 346 347 for (const ws of allWorkspaces) { 348 if (withFirefox.has(ws)) { 349 wsWithFirefox.push(ws); 350 } else { 351 wsWithoutFirefox.push(ws); 352 } 353 } 354 355 for (const ws of wsWithFirefox) { 356 browser.menus.create({ 357 id: `ws-${ws}`, 358 parentId: "send-to-workspace", 359 title: `● ${ws}`, 360 contexts: ["tab"], 361 }); 362 } 363 364 if (wsWithFirefox.length > 0 && wsWithoutFirefox.length > 0) { 365 browser.menus.create({ 366 id: "ws-separator", 367 parentId: "send-to-workspace", 368 type: "separator", 369 contexts: ["tab"], 370 }); 371 } 372 373 for (const ws of wsWithoutFirefox) { 374 browser.menus.create({ 375 id: `ws-${ws}`, 376 parentId: "send-to-workspace", 377 title: `○ ${ws}`, 378 contexts: ["tab"], 379 }); 380 } 381 382 browser.menus.create({ 383 id: "ws-separator-new", 384 parentId: "send-to-workspace", 385 type: "separator", 386 contexts: ["tab"], 387 }); 388 389 browser.menus.create({ 390 id: "ws-new", 391 parentId: "send-to-workspace", 392 title: "New workspace…", 393 contexts: ["tab"], 394 }); 395} 396 397browser.menus.onShown.addListener(async (info) => { 398 if (info.contexts.includes("tab")) { 399 await rebuildContextMenu(); 400 browser.menus.refresh(); 401 } 402}); 403 404browser.menus.onClicked.addListener(async (info, tab) => { 405 if (!tab || !tab.id) return; 406 407 if (info.menuItemId === "ws-new") { 408 pendingNewWorkspaceTabId = tab.id; 409 browser.windows.create({ 410 url: browser.runtime.getURL("new-workspace.html"), 411 type: "popup", 412 width: 320, 413 height: 60, 414 }); 415 return; 416 } 417 418 if (info.menuItemId.startsWith("ws-")) { 419 const workspace = info.menuItemId.slice(3); 420 await sendTabToWorkspace(tab.id, workspace); 421 } 422}); 423 424// ── Init ──────────────────────────────────────────────────── 425 426async function init() { 427 // Create anchor window immediately — doesn't need native messaging 428 try { 429 await ensureAnchorWindow(); 430 } catch (e) { 431 console.error("Failed to create anchor window:", e); 432 } 433 434 // Connect to native host for workspace integration 435 connectNative(); 436 await new Promise((r) => setTimeout(r, 500)); 437 438 try { 439 lastWorkspace = await getCurrentWorkspace(); 440 } catch (e) { 441 console.warn("Failed to get current workspace:", e); 442 } 443 444 try { 445 await rebuildContextMenu(); 446 } catch (e) { 447 console.warn("Failed to build context menu:", e); 448 } 449 450 // Mark init complete — workspace changes from now on will restore tabs 451 initialized = true; 452} 453 454init();