Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
uses: actions/checkout@v7

- name: Set up Node.js
uses: actions/setup-node@v6
uses: actions/setup-node@v7
with:
node-version: 24
cache: npm
Expand Down
67 changes: 41 additions & 26 deletions src/js/background/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import trackers from "@/background/page-trackers";
import { isPopupWindow } from "@/background/popup-utils";
import handleStartup from "@/background/startup";
import checkMenuPick from "@/background/check-menu-pick";
import watchForDoublePress from "@/background/double-press";
import getChromeShortcuts from "@/background/get-chrome-shortcuts";
import { CommandIDs } from "@/background/constants";
import log from "@/background/persistent-log";
import initEventController from "@/shared/eventController";
import { toggleRecentTabs } from "@/shared/commandHandlers";
Expand All @@ -25,9 +28,6 @@ if (globalThis.DEBUG) {
// relaunch woke the worker at all, and whether onStartup fired after it
log("service worker loaded");

// if the popup is opened and closed within this time, switch to the
// previous tab
const MaxPopupLifetime = 450;
const RestartDelay = 60 * 1000;
// how long the tab handlers stay quiet after a restart if nothing else
// clears the flag. generous, since a big profile can take over a minute to
Expand All @@ -52,6 +52,15 @@ function delay(
}


// the shortcut Chrome currently has for opening the menu, to tell a second
// press of it from the other keys the menu page reports
function getMenuShortcut()
{
return getChromeShortcuts()
.then((shortcuts) => shortcuts.find(({ id }) => id == CommandIDs.OpenMenuCommand));
}


const ports = {};
//let startingUp = false;
// handleStartup() reads the reason synchronously to decide whether this
Expand Down Expand Up @@ -153,15 +162,9 @@ chrome.runtime.onConnect.addListener(port => {
}
//console.log("---- background: onConnect", port?.name);

// if sw.js is replaying a connect that arrived while this worker was
// still starting, use when it arrived. the time of the replay would
// make a menu that had been open through a slow start look like it had
// only just opened, and closing it would be taken for a double-press.
const connectTime = globalThis.replayedEventTime ?? Date.now();
// the port this worker made for itself at startup, below, rather than
// one a page opened in init.js
const isStandIn = port.isStandIn === true;
let closedOnPurpose = false;
// the window the menu opened over, so a failed pick can say whether it
// was of a tab in another window. kept as a promise, since a quick
// pick can arrive before it resolves.
Expand All @@ -188,13 +191,12 @@ DEBUG && console.log("== onConnect", port.name, state.startingUp);
// TODO: this only needs to be done for the menu case
port.onMessage.addListener(message => {
//console.log("---- background: onMessage", port.name, message);
// the page says when it's closing because of something the user
// did in it, either pressing esc or picking an item. a pick of a
// tab comes as an object with its ID.
// the menu says when it's closing because the user picked an
// item. a pick of a tab comes as an object with its ID.
// double-press.js listens for the same messages, to tell a pick
// or esc from a second press of the shortcut.
const name = message?.message ?? message;

closedOnPurpose = (name == "closedByEsc" || name == "pickedItem");

if (port.name == "menu" && name == "pickedItem" && typeof message?.tabID == "number") {
// the menu can't see whether its pick worked, since its page
// may be destroyed before the tab is activated. start watching
Expand All @@ -215,19 +217,32 @@ DEBUG && console.log("== onConnect", port.name, state.startingUp);
popupWindow.close("popup-port-disconnected");
// }
}

// a stand-in port can't be a double-press: it's made when the worker
// starts, not when the user opens anything. it drops right away if
// the popup page was already closing, such as after a hide behavior
// change, which woke the worker and then switched to the previous tab.
// nor can a menu that said it was closing: without that, picking a
// tab within MaxPopupLifetime of opening the menu switched to it
// and then toggled straight back.
if (!isStandIn && !closedOnPurpose && Date.now() - connectTime < MaxPopupLifetime) {
// this was a double-press of alt-Q, so toggle the tabs
toggleRecentTabs();
}
});

// a popup window or menu that's closed by a second press of its
// shortcut is a double-press, so toggle the tabs. the worker does
// that even when the popup window's page has control: the menu
// connecting always wakes the worker, its timing of the port doesn't
// depend on a hidden page that can be slow to hear about the close,
// and for the popup window, its own page is the one going away.
// the menu's page reports the keys it sees, so a second press can be
// timed from the key going down rather than from the port closing.
// a stand-in port can't be a double-press: it's made when the worker
// starts, not when the user opens anything. it drops right away if
// the popup page was already closing, such as after a hide behavior
// change, which woke the worker and then switched to the previous tab.
if (!isStandIn) {
watchForDoublePress(
port,
({ pressTime, lifetime }) => {
log("double-press of the", port.name, "shortcut:", pressTime !== undefined
? `key down ${pressTime} ms after the page started`
: `closed after ${lifetime} ms`);
toggleRecentTabs();
},
port.name == "menu" ? getMenuShortcut : undefined
);
}
});


Expand Down
156 changes: 156 additions & 0 deletions src/js/background/double-press.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// pressing the shortcut for the menu or the popup window again right after
// it opens closes it, and that double-press toggles to the previous tab.
// Chrome doesn't tell the extension about either press of the menu's
// shortcut, and the popup window's page is the one going away, so the
// worker has to work it out from the page's port.

// if the popup or menu is opened and closed within this time, it's taken
// for a second press of the shortcut that opened it
const MaxPopupLifetime = 450;
// when the menu's page saw the second press itself, how long after the
// page started the key can have gone down. the port's lifetime is a poor
// measure of the time between the presses: it starts when the page
// connects, some 70-110 ms after the page starts, and ends when the page
// has gone, which was 230-350 ms after the second press on a fast machine
// with few tabs, and longer the busier the page is. so the same pair of
// presses could land on either side of MaxPopupLifetime.
// the page starts some tens of ms after the first press, so this allows
// a little over half a second between the presses, about the default
// double-click time on Windows. it was 300 at first, which is what
// MaxPopupLifetime allowed at its best, and that turned out to be right
// in the middle of an unhurried double-press: in one run of ten, the key
// went down 242-335 ms after the page started, and only half toggled.
// it can be this generous because only a second press of the menu's own
// shortcut counts. a click outside the menu or a slow page can't.
const MaxPressGap = 500;

const ModifierFlags = ["altKey", "ctrlKey", "shiftKey", "metaKey"];
// the names get-chrome-shortcuts.js gives the modifiers, on any platform
const FlagsByModifier = {
alt: "altKey",
opt: "altKey",
ctrl: "ctrlKey",
shift: "shiftKey",
cmd: "metaKey",
search: "metaKey"
};
const KeyNames = {
" ": "space"
};
// the letter or digit on a key, whatever a modifier turned it into
const CodePattern = /^(?:Key|Digit)(.)$/;


// whether a keydown the menu page reported is the given shortcut, which is
// an entry from get-chrome-shortcuts.js. the modifiers have to match
// exactly, since Chrome wouldn't take anything else for the shortcut.
export function isShortcutKey(
{ type, repeat, key, code, ...flags },
shortcut)
{
const { baseKey, modifiers = [] } = shortcut || {};

if (type !== "keydown" || repeat || !baseKey || !modifiers.length) {
return false;
}

const shortcutFlags = modifiers.map((modifier) => FlagsByModifier[modifier]);
const lcKey = String(key).toLowerCase();
// with a modifier down, the key can be a different character, like !
// for shift-1, or a dead key for opt-E on a Mac, so check the code too
const names = [KeyNames[lcKey] || lcKey, CodePattern.exec(code)?.[1].toLowerCase()];

return !shortcutFlags.includes(undefined)
&& ModifierFlags.every((flag) => Boolean(flags[flag]) == shortcutFlags.includes(flag))
&& names.includes(baseKey);
}


// call onDoublePress if the page behind port was closed by a second press
// of the shortcut that opened it. call this from an onConnect handler,
// since the port's lifetime is counted from the call.
//
// getShortcut is passed for the menu. it returns a promise of the menu's
// shortcut, and it's called now, so the answer is ready by the time the
// port closes. the user can change the shortcut at any time and Chrome
// doesn't say when, so it's asked for each time the menu opens. if the
// page reported a press of that shortcut, when the key went down decides
// it. otherwise it's whether the port closed within MaxPopupLifetime,
// which is all there is to go on when:
// - it's the popup window's port
// - the press came before the menu had the focus. it goes to the
// browser window then, and Chrome closes the menu before it's shown.
// - Chrome didn't return the shortcut, which it sometimes doesn't
//
// neither catches a press that comes after the menu has the focus but
// before it has painted, a stretch of 50-90 ms. Chrome doesn't deliver a
// key that goes down then to the page, and doesn't close the menu either,
// so the menu just stays open. that's true of any key, not only the
// shortcut, and the page can't tell it from a single press held past the
// paint, since all it sees of either is the key coming up.
//
// onDoublePress is passed how it was decided, for logging: { pressTime }
// in ms from the page starting, or { lifetime } in ms.
export default function watchForDoublePress(
port,
onDoublePress,
getShortcut)
{
// if sw.js is replaying a connect that arrived while the worker was
// still starting, use when it arrived. the time of the replay would
// make a menu that had been open through a slow start look like it had
// only just opened, and closing it would be taken for a double-press.
const connectTime = globalThis.replayedEventTime ?? Date.now();
const shortcutPromise = getShortcut
? Promise.resolve().then(getShortcut).catch(() => null)
: null;
const keys = [];
let closedOnPurpose = false;

port.onMessage.addListener((message) => {
// the page says when it's closing because of something the user
// did in it, either pressing esc or picking an item. without
// that, picking a tab within MaxPopupLifetime of opening the menu
// switched to it and then toggled straight back. the message is
// a string, or an object with the string in its message key.
// once said, it stays said, since the page posts other things on
// this port too, and one of those arriving afterwards mustn't
// turn a pick back into a double-press.
const name = message?.message ?? message;

if (name == "closedByEsc" || name == "pickedItem") {
closedOnPurpose = true;
} else if (name == "menuKey") {
keys.push(message);
}
});

port.onDisconnect.addListener(() => {
if (closedOnPurpose) {
return;
}

const lifetime = Date.now() - connectTime;
const checkLifetime = () => {
if (lifetime < MaxPopupLifetime) {
onDoublePress({ lifetime });
}
};

if (!shortcutPromise || !keys.length) {
checkLifetime();

return;
}

shortcutPromise.then((shortcut) => {
const press = keys.find((key) => isShortcutKey(key, shortcut));

if (!press) {
checkLifetime();
} else if (press.time < MaxPressGap) {
onDoublePress({ pressTime: press.time });
}
});
});
}
67 changes: 65 additions & 2 deletions src/js/background/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,16 +82,55 @@ const DetachedEventNames = new Set(["commands.onCommand"]);
// sent to a dead port until the menu is next opened and closed.
const closedPorts = new WeakSet();

function watchForClose(
// what each cached port has posted so far. a page posts as soon as it has
// connected, and Chrome doesn't hold a message for a listener that's added
// later, so anything posted before background.js got to the port's
// onConnect was lost. that included the key the toolbar menu's page
// reports when its shortcut is pressed a second time: a double-press that
// started the worker could only be judged by how long the port stayed
// open, and one that kept it open 465 ms didn't toggle. the messages are
// handed to the port's real listeners right after its connect is replayed.
// a port never has more than a handful this early, but a page that's stuck
// in a loop shouldn't be able to fill the worker's memory while it starts.
const MaxCachedPortMessages = 50;
const cachedPortMessages = new Map();

function watchPort(
port)
{
try {
const messages = [];
const keep = (message) => {
if (messages.length < MaxCachedPortMessages) {
messages.push(message);
}
};

port.onDisconnect.addListener(() => closedPorts.add(port));
port.onMessage.addListener(keep);
cachedPortMessages.set(port, { messages, keep });
} catch (error) {
// the placeholder listener must never throw
}
}

// stop keeping a port's messages, and return the ones it posted
function takePortMessages(
port)
{
const { messages = [], keep } = cachedPortMessages.get(port) || {};

cachedPortMessages.delete(port);

try {
keep && port.onMessage.removeListener(keep);
} catch (error) {
// a port that has closed throws when it's touched
}

return messages;
}

function cacheEvents(
eventNames)
{
Expand All @@ -111,7 +150,7 @@ function cacheEvents(
cache.push([eventName, eventArgs, Date.now()]);

if (eventName === "runtime.onConnect") {
watchForClose(eventArgs[0]);
watchPort(eventArgs[0]);
}

if (cache.length > MaxCachedEvents) {
Expand Down Expand Up @@ -145,6 +184,19 @@ function cacheEvents(
// causing the shortcuts, tab events and onStartup to all go dead.
cache = null;

// only the ports replayed below still need their messages. the
// rest are closed, were dropped from the cache as too old, or
// have nothing to be replayed to.
const replayedPorts = new Set(!loaded ? [] : events
.filter(([eventName]) => eventName === "runtime.onConnect")
.map(([, [port]]) => port));

for (const port of [...cachedPortMessages.keys()]) {
if (!replayedPorts.has(port)) {
takePortMessages(port);
}
}

if (!loaded) {
// there are no real handlers to replay to. keeping every
// placeholder, including onCommand's, means the next event
Expand All @@ -163,6 +215,10 @@ function cacheEvents(
for (const event of events) {
const [eventName, eventArgs, time] = event;

const portMessages = eventName === "runtime.onConnect"
? takePortMessages(eventArgs[0])
: [];

if (isExpired(event, cutoff)) {
log("sw dropping stale event:", eventName, Date.now() - time, "ms old");
continue;
Expand All @@ -183,6 +239,13 @@ function cacheEvents(

try {
getEvent(eventName).dispatch(...eventArgs);

// the port's onConnect handlers have added their listeners
// now, so give them what the page has posted since it
// connected, in order
for (const message of portMessages) {
eventArgs[0].onMessage.dispatch(message, eventArgs[0]);
}
} finally {
globalThis.replayedEventTime = undefined;
}
Expand Down
Loading