forked from philc/vimium
-
Notifications
You must be signed in to change notification settings - Fork 1
/
background_page.html
388 lines (328 loc) · 13.3 KB
/
background_page.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
<html>
<head>
<script type="text/javascript" charset="utf-8">
var tabQueue = {}; // windowId -> Array
var keyQueue = ""; // Queue of keys typed
var validFirstKeys = {};
var singleKeyCommands = [];
var defaultSettings = { scrollStepSize: 60 };
// Port handler mapping
var portHandlers = {
keyDown: handleKeyDown,
returnScrollPosition: handleReturnScrollPosition,
isEnabledForUrl: isEnabledForUrl,
getCurrentTabUrl: getCurrentTabUrl,
getZoomLevel: getZoomLevel,
saveZoomLevel: saveZoomLevel,
getSetting: getSetting
};
var sendRequestHandlers = {
getCompletionKeys: getCompletionKeys
};
// Event handlers
var selectionChangedHandlers = [];
var getScrollPositionHandlers = {}; // tabId -> function(tab, scrollX, scrollY);
var tabLoadedHandlers = {}; // tabId -> function()
chrome.extension.onConnect.addListener(function(port, name) {
var senderTabId = port.sender.tab ? port.sender.tab.id : null;
// If this is a tab we've been waiting to open, execute any "tab loaded" handlers, e.g. to restore
// the tab's scroll position. Wait until domReady before doing this; otherwise operations like restoring
// the scroll position will not be possible.
if (port.name == "domReady" && senderTabId && tabLoadedHandlers[senderTabId]) {
var toCall = tabLoadedHandlers[senderTabId];
// Delete first to be sure there's no circular events.
delete tabLoadedHandlers[senderTabId];
toCall.call();
}
if (portHandlers[port.name])
port.onMessage.addListener(portHandlers[port.name]);
});
chrome.extension.onRequest.addListener(function (request, sender, sendResponse) {
var senderTabId = sender.tab ? sender.tab.id : null;
if (sendRequestHandlers[request.handler])
sendResponse(sendRequestHandlers[request.handler](request));
});
function handleReturnScrollPosition(args) {
if (getScrollPositionHandlers[args.currentTab.id]) {
// Delete first to be sure there's no circular events.
var toCall = getScrollPositionHandlers[args.currentTab.id];
delete getScrollPositionHandlers[args.currentTab.id];
toCall(args.currentTab, args.scrollX, args.scrollY);
}
}
/*
* Used by the content scripts to get their full URL. This is needed for URLs like "view-source:http:// .."
* because window.location doesn't know anything about the Chrome-specific "view-source:".
*/
function getCurrentTabUrl(args, port) {
var returnPort = chrome.tabs.connect(port.tab.id, { name: "returnCurrentTabUrl" });
returnPort.postMessage({ url: port.tab.url });
}
/*
* Checks the user's preferences in local storage to determine if Vimium is enabled for the given URL.
*/
function isEnabledForUrl(args, port) {
var returnPort = chrome.tabs.connect(port.tab.id, { name: "returnIsEnabledForUrl" });
// excludedUrls are stored as a series of URL expressions separated by newlines.
var excludedUrls = (localStorage["excludedUrls"] || "").split("\n");
var isEnabled = true;
for (var i = 0; i < excludedUrls.length; i++) {
// The user can add "*" to the URL which means ".*"
var regexp = new RegExp("^" + excludedUrls[i].replace(/\*/g, ".*") + "$");
if (args.url.match(regexp))
isEnabled = false;
}
returnPort.postMessage({ isEnabledForUrl: isEnabled });
}
/*
* Returns the previously saved zoom level for the current tab, or the default zoom level
*/
function getZoomLevel(args, port) {
var returnPort = chrome.tabs.connect(port.tab.id, { name: "returnZoomLevel" });
var localStorageKey = "zoom" + args.domain;
var zoomLevelForDomain = (localStorage[localStorageKey] || "").split(",")[1];
var zoomLevel = parseInt(zoomLevelForDomain || localStorage["defaultZoomLevel"] || 100);
returnPort.postMessage({ zoomLevel: zoomLevel });
}
/**
* Returns the keys that can complete a valid command given the current key queue.
*/
function getCompletionKeys(request) {
return {completionKeys: generateCompletionKeys()};
}
/*
* Used by the content scripts to get settings from the local storage.
*/
function getSetting(args, port) {
var value = localStorage[args.key] ? localStorage[args.key] : defaultSettings[args.key];
var returnPort = chrome.tabs.connect(port.tab.id, { name: "returnSetting" });
returnPort.postMessage({ key: args.key, value: value });
}
/*
* Persists the current zoom level for a given domain
*/
function saveZoomLevel(args) {
var localStorageKey = "zoom" + args.domain;
// TODO(philc): We might want to consider expiring these entries after X months as NoSquint does.
// Note(philc): We might also want to jsonify this hash instead of polluting our local storage keyspace.
localStorage[localStorageKey] = [getCurrentTimeInSeconds(), args.zoomLevel].join(",");
}
function getCurrentTimeInSeconds() { Math.floor((new Date()).getTime() / 1000); }
chrome.tabs.onSelectionChanged.addListener(function(tabId, selectionInfo) {
if (selectionChangedHandlers.length > 0) { selectionChangedHandlers.pop().call(); }
});
function repeatFunction(func, totalCount, currentCount) {
if (currentCount < totalCount)
func(function() { repeatFunction(func, totalCount, currentCount + 1); });
}
// Returns the currently selected tab along with scroll coordinates. Pass in a callback of the form:
// function(tab, scrollX, scrollY) { .. }
function getCurrentTabWithScrollPosition(callback) {
chrome.tabs.getSelected(null, function(tab) {
getScrollPositionHandlers[tab.id] = callback;
var scrollPort = chrome.tabs.connect(tab.id, { name: "getScrollPosition" });
scrollPort.postMessage({currentTab: tab});
});
}
// Start action functions
function createTab(callback) {
chrome.tabs.create({}, function(tab) { callback(); });
}
function nextTab() { selectTab("next"); }
function previousTab() { selectTab("previous"); }
/*
* Selects a tab before or after the currently selected tab. Direction is either "next" or "previous".
*/
function selectTab(direction) {
chrome.tabs.getAllInWindow(null, function(tabs) {
if (tabs.length <= 1)
return;
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].selected) {
var delta = (direction == "next") ? 1 : -1;
var toSelect = tabs[(i + delta + tabs.length) % tabs.length];
chrome.tabs.update(toSelect.id, { selected: true });
break;
}
}
});
}
function removeTab(callback) {
getCurrentTabWithScrollPosition(function(tab, scrollX, scrollY) {
var tabQueueEntry = { tabUrl: tab.url,
scrollX: scrollX,
scrollY: scrollY };
if (tabQueue[tab.windowId])
tabQueue[tab.windowId].push(tabQueueEntry);
else
tabQueue[tab.windowId] = [tabQueueEntry];
chrome.tabs.remove(tab.id);
// We can't just call the callback here because we actually need to wait
// for the selection to change to consider this action done.
selectionChangedHandlers.push(callback);
});
}
function restoreTab(callback) {
// TODO(ilya): Should this be getLastFocused instead?
chrome.windows.getCurrent(function(window) {
if (tabQueue[window.id] && tabQueue[window.id].length > 0)
{
var tabQueueEntry = tabQueue[window.id].pop();
// Clean out the tabQueue so we don't have unused windows laying about.
if (tabQueue[window.id].length == 0)
delete tabQueue[window.id];
// We have to chain a few callbacks to set the appropriate scroll position. We can't just wait until the
// tab is created because the content script is not available during the "loading" state. We need to
// wait until that's over before we can call setScrollPosition.
chrome.tabs.create({ url: tabQueueEntry.tabUrl }, function(tab) {
tabLoadedHandlers[tab.id] = function() {
var scrollPort = chrome.tabs.connect(tab.id, {name: "setScrollPosition"});
scrollPort.postMessage({ scrollX: tabQueueEntry.scrollX, scrollY: tabQueueEntry.scrollY });
};
callback();
});
}
});
}
// End action functions
var keyToCommandRegistry = {};
keyToCommandRegistry['j'] = 'scrollDown';
keyToCommandRegistry['k'] = 'scrollUp';
keyToCommandRegistry['h'] = 'scrollLeft';
keyToCommandRegistry['l'] = 'scrollRight';
keyToCommandRegistry['gg'] = 'scrollToTop';
keyToCommandRegistry['G'] = 'scrollToBottom';
keyToCommandRegistry['<c-d>'] = "scrollPageDown";
keyToCommandRegistry['<c-u>'] = "scrollPageUp";
keyToCommandRegistry['r'] = 'reload';
keyToCommandRegistry['gf'] = 'toggleViewSource';
keyToCommandRegistry['i'] = 'enterInsertMode';
keyToCommandRegistry['ba'] = 'goBack';
keyToCommandRegistry['H'] = 'goBack';
keyToCommandRegistry['fw'] = 'goForward';
keyToCommandRegistry['fo'] = 'goForward';
keyToCommandRegistry['L'] = 'goForward';
keyToCommandRegistry['zi'] = 'zoomIn';
keyToCommandRegistry['zo'] = 'zoomOut';
keyToCommandRegistry['f'] = 'activateLinkHintsMode';
keyToCommandRegistry['F'] = 'activateLinkHintsModeToOpenInNewTab';
keyToCommandRegistry['/'] = 'enterFindMode';
keyToCommandRegistry['n'] = 'performFind';
keyToCommandRegistry['N'] = 'performBackwardsFind';
keyToCommandRegistry['y'] = 'copyCurrentUrl';
keyToCommandRegistry['J'] = nextTab;
keyToCommandRegistry['K'] = previousTab;
keyToCommandRegistry['gt'] = nextTab;
keyToCommandRegistry['gT'] = previousTab;
keyToCommandRegistry['t'] = createTab;
keyToCommandRegistry['d'] = removeTab;
keyToCommandRegistry['u'] = restoreTab;
function getActualKeyStrokeLength(key) {
if (key.slice(0, 3) == "<c-" && key[key.length - 1] == ">")
return 1;
else
return key.length;
}
function populateValidFirstKeys() {
for (var key in keyToCommandRegistry)
{
if (key.length == 2)
validFirstKeys[key[0]] = true;
}
}
function populateSingleKeyCommands() {
for (var key in keyToCommandRegistry)
{
if (getActualKeyStrokeLength(key) == 1)
singleKeyCommands.push(key);
}
}
/*
* Generates a list of keys that can complete a valid command given the current key queue or the one passed
* in.
*/
function generateCompletionKeys(keysToCheck) {
var splitHash = splitKeyQueue(keysToCheck || keyQueue);
command = splitHash.command;
count = splitHash.count;
var completionKeys = singleKeyCommands.slice(0);
if (getActualKeyStrokeLength(command) == 1)
{
for (var key in keyToCommandRegistry)
{
// NOTE(ilya): This won't work if we allow keys like <c-x><c-y>.
if (key[0] == command)
completionKeys.push(key.substring(1));
}
}
return completionKeys;
}
function splitKeyQueue(queue) {
var match = /([0-9]*)(.*)/.exec(queue);
var count = parseInt(match[1]);
var command = match[2];
return {count: count, command: command};
}
function handleKeyDown(key, port) {
var hudport = chrome.tabs.connect(port.tab.id, { name: "HUD" });
if (key == "<ESC>") {
console.log("clearing keyQueue");
keyQueue = ""
hudport.postMessage({ message: "ESC", timeout: 10 });
}
else {
console.log("checking keyQueue: [", keyQueue + key, "]");
keyQueue = checkKeyQueue(keyQueue + key, port.tab.id);
console.log("new KeyQueue: " + keyQueue);
if (keyQueue != "") {
hudport.postMessage({ message: keyQueue });
}
}
}
function checkKeyQueue(keysToCheck, tabId) {
var refreshedCompletionKeys = false;
var splitHash = splitKeyQueue(keysToCheck);
command = splitHash.command;
count = splitHash.count;
if (command.length == 0) { return keysToCheck; }
if (isNaN(count)) { count = 1; }
if (keyToCommandRegistry[command]) {
registryEntry = keyToCommandRegistry[command];
console.log("command found for [", keysToCheck, "],", registryEntry);
var hudport = chrome.tabs.connect(tabId, { name: "HUD" });
hudport.postMessage({ message: keysToCheck, timeout: 10 });
if (typeof(registryEntry) == "string") {
var port = chrome.tabs.connect(tabId, { name: "executePageCommand" });
port.postMessage({ command: registryEntry, count: count,
completionKeys: generateCompletionKeys("") });
refreshedCompletionKeys = true;
} else {
repeatFunction(registryEntry, count, 0);
}
newKeyQueue = "";
} else if (command.length > 1) {
// The second key might be a valid command by its self.
if (keyToCommandRegistry[command[1]])
newKeyQueue = checkKeyQueue(command[1]);
else
newKeyQueue = (validFirstKeys[command[1]] ? command[1] : "");
} else {
newKeyQueue = (validFirstKeys[command] ? count.toString() + command : "");
}
// If we haven't sent the completion keys piggybacked on executePageCommand,
// send them by themselves.
if (!refreshedCompletionKeys)
{
var port = chrome.tabs.connect(tabId, { name: "refreshCompletionKeys" });
port.postMessage({ completionKeys: generateCompletionKeys(newKeyQueue) });
}
return newKeyQueue;
}
function init() {
populateValidFirstKeys();
populateSingleKeyCommands();
}
init();
</script>
</head>
</html>