]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Recognozie more ARIA roles as clickable
[VimFx.git] / extension / lib / commands.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014, 2015.
4 # Copyright Wang Zhuochun 2013, 2014.
5 #
6 # This file is part of VimFx.
7 #
8 # VimFx is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # VimFx is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
20 ###
21
22 # This file defines all Normal mode commands. Commands that need to interact
23 # with web page content do so by running `vim._run(name)`, which invokes `name`
24 # in commands-frame.coffee.
25
26 # NOTE: Most tab related commands need to do their actual tab manipulations in
27 # the next tick (`utils.nextTick`) to work around bug 1200334.
28
29 help = require('./help')
30 hints = require('./hints')
31 prefs = require('./prefs')
32 translate = require('./l10n')
33 utils = require('./utils')
34
35 commands = {}
36
37
38
39 commands.focus_location_bar = ({vim}) ->
40 # This function works even if the Address Bar has been removed.
41 vim.window.focusAndSelectUrlBar()
42
43 commands.focus_search_bar = ({vim, count}) ->
44 # The `.webSearch()` method opens a search engine in a tab if the Search Bar
45 # has been removed. Therefore we first check if it exists.
46 if vim.window.BrowserSearch.searchBar
47 vim.window.BrowserSearch.webSearch()
48
49 helper_paste_and_go = (props, {vim}) ->
50 {gURLBar} = vim.window
51 gURLBar.value = vim.window.readFromClipboard()
52 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
53
54 commands.paste_and_go = helper_paste_and_go.bind(null, null)
55
56 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
57
58 commands.copy_current_url = ({vim}) ->
59 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
60 vim.notify(translate('notification.copy_current_url'))
61
62 commands.go_up_path = ({vim, count}) ->
63 vim._run('go_up_path', {count})
64
65 # Go up to root of the URL hierarchy.
66 commands.go_to_root = ({vim}) ->
67 vim._run('go_to_root')
68
69 commands.go_home = ({vim}) ->
70 vim.window.BrowserHome()
71
72 helper_go_history = (direction, {vim, count = 1}) ->
73 {SessionStore, gBrowser} = vim.window
74
75 # TODO: When Firefox 43 is released, only use the `.getSessionHistory`
76 # version and bump the minimum Firefox version.
77 if SessionStore.getSessionHistory
78 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
79 {index} = sessionHistory
80 newIndex = index + count * (if direction == 'back' then -1 else 1)
81 newIndex = Math.max(newIndex, 0)
82 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
83 if newIndex == index
84 vim.notify(translate("notification.history_#{direction}.limit"))
85 else
86 gBrowser.gotoIndex(newIndex)
87 )
88 else
89 # Until then, fall back to a no-count version.
90 if direction == 'back' then gBrowser.goBack() else gBrowser.goForward()
91
92 commands.history_back = helper_go_history.bind(null, 'back')
93
94 commands.history_forward = helper_go_history.bind(null, 'forward')
95
96 commands.history_list = ({vim}) ->
97 menu = vim.window.document.getElementById('backForwardMenu')
98 utils.openPopup(menu)
99 vim.notify(translate('notification.history_list.none')) unless menu.open
100
101 commands.reload = ({vim}) ->
102 vim.window.BrowserReload()
103
104 commands.reload_force = ({vim}) ->
105 vim.window.BrowserReloadSkipCache()
106
107 commands.reload_all = ({vim}) ->
108 vim.window.gBrowser.reloadAllTabs()
109
110 commands.reload_all_force = ({vim}) ->
111 for tab in vim.window.gBrowser.visibleTabs
112 gBrowser = tab.linkedBrowser
113 consts = gBrowser.webNavigation
114 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
115 gBrowser.reload(flags)
116 return
117
118 commands.stop = ({vim}) ->
119 vim.window.BrowserStop()
120
121 commands.stop_all = ({vim}) ->
122 for tab in vim.window.gBrowser.visibleTabs
123 tab.linkedBrowser.stop()
124 return
125
126
127
128 helper_scroll = (vim, uiEvent, args...) ->
129 [
130 method, type, directions, amounts
131 properties = null, adjustment = 0, name = 'scroll'
132 ] = args
133 options = {
134 method, type, directions, amounts, properties, adjustment
135 smooth: (prefs.root.get('general.smoothScroll') and
136 prefs.root.get("general.smoothScroll.#{type}"))
137 }
138 reset = prefs.root.tmp(
139 'layout.css.scroll-behavior.spring-constant',
140 vim.options["smoothScroll.#{type}.spring-constant"]
141 )
142
143 if uiEvent
144 activeElement = utils.getActiveElement(vim.window)
145 if vim._state.scrollableElements.has(activeElement)
146 utils.scroll(activeElement, options)
147 reset()
148 return
149
150 vim._run(name, options, reset)
151
152
153 helper_scrollByLinesX = (amount, {vim, uiEvent, count = 1}) ->
154 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
155 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['left'],
156 [amount * distance * count * 5])
157
158 helper_scrollByLinesY = (amount, {vim, uiEvent, count = 1}) ->
159 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
160 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['top'],
161 [amount * distance * count * 20])
162
163 helper_scrollByPagesY = (amount, type, {vim, uiEvent, count = 1}) ->
164 adjustment = prefs.get("scroll.#{type}_page_adjustment")
165 helper_scroll(vim, uiEvent, 'scrollBy', 'pages', ['top'],
166 [amount * count], ['clientHeight'], adjustment)
167
168 helper_scrollToX = (amount, {vim, uiEvent}) ->
169 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['left'],
170 [amount], ['scrollLeftMax'])
171 helper_mark_last_scroll_position(vim)
172
173 helper_scrollToY = (amount, {vim, uiEvent}) ->
174 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['top'],
175 [amount], ['scrollTopMax'])
176 helper_mark_last_scroll_position(vim)
177
178 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
179 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
180 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
181 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
182 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
183 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
184 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
185 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
186 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
187 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
188 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
189 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
190
191 helper_mark_last_scroll_position = (vim) ->
192 keyStr = vim.options['scroll.last_position_mark']
193 vim._run('mark_scroll_position', {keyStr, notify: false})
194
195 commands.mark_scroll_position = ({vim}) ->
196 vim.enterMode('marks', (keyStr) -> vim._run('mark_scroll_position', {keyStr}))
197
198 commands.scroll_to_mark = ({vim}) ->
199 vim.enterMode('marks', (keyStr) ->
200 unless keyStr == vim.options['scroll.last_position_mark']
201 helper_mark_last_scroll_position(vim)
202 helper_scroll(vim, 'scrollTo', 'other', ['top', 'left'], keyStr,
203 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark')
204 )
205
206
207
208 commands.tab_new = ({vim}) ->
209 utils.nextTick(vim.window, ->
210 vim.window.BrowserOpenTab()
211 )
212
213 commands.tab_duplicate = ({vim}) ->
214 {gBrowser} = vim.window
215 utils.nextTick(vim.window, ->
216 gBrowser.duplicateTab(gBrowser.selectedTab)
217 )
218
219 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
220 tabs = gBrowser.visibleTabs
221 {selectedTab} = gBrowser
222
223 currentIndex = tabs.indexOf(selectedTab)
224 absoluteIndex = currentIndex + relativeIndex
225 numTabsTotal = tabs.length
226 numPinnedTabs = gBrowser._numPinnedTabs
227
228 [numTabs, min] = switch
229 when not pinnedSeparate then [numTabsTotal, 0]
230 when selectedTab.pinned then [numPinnedTabs, 0]
231 else [numTabsTotal - numPinnedTabs, numPinnedTabs]
232
233 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
234 # current direction.
235 if (relativeIndex < 0 and currentIndex == min) or
236 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
237 if absoluteIndex < min
238 absoluteIndex += numTabs
239 else if absoluteIndex >= min + numTabs
240 absoluteIndex -= numTabs
241
242 absoluteIndex = Math.max(min, absoluteIndex)
243 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
244
245 return absoluteIndex
246
247 helper_switch_tab = (direction, {vim, count = 1}) ->
248 {gBrowser} = vim.window
249 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
250 utils.nextTick(vim.window, ->
251 gBrowser.selectTabAtIndex(index)
252 )
253
254 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
255
256 commands.tab_select_next = helper_switch_tab.bind(null, +1)
257
258 helper_move_tab = (direction, {vim, count = 1}) ->
259 {gBrowser} = vim.window
260 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
261 utils.nextTick(vim.window, ->
262 gBrowser.moveTabTo(gBrowser.selectedTab, index)
263 )
264
265 commands.tab_move_backward = helper_move_tab.bind(null, -1)
266
267 commands.tab_move_forward = helper_move_tab.bind(null, +1)
268
269 commands.tab_move_to_window = ({vim}) ->
270 {gBrowser} = vim.window
271 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
272
273 commands.tab_select_first = ({vim, count = 1}) ->
274 utils.nextTick(vim.window, ->
275 vim.window.gBrowser.selectTabAtIndex(count - 1)
276 )
277
278 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
279 firstNonPinned = vim.window.gBrowser._numPinnedTabs
280 utils.nextTick(vim.window, ->
281 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
282 )
283
284 commands.tab_select_last = ({vim, count = 1}) ->
285 utils.nextTick(vim.window, ->
286 vim.window.gBrowser.selectTabAtIndex(-count)
287 )
288
289 commands.tab_toggle_pinned = ({vim}) ->
290 currentTab = vim.window.gBrowser.selectedTab
291 if currentTab.pinned
292 vim.window.gBrowser.unpinTab(currentTab)
293 else
294 vim.window.gBrowser.pinTab(currentTab)
295
296 commands.tab_close = ({vim, count = 1}) ->
297 {gBrowser} = vim.window
298 return if gBrowser.selectedTab.pinned
299 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
300 utils.nextTick(vim.window, ->
301 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
302 gBrowser.removeTab(tab)
303 return
304 )
305
306 commands.tab_restore = ({vim, count = 1}) ->
307 utils.nextTick(vim.window, ->
308 for index in [0...count] by 1
309 restoredTab = vim.window.undoCloseTab()
310 if not restoredTab and index == 0
311 vim.notify(translate('notification.tab_restore.none'))
312 break
313 return
314 )
315
316 commands.tab_restore_list = ({vim}) ->
317 {window} = vim
318 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
319 window, 'menuitem'
320 )
321 if fragment.childElementCount == 0
322 vim.notify(translate('notification.tab_restore.none'))
323 else
324 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
325
326 commands.tab_close_to_end = ({vim}) ->
327 {gBrowser} = vim.window
328 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
329
330 commands.tab_close_other = ({vim}) ->
331 {gBrowser} = vim.window
332 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
333
334
335
336 helper_follow = (name, vim, callback, count = null) ->
337 vim.markPageInteraction()
338
339 # Enter hints mode immediately, with an empty set of markers. The user might
340 # press keys before the `vim._run` callback is invoked. Those key presses
341 # should be handled in hints mode, not normal mode.
342 initialMarkers = []
343 storage = vim.enterMode('hints', initialMarkers, callback, count)
344
345 vim._run(name, null, ({wrappers, viewport}) ->
346 # The user might have exited hints mode (and perhaps even entered it again)
347 # before this callback is invoked. If so, `storage.markers` has been
348 # cleared, or set to a new value. Only proceed if it is unchanged.
349 return unless storage.markers == initialMarkers
350
351 if wrappers.length > 0
352 markers = hints.injectHints(vim.window, wrappers, viewport, vim.options)
353 storage.markers = markers
354 else
355 vim.notify(translate('notification.follow.none'))
356 vim.enterMode('normal')
357 )
358
359 helper_follow_clickable = ({inTab, inBackground}, {vim, count = 1}) ->
360 callback = (marker, timesLeft, keyStr) ->
361 {type, elementIndex} = marker.wrapper
362 isLast = (timesLeft == 1)
363 isLink = (type == 'link')
364
365 switch
366 when keyStr.startsWith(vim.options.hints_toggle_in_tab)
367 inTab = not inTab
368 when keyStr.startsWith(vim.options.hints_toggle_in_background)
369 inTab = true
370 inBackground = not inBackground
371 else
372 unless isLast
373 inTab = true
374 inBackground = true
375
376 inTab = false unless isLink
377
378 if type == 'text' or (isLink and not (inTab and inBackground))
379 isLast = true
380
381 vim._focusMarkerElement(elementIndex)
382
383 if inTab
384 utils.nextTick(vim.window, ->
385 utils.openTab(vim.window, marker.wrapper.href, {
386 inBackground
387 relatedToCurrent: true
388 })
389 )
390 else
391 vim._run('click_marker_element', {
392 elementIndex, type
393 preventTargetBlank: vim.options.prevent_target_blank
394 })
395
396 return not isLast
397
398 name = if inTab then 'follow_in_tab' else 'follow'
399 helper_follow(name, vim, callback, count)
400
401 # Follow links, focus text inputs and click buttons with hint markers.
402 commands.follow =
403 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
404
405 # Follow links in a new background tab with hint markers.
406 commands.follow_in_tab =
407 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
408
409 # Follow links in a new foreground tab with hint markers.
410 commands.follow_in_focused_tab =
411 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
412
413 # Follow links in a new window with hint markers.
414 commands.follow_in_window = ({vim}) ->
415 callback = (marker) ->
416 vim._focusMarkerElement(marker.wrapper.elementIndex)
417 vim.window.openLinkIn(marker.wrapper.href, 'window', {})
418 helper_follow('follow_in_tab', vim, callback)
419
420 # Like command_follow but multiple times.
421 commands.follow_multiple = (args) ->
422 args.count = Infinity
423 commands.follow(args)
424
425 # Copy the URL or text of a markable element to the system clipboard.
426 commands.follow_copy = ({vim}) ->
427 callback = (marker) ->
428 {elementIndex} = marker.wrapper
429 property = switch marker.wrapper.type
430 when 'link' then 'href'
431 when 'text' then 'value'
432 when 'contenteditable' then 'textContent'
433 vim._run('copy_marker_element', {elementIndex, property})
434 helper_follow('follow_copy', vim, callback)
435
436 # Focus element with hint markers.
437 commands.follow_focus = ({vim}) ->
438 callback = (marker) ->
439 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
440 return helper_follow('follow_focus', vim, callback)
441
442 commands.click_browser_element = ({vim}) ->
443 markerElements = []
444
445 filter = (element, getElementShape) ->
446 document = element.ownerDocument
447 type = switch
448 when vim._state.scrollableElements.has(element)
449 'scrollable'
450 when element.tabIndex > -1 and
451 not (element.nodeName.endsWith('box') and
452 element.nodeName != 'checkbox') and
453 element.nodeName != 'tabs'
454 'clickable'
455 return unless type
456 return unless shape = getElementShape(element)
457 length = markerElements.push(element)
458 return {type, semantic: true, shape, elementIndex: length - 1}
459
460 callback = (marker) ->
461 element = markerElements[marker.wrapper.elementIndex]
462 switch marker.wrapper.type
463 when 'scrollable'
464 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
465 when 'clickable'
466 utils.focusElement(element)
467 utils.simulateClick(element)
468
469 {wrappers, viewport} =
470 hints.getMarkableElementsAndViewport(vim.window, filter)
471
472 if wrappers.length > 0
473 markers = hints.injectHints(vim.window, wrappers, viewport, {
474 hint_chars: vim.options.hint_chars
475 ui: true
476 })
477 vim.enterMode('hints', markers, callback)
478 else
479 vim.notify(translate('notification.follow.none'))
480
481 helper_follow_pattern = (type, {vim}) ->
482 options =
483 pattern_selector: vim.options.pattern_selector
484 pattern_attrs: vim.options.pattern_attrs
485 patterns: vim.options["#{type}_patterns"]
486 vim._run('follow_pattern', {type, options})
487
488 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
489
490 commands.follow_next = helper_follow_pattern.bind(null, 'next')
491
492 # Focus last focused or first text input.
493 commands.focus_text_input = ({vim, count}) ->
494 vim.markPageInteraction()
495 vim._run('focus_text_input', {count})
496
497
498
499 findStorage = {lastSearchString: ''}
500
501 helper_find = ({highlight, linksOnly = false}, {vim}) ->
502 helper_mark_last_scroll_position(vim)
503 findBar = vim.window.gBrowser.getFindBar()
504
505 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
506 findBar.startFind(mode)
507 utils.focusElement(findBar._findField, {select: true})
508
509 return if linksOnly
510 return unless highlightButton = findBar.getElement('highlight')
511 if highlightButton.checked != highlight
512 highlightButton.click()
513
514 # Open the find bar, making sure that hightlighting is off.
515 commands.find = helper_find.bind(null, {highlight: false})
516
517 # Open the find bar, making sure that hightlighting is on.
518 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
519
520 # Open the find bar in links only mode.
521 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
522
523 helper_find_again = (direction, {vim}) ->
524 findBar = vim.window.gBrowser.getFindBar()
525 if findStorage.lastSearchString.length == 0
526 vim.notify(translate('notification.find_again.none'))
527 return
528 helper_mark_last_scroll_position(vim)
529 findBar._findField.value = findStorage.lastSearchString
530 findBar.onFindAgainCommand(direction)
531 message = findBar._findStatusDesc.textContent
532 vim.notify(message) if message
533
534 commands.find_next = helper_find_again.bind(null, false)
535
536 commands.find_previous = helper_find_again.bind(null, true)
537
538
539
540 commands.window_new = ({vim}) ->
541 vim.window.OpenBrowserWindow()
542
543 commands.window_new_private = ({vim}) ->
544 vim.window.OpenBrowserWindow({private: true})
545
546 commands.enter_mode_ignore = ({vim}) ->
547 vim.enterMode('ignore')
548
549 # Quote next keypress (pass it through to the page).
550 commands.quote = ({vim, count = 1}) ->
551 vim.enterMode('ignore', count)
552
553 commands.enter_reader_view = ({vim}) ->
554 button = vim.window.document.getElementById('reader-mode-button')
555 if not button?.hidden
556 button.click()
557 else
558 vim.notify(translate('notification.enter_reader_view.none'))
559
560 # Display the Help Dialog.
561 commands.help = ({vim}) ->
562 help.injectHelp(vim.window, vim._parent)
563
564 # Open and focus the Developer Toolbar.
565 commands.dev = ({vim}) ->
566 vim.window.DeveloperToolbar.show(true) # `true` to focus.
567
568 commands.esc = ({vim}) ->
569 vim._run('esc')
570 utils.blurActiveBrowserElement(vim)
571 help.removeHelp(vim.window)
572 vim.window.DeveloperToolbar.hide()
573 vim.window.gBrowser.getFindBar().close()
574 # TODO: Remove when Tab Groups have been removed.
575 vim.window.TabView?.hide()
576 hints.removeHints(vim.window) # Better safe than sorry.
577
578
579
580 module.exports = {
581 commands
582 findStorage
583 }
Imprint / Impressum