aboutsummaryrefslogtreecommitdiffstats
path: root/vimiumFrontend.js
blob: ce37db3fba67b5df67e9eaae8a007cf62cbbfbcf (plain)
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
/*
 * This content script takes input from its webpage and executes commands locally on behalf of the background
 * page. It must be run prior to domReady so that we perform some operations very early, like setting
 * the page's zoom level. We tell the background page that we're in domReady and ready to accept normal
 * commands by connectiong to a port named "domReady".
 */
var settings = {};
var settingsToLoad = ["scrollStepSize"];

var getCurrentUrlHandlers = []; // function(url)

var keyCodes = { ESC: 27, backspace: 8, deleteKey: 46, enter: 13 };
var insertMode = false;
var findMode = false;
var findModeQuery = "";
var keyPort;
var settingPort;
var saveZoomLevelPort;

// TODO(philc): This should be pulled from the extension's storage when the page loads.
var currentZoomLevel = 100;

function getSetting(key) {
  if (!settingPort)
    settingPort = chrome.extension.connect({ name: "getSetting" });
  settingPort.postMessage({ key: key });
}

function setSetting(args) { settings[args.key] = args.value; }

/*
 * Complete initialization work that sould be done prior to DOMReady, like setting the page's zoom level.
 */
function initializePreDomReady() {
  for (var i in settingsToLoad) { getSetting(settingsToLoad[i]); }

  document.addEventListener("keydown", onKeydown);
  document.addEventListener("focus", onFocusCapturePhase, true);
  document.addEventListener("blur", onBlurCapturePhase, true);

  var getZoomLevelPort = chrome.extension.connect({ name: "getZoomLevel" });
  getZoomLevelPort.postMessage({ domain: window.location.host });

  // Send the key to the key handler in the background page.
  keyPort = chrome.extension.connect({name: "keyDown"});

  chrome.extension.onConnect.addListener(function(port, name) {
    if (port.name == "executePageCommand") {
      port.onMessage.addListener(function(args) {
        if (this[args.command]) {
          for (var i = 0; i < args.count; i++) { this[args.command].call(); }
        }
      });
    }
    else if (port.name == "getScrollPosition") {
      port.onMessage.addListener(function(args) {
        var scrollPort = chrome.extension.connect({ name: "returnScrollPosition" });
        scrollPort.postMessage({
          scrollX: window.scrollX,
          scrollY: window.scrollY,
          currentTab: args.currentTab
        });
      });
    } else if (port.name == "setScrollPosition") {
      port.onMessage.addListener(function(args) {
        if (args.scrollX > 0 || args.scrollY > 0) { window.scrollBy(args.scrollX, args.scrollY); }
      });
    } else if (port.name == "returnCurrentTabUrl") {
      port.onMessage.addListener(function(args) {
        if (getCurrentUrlHandlers.length > 0) { getCurrentUrlHandlers.pop()(args.url); }
      });
    } else if (port.name == "returnZoomLevel") {
      port.onMessage.addListener(function(args) {
        currentZoomLevel = args.zoomLevel;
        setPageZoomLevel(currentZoomLevel);
      });
    } else if (port.name == "returnSetting") {
      port.onMessage.addListener(setSetting);
    }
  });
}

/*
 * Initialization tasks that must wait for the document to be ready.
 */
function initializeOnDomReady() {
  // Enter insert mode automatically if there's already a text box focused.
  var focusNode = window.getSelection().focusNode;
  var focusOffset = window.getSelection().focusOffset;
  if (focusNode && focusOffset && focusNode.children.length > focusOffset &&
      isInputOrText(focusNode.children[focusOffset])) { enterInsertMode(); }
  // Tell the background page we're in the dom ready state.
  chrome.extension.connect({ name: "domReady" });
};

/*
 * Asks the background page to persist the zoom level for the given domain to localStorage.
 */
function saveZoomLevel(domain, zoomLevel) {
  if (!saveZoomLevelPort)
    saveZoomLevelPort = chrome.extension.connect({ name: "saveZoomLevel" });
  saveZoomLevelPort.postMessage({ domain: domain, zoomLevel: zoomLevel });
}

/*
 * Zoom in increments of 20%; this matches chrome's CMD+ and CMD- keystrokes.
 * Set the zoom style on documentElement because document.body does not exist pre-page load.
 */
function setPageZoomLevel(zoomLevel) {
  document.documentElement.style.zoom = zoomLevel + "%";
  HUD.updatePageZoomLevel(zoomLevel);
}

function zoomIn() {
  setPageZoomLevel(currentZoomLevel += 20);
  saveZoomLevel(window.location.host, currentZoomLevel);
}

function zoomOut() {
  setPageZoomLevel(currentZoomLevel -= 20);
  saveZoomLevel(window.location.host, currentZoomLevel);
}

function scrollToBottom() { window.scrollTo(0, document.body.scrollHeight); }
function scrollToTop() { window.scrollTo(0, 0); }
function scrollUp() { window.scrollBy(0, -1 * settings["scrollStepSize"]); }
function scrollDown() { window.scrollBy(0, settings["scrollStepSize"]); }
function scrollPageUp() { window.scrollBy(0, -6 * settings["scrollStepSize"]); }
function scrollPageDown() { window.scrollBy(0, 6 * settings["scrollStepSize"]); }
function scrollLeft() { window.scrollBy(-1 * settings["scrollStepSize"], 0); }
function scrollRight() { window.scrollBy(settings["scrollStepSize"], 0); }

function reload() { window.location.reload(); }
function goBack() { history.back(); }
function goForward() { history.forward(); }

function toggleViewSource() {
  getCurrentUrlHandlers.push(toggleViewSourceCallback);

  var getCurrentUrlPort = chrome.extension.connect({ name: "getCurrentTabUrl" });
  getCurrentUrlPort.postMessage({});
}

function toggleViewSourceCallback(url) {
  if (url.substr(0, 12) == "view-source:")
  {
    window.location.href = url.substr(12, url.length - 12);
  }
  else { window.location.href = "view-source:" + url; }
}

/**
 * Sends everything except i & ESC to the handler in background_page. i & ESC are special because they control
 * insert mode which is local state to the page. The key will be are either a single ascii letter or a
 * key-modifier pair, e.g. <c-a> for control a.
 *
 * Note that some keys will only register keydown events and not keystroke events, e.g. ESC.
 */
function onKeydown(event) {
  var keyChar = "";

  if (linkHintsModeActivated)
    return;

  // Ignore modifier keys by themselves.
  if (event.keyCode > 31) {
    if (event.keyCode < 127)
      keyChar = String.fromCharCode(event.keyCode).toLowerCase();
    else
    {
      unicodeKeyInHex = "0x" + event.keyIdentifier.substring(2);
      keyChar = String.fromCharCode(parseInt(unicodeKeyInHex)).toLowerCase();
    }

    if (event.shiftKey)
      keyChar = keyChar.toUpperCase();
    if (event.ctrlKey)
      keyChar = "<c-" + keyChar + ">";
  }

  if (insertMode && event.keyCode == keyCodes.ESC)
  {
    // Note that we can't programmatically blur out of Flash embeds from Javascript.
    if (event.srcElement.tagName != "EMBED") {
      // Remove focus so the user can't just get himself back into insert mode by typing in the same input box.
      if (isInputOrText(event.srcElement)) { event.srcElement.blur(); }
      exitInsertMode();
    }
  }
  else if (findMode)
  {
    if (event.keyCode == keyCodes.ESC)
      exitFindMode();
    else if (keyChar)
      handleKeyCharForFindMode(keyChar);
    // Don't let backspace take us back in history.
    else if (event.keyCode == keyCodes.backspace || event.keyCode == keyCodes.deleteKey)
    {
      handleDeleteForFindMode();
      event.preventDefault();
    }
    else if (event.keyCode == keyCodes.enter)
      handleEnterForFindMode();
  }
  else if (!insertMode && !findMode && keyChar)
    keyPort.postMessage(keyChar);
}

function onFocusCapturePhase(event) {
  if (isFocusable(event.target))
    enterInsertMode();
}

function onBlurCapturePhase(event) {
  if (isFocusable(event.target))
    exitInsertMode();
}

/*
 * Returns true if the element is focusable. This includes embeds like Flash, which steal the keybaord focus.
 */
function isFocusable(element) { return isInputOrText(element) || element.tagName == "EMBED"; }

function isInputOrText(target) {
  return ((target.tagName == "INPUT" && (target.type == "text" || target.type == "password")) ||
          target.tagName == "TEXTAREA");
}

function enterInsertMode() {
  insertMode = true;
  HUD.show("Insert mode");
}

function exitInsertMode() {
  insertMode = false;
  HUD.hide();
}

function handleKeyCharForFindMode(keyChar) {
  findModeQuery = findModeQuery + keyChar;
  showFindModeHUDForQuery();
  performFind();
}

function handleDeleteForFindMode() {
  if (findModeQuery.length == 0)
    exitFindMode();
  else
  {
    findModeQuery = findModeQuery.substring(0, findModeQuery.length - 1);
    showFindModeHUDForQuery();
  }

  performFind();
}

function handleEnterForFindMode() {
  exitFindMode();
  performFind();
}

function performFind() {
  window.find(findModeQuery, false, false, true, false, true, false);
}

function performBackwardsFind() {
  window.find(findModeQuery, false, true, true, false, true, false);
}

function showFindModeHUDForQuery() {
  HUD.show("/" + insertSpaces(findModeQuery));
}

/*
 * We need this so that the find mode HUD doesn't match its own searches.
 */
function insertSpaces(query) {
  var newQuery = "";

  for (var i = 0; i < query.length; i++)
  {
    if (query[i] == " " || (i + 1 < query.length && query[i + 1] == " "))
      newQuery = newQuery + query[i];
    else
      newQuery = newQuery + query[i] + "<span style=\"font-size: 0px;\"> </span>";
  }

  return newQuery;
}

function enterFindMode() {
  findModeQuery = "";
  findMode = true;
  HUD.show("/");
}

function exitFindMode() {
  findMode = false;
  HUD.hide();
}

HUD = {
  show:function(text) {
    HUD.displayElement().innerHTML = text;
    HUD.displayElement().style.display = "";
  },

  updatePageZoomLevel: function(pageZoomLevel) {
    // Since the chrome HUD does not scale with the page's zoom level, neither will this HUD.
    HUD.displayElement().style.zoom = (100.0 / pageZoomLevel) * 100 + "%";
  },

  /*
   * Retrieves the HUD HTML element, creating it if necessary.
   */
  displayElement: function() {
    if (!HUD._displayElement) {
      // This is styled to precisely mimick the chrome HUD. Use the "has_popup_and_link_hud.html" test harness
      // to tweak these styles to match Chrome's. One limitation of our HUD display is that it doesn't sit
      // on top of horizontal scrollbars like Chrome's HUD does.
      var element = document.createElement("div");
      element.style.position = "fixed";
      element.style.bottom = "0px";
      // Keep this far enough to the right so that it doesn't collide with the "popups blocked" chrome HUD.
      element.style.right = "150px";
      element.style.height = "13px";
      element.style.maxWidth = "400px";
      element.style.minWidth = "150px";
      element.style.backgroundColor = "#ebebeb";
      element.style.fontSize = "11px";
      element.style.padding = "3px 3px 2px 3px";
      element.style.border = "1px solid #b3b3b3";
      element.style.borderRadius = "4px 4px 0 0";
      element.style.fontFamily = "Lucida Grande";
      element.style.textShadow = "0px 1px 2px #FFF";
      element.style.display = "none";

      document.body.appendChild(element);
      HUD._displayElement = element
      HUD.updatePageZoomLevel(currentZoomLevel);
    }
    return HUD._displayElement;
  },

  hide: function() {
    HUD.displayElement().style.display = "none";
  }
};

// Prevent our content script from being run on iframes -- only allow it to run on the top level DOM "window".
// TODO(philc): We don't want to process multiple keyhandlers etc. when embedded on a page containing IFrames.
// This should be revisited, because sometimes we *do* want to listen inside of the currently focused iframe.
var isIframe = (window.self != window.parent);
if (!isIframe) {
  initializePreDomReady();
  window.addEventListener("DOMContentLoaded", initializeOnDomReady);
}