]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Add command to click browser elements using markers
[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, 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 vim._run(name, options, reset)
143
144
145 helper_scrollByLinesX = (amount, {vim, count = 1}) ->
146 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
147 helper_scroll(vim, 'scrollBy', 'lines', ['left'],
148 [amount * distance * count * 5])
149
150 helper_scrollByLinesY = (amount, {vim, count = 1}) ->
151 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
152 helper_scroll(vim, 'scrollBy', 'lines', ['top'],
153 [amount * distance * count * 20])
154
155 helper_scrollByPagesY = (amount, type, {vim, count = 1}) ->
156 adjustment = prefs.get("scroll.#{type}_page_adjustment")
157 helper_scroll(vim, 'scrollBy', 'pages', ['top'],
158 [amount * count], ['clientHeight'], adjustment)
159
160 helper_scrollToX = (amount, {vim}) ->
161 helper_scroll(vim, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax'])
162 helper_mark_last_scroll_position(vim)
163
164 helper_scrollToY = (amount, {vim}) ->
165 helper_scroll(vim, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax'])
166 helper_mark_last_scroll_position(vim)
167
168 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
169 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
170 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
171 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
172 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
173 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
174 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
175 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
176 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
177 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
178 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
179 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
180
181 helper_mark_last_scroll_position = (vim) ->
182 keyStr = vim.options['scroll.last_position_mark']
183 vim._run('mark_scroll_position', {keyStr, notify: false})
184
185 commands.mark_scroll_position = ({vim}) ->
186 vim.enterMode('marks', (keyStr) -> vim._run('mark_scroll_position', {keyStr}))
187
188 commands.scroll_to_mark = ({vim}) ->
189 vim.enterMode('marks', (keyStr) ->
190 unless keyStr == vim.options['scroll.last_position_mark']
191 helper_mark_last_scroll_position(vim)
192 helper_scroll(vim, 'scrollTo', 'other', ['top', 'left'], keyStr,
193 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark')
194 )
195
196
197
198 commands.tab_new = ({vim}) ->
199 utils.nextTick(vim.window, ->
200 vim.window.BrowserOpenTab()
201 )
202
203 commands.tab_duplicate = ({vim}) ->
204 {gBrowser} = vim.window
205 utils.nextTick(vim.window, ->
206 gBrowser.duplicateTab(gBrowser.selectedTab)
207 )
208
209 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
210 tabs = gBrowser.visibleTabs
211 {selectedTab} = gBrowser
212
213 currentIndex = tabs.indexOf(selectedTab)
214 absoluteIndex = currentIndex + relativeIndex
215 numTabsTotal = tabs.length
216 numPinnedTabs = gBrowser._numPinnedTabs
217
218 [numTabs, min] = switch
219 when not pinnedSeparate then [numTabsTotal, 0]
220 when selectedTab.pinned then [numPinnedTabs, 0]
221 else [numTabsTotal - numPinnedTabs, numPinnedTabs]
222
223 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
224 # current direction.
225 if (relativeIndex < 0 and currentIndex == min) or
226 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
227 if absoluteIndex < min
228 absoluteIndex += numTabs
229 else if absoluteIndex >= min + numTabs
230 absoluteIndex -= numTabs
231
232 absoluteIndex = Math.max(min, absoluteIndex)
233 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
234
235 return absoluteIndex
236
237 helper_switch_tab = (direction, {vim, count = 1}) ->
238 {gBrowser} = vim.window
239 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
240 utils.nextTick(vim.window, ->
241 gBrowser.selectTabAtIndex(index)
242 )
243
244 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
245
246 commands.tab_select_next = helper_switch_tab.bind(null, +1)
247
248 helper_move_tab = (direction, {vim, count = 1}) ->
249 {gBrowser} = vim.window
250 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
251 utils.nextTick(vim.window, ->
252 gBrowser.moveTabTo(gBrowser.selectedTab, index)
253 )
254
255 commands.tab_move_backward = helper_move_tab.bind(null, -1)
256
257 commands.tab_move_forward = helper_move_tab.bind(null, +1)
258
259 commands.tab_move_to_window = ({vim}) ->
260 {gBrowser} = vim.window
261 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
262
263 commands.tab_select_first = ({vim, count = 1}) ->
264 utils.nextTick(vim.window, ->
265 vim.window.gBrowser.selectTabAtIndex(count - 1)
266 )
267
268 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
269 firstNonPinned = vim.window.gBrowser._numPinnedTabs
270 utils.nextTick(vim.window, ->
271 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
272 )
273
274 commands.tab_select_last = ({vim, count = 1}) ->
275 utils.nextTick(vim.window, ->
276 vim.window.gBrowser.selectTabAtIndex(-count)
277 )
278
279 commands.tab_toggle_pinned = ({vim}) ->
280 currentTab = vim.window.gBrowser.selectedTab
281 if currentTab.pinned
282 vim.window.gBrowser.unpinTab(currentTab)
283 else
284 vim.window.gBrowser.pinTab(currentTab)
285
286 commands.tab_close = ({vim, count = 1}) ->
287 {gBrowser} = vim.window
288 return if gBrowser.selectedTab.pinned
289 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
290 utils.nextTick(vim.window, ->
291 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
292 gBrowser.removeTab(tab)
293 return
294 )
295
296 commands.tab_restore = ({vim, count = 1}) ->
297 utils.nextTick(vim.window, ->
298 for index in [0...count] by 1
299 restoredTab = vim.window.undoCloseTab()
300 if not restoredTab and index == 0
301 vim.notify(translate('notification.tab_restore.none'))
302 break
303 return
304 )
305
306 commands.tab_restore_list = ({vim}) ->
307 {window} = vim
308 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
309 window, 'menuitem'
310 )
311 if fragment.childElementCount == 0
312 vim.notify(translate('notification.tab_restore.none'))
313 else
314 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
315
316 commands.tab_close_to_end = ({vim}) ->
317 {gBrowser} = vim.window
318 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
319
320 commands.tab_close_other = ({vim}) ->
321 {gBrowser} = vim.window
322 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
323
324
325
326 helper_follow = (name, vim, callback, count = null) ->
327 vim.markPageInteraction()
328
329 # Enter hints mode immediately, with an empty set of markers. The user might
330 # press keys before the `vim._run` callback is invoked. Those key presses
331 # should be handled in hints mode, not normal mode.
332 initialMarkers = []
333 storage = vim.enterMode('hints', initialMarkers, callback, count)
334
335 vim._run(name, null, ({wrappers, viewport}) ->
336 # The user might have exited hints mode (and perhaps even entered it again)
337 # before this callback is invoked. If so, `storage.markers` has been
338 # cleared, or set to a new value. Only proceed if it is unchanged.
339 return unless storage.markers == initialMarkers
340
341 if wrappers.length > 0
342 markers = hints.injectHints(vim.window, wrappers, viewport, vim.options)
343 storage.markers = markers
344 else
345 vim.notify(translate('notification.follow.none'))
346 vim.enterMode('normal')
347 )
348
349 helper_follow_clickable = ({inTab, inBackground}, {vim, count = 1}) ->
350 callback = (marker, timesLeft, keyStr) ->
351 {type, elementIndex} = marker.wrapper
352 isLast = (timesLeft == 1)
353 isLink = (type == 'link')
354
355 switch
356 when keyStr.startsWith(vim.options.hints_toggle_in_tab)
357 inTab = not inTab
358 when keyStr.startsWith(vim.options.hints_toggle_in_background)
359 inTab = true
360 inBackground = not inBackground
361 else
362 unless isLast
363 inTab = true
364 inBackground = true
365
366 inTab = false unless isLink
367
368 if type == 'text' or (isLink and not (inTab and inBackground))
369 isLast = true
370
371 vim._focusMarkerElement(elementIndex)
372
373 if inTab
374 utils.nextTick(vim.window, ->
375 utils.openTab(vim.window, marker.wrapper.href, {
376 inBackground
377 relatedToCurrent: true
378 })
379 )
380 else
381 vim._run('click_marker_element', {
382 elementIndex, type
383 preventTargetBlank: vim.options.prevent_target_blank
384 })
385
386 return not isLast
387
388 name = if inTab then 'follow_in_tab' else 'follow'
389 helper_follow(name, vim, callback, count)
390
391 # Follow links, focus text inputs and click buttons with hint markers.
392 commands.follow =
393 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
394
395 # Follow links in a new background tab with hint markers.
396 commands.follow_in_tab =
397 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
398
399 # Follow links in a new foreground tab with hint markers.
400 commands.follow_in_focused_tab =
401 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
402
403 # Follow links in a new window with hint markers.
404 commands.follow_in_window = ({vim}) ->
405 callback = (marker) ->
406 vim._focusMarkerElement(marker.wrapper.elementIndex)
407 vim.window.openLinkIn(marker.wrapper.href, 'window', {})
408 helper_follow('follow_in_tab', vim, callback)
409
410 # Like command_follow but multiple times.
411 commands.follow_multiple = (args) ->
412 args.count = Infinity
413 commands.follow(args)
414
415 # Copy the URL or text of a markable element to the system clipboard.
416 commands.follow_copy = ({vim}) ->
417 callback = (marker) ->
418 {elementIndex} = marker.wrapper
419 property = switch marker.wrapper.type
420 when 'link' then 'href'
421 when 'text' then 'value'
422 when 'contenteditable' then 'textContent'
423 vim._run('copy_marker_element', {elementIndex, property})
424 helper_follow('follow_copy', vim, callback)
425
426 # Focus element with hint markers.
427 commands.follow_focus = ({vim}) ->
428 callback = (marker) ->
429 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
430 return helper_follow('follow_focus', vim, callback)
431
432 commands.click_browser_element = ({vim}) ->
433 markerElements = []
434
435 filter = (element, getElementShape) ->
436 document = element.ownerDocument
437 unless element.tabIndex > -1 and
438 not (element.nodeName.endsWith('box') and
439 element.nodeName != 'checkbox') and
440 element.nodeName != 'tabs'
441 return
442 return unless shape = getElementShape(element)
443 length = markerElements.push(element)
444 return {type: 'clickable', semantic: true, shape, elementIndex: length - 1}
445
446 callback = (marker) ->
447 element = markerElements[marker.wrapper.elementIndex]
448 utils.focusElement(element)
449 utils.simulateClick(element)
450
451 {wrappers, viewport} =
452 hints.getMarkableElementsAndViewport(vim.window, filter)
453
454 if wrappers.length > 0
455 markers = hints.injectHints(vim.window, wrappers, viewport, {
456 hint_chars: vim.options.hint_chars
457 ui: true
458 })
459 vim.enterMode('hints', markers, callback)
460 else
461 vim.notify(translate('notification.follow.none'))
462
463 helper_follow_pattern = (type, {vim}) ->
464 options =
465 pattern_selector: vim.options.pattern_selector
466 pattern_attrs: vim.options.pattern_attrs
467 patterns: vim.options["#{type}_patterns"]
468 vim._run('follow_pattern', {type, options})
469
470 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
471
472 commands.follow_next = helper_follow_pattern.bind(null, 'next')
473
474 # Focus last focused or first text input.
475 commands.focus_text_input = ({vim, count}) ->
476 vim.markPageInteraction()
477 vim._run('focus_text_input', {count})
478
479
480
481 findStorage = {lastSearchString: ''}
482
483 helper_find = ({highlight, linksOnly = false}, {vim}) ->
484 helper_mark_last_scroll_position(vim)
485 findBar = vim.window.gBrowser.getFindBar()
486
487 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
488 findBar.startFind(mode)
489 utils.focusElement(findBar._findField, {select: true})
490
491 return if linksOnly
492 return unless highlightButton = findBar.getElement('highlight')
493 if highlightButton.checked != highlight
494 highlightButton.click()
495
496 # Open the find bar, making sure that hightlighting is off.
497 commands.find = helper_find.bind(null, {highlight: false})
498
499 # Open the find bar, making sure that hightlighting is on.
500 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
501
502 # Open the find bar in links only mode.
503 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
504
505 helper_find_again = (direction, {vim}) ->
506 findBar = vim.window.gBrowser.getFindBar()
507 if findStorage.lastSearchString.length == 0
508 vim.notify(translate('notification.find_again.none'))
509 return
510 helper_mark_last_scroll_position(vim)
511 findBar._findField.value = findStorage.lastSearchString
512 findBar.onFindAgainCommand(direction)
513 message = findBar._findStatusDesc.textContent
514 vim.notify(message) if message
515
516 commands.find_next = helper_find_again.bind(null, false)
517
518 commands.find_previous = helper_find_again.bind(null, true)
519
520
521
522 commands.window_new = ({vim}) ->
523 vim.window.OpenBrowserWindow()
524
525 commands.window_new_private = ({vim}) ->
526 vim.window.OpenBrowserWindow({private: true})
527
528 commands.enter_mode_ignore = ({vim}) ->
529 vim.enterMode('ignore')
530
531 # Quote next keypress (pass it through to the page).
532 commands.quote = ({vim, count = 1}) ->
533 vim.enterMode('ignore', count)
534
535 commands.enter_reader_view = ({vim}) ->
536 button = vim.window.document.getElementById('reader-mode-button')
537 if not button?.hidden
538 button.click()
539 else
540 vim.notify(translate('notification.enter_reader_view.none'))
541
542 # Display the Help Dialog.
543 commands.help = ({vim}) ->
544 help.injectHelp(vim.window, vim._parent)
545
546 # Open and focus the Developer Toolbar.
547 commands.dev = ({vim}) ->
548 vim.window.DeveloperToolbar.show(true) # `true` to focus.
549
550 commands.esc = ({vim}) ->
551 vim._run('esc')
552 utils.blurActiveBrowserElement(vim)
553 help.removeHelp(vim.window)
554 vim.window.DeveloperToolbar.hide()
555 vim.window.gBrowser.getFindBar().close()
556 # TODO: Remove when Tab Groups have been removed.
557 vim.window.TabView?.hide()
558 hints.removeHints(vim.window) # Better safe than sorry.
559
560
561
562 module.exports = {
563 commands
564 findStorage
565 }
Imprint / Impressum