1 # This file defines all Normal mode commands. Commands that need to interact
2 # with web page content do so by running `vim._run(name)`, which invokes `name`
3 # in commands-frame.coffee.
5 # NOTE: Most tab related commands need to do their actual tab manipulations in
6 # the next tick (`utils.nextTick`) to work around bug 1200334.
8 config = require('./config')
9 help = require('./help')
10 markableElements = require('./markable-elements')
11 MarkerContainer = require('./marker-container')
12 parsePrefs = require('./parse-prefs')
13 prefs = require('./prefs')
14 SelectionManager = require('./selection')
15 translate = require('./translate')
16 utils = require('./utils')
17 viewportUtils = require('./viewport')
19 {PlacesUIUtils} = Cu.import('resource:///modules/PlacesUIUtils.jsm', {})
20 {PrivateBrowsingUtils} =
21 Cu.import('resource://gre/modules/PrivateBrowsingUtils.jsm', {})
22 {E10SUtils} = Cu.import('resource://gre/modules/E10SUtils.jsm', {})
23 {FORWARD, BACKWARD} = SelectionManager
25 READER_VIEW_PREFIX = 'about:reader?url='
26 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
32 commands.focus_location_bar = ({vim}) ->
33 vim.window.focusAndSelectUrlBar()
35 commands.focus_search_bar = ({vim, count}) ->
36 # The `.webSearch()` method opens a search engine in a tab if the search bar
37 # has been removed. Therefore we first check if it exists.
38 if vim.window.BrowserSearch.searchBar
39 vim.window.BrowserSearch.webSearch()
41 vim.notify(translate('notification.focus_search_bar.none'))
43 helper_paste_and_go = (props, {vim}) ->
44 {gURLBar} = vim.window
45 gURLBar.value = vim.window.readFromClipboard()
46 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
48 commands.paste_and_go = helper_paste_and_go.bind(null, null)
50 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
52 commands.copy_current_url = ({vim}) ->
53 url = vim.window.gBrowser.currentURI.spec
55 if url.startsWith(READER_VIEW_PREFIX)
56 decodeURIComponent(url[READER_VIEW_PREFIX.length..])
59 utils.writeToClipboard(adjustedUrl)
60 vim.notify(translate('notification.copy_current_url.success'))
62 commands.go_up_path = ({vim, count}) ->
63 vim._run('go_up_path', {count})
65 commands.go_to_root = ({vim}) ->
66 vim._run('go_to_root')
68 commands.go_home = ({vim}) ->
69 vim.window.BrowserHome()
71 helper_go_history = (direction, {vim, count = 1}) ->
73 {SessionStore, gBrowser} = window
75 if (direction == 'back' and not gBrowser.canGoBack) or
76 (direction == 'forward' and not gBrowser.canGoForward)
77 vim.notify(translate("notification.history_#{direction}.limit"))
80 # `SessionStore.getSessionHistory()` (used below to support counts) starts
81 # lots of asynchronous tasks internally, which is a bit unreliable, it has
82 # turned out. The primary use of the `history_back` and `history_forward`
83 # commands is to go _one_ step back or forward, though, so those cases are
84 # optimized to use more reliable ways of going back and forward. Also, some
85 # extensions override the following functions, so calling them also gives
86 # better interoperability.
88 if direction == 'back'
91 window.BrowserForward()
94 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
95 {index} = sessionHistory
96 newIndex = index + count * (if direction == 'back' then -1 else 1)
97 newIndex = Math.max(newIndex, 0)
98 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
99 gBrowser.gotoIndex(newIndex)
102 commands.history_back = helper_go_history.bind(null, 'back')
104 commands.history_forward = helper_go_history.bind(null, 'forward')
106 commands.history_list = ({vim}) ->
107 menu = vim.window.document.getElementById('backForwardMenu')
108 utils.openPopup(menu)
109 if menu.childElementCount == 0
110 vim.notify(translate('notification.history_list.none'))
112 commands.reload = ({vim}) ->
113 vim.window.BrowserReload()
115 commands.reload_force = ({vim}) ->
116 vim.window.BrowserReloadSkipCache()
118 commands.reload_all = ({vim}) ->
119 vim.window.gBrowser.reloadAllTabs()
121 commands.reload_all_force = ({vim}) ->
122 for tab in vim.window.gBrowser.visibleTabs
123 gBrowser = tab.linkedBrowser
124 consts = gBrowser.webNavigation
125 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
126 gBrowser.reload(flags)
129 commands.stop = ({vim}) ->
130 vim.window.BrowserStop()
132 commands.stop_all = ({vim}) ->
133 for tab in vim.window.gBrowser.visibleTabs
134 tab.linkedBrowser.stop()
145 helper_scroll = (vim, event, args...) ->
147 method, type, directions, amounts
148 properties = null, adjustment = 0, name = 'scroll', extra = {}
151 elapsed = event.timeStamp - scrollData.lastRepeat
153 if event.repeat and elapsed < vim.options['scroll.repeat_timeout']
156 scrollData.lastRepeat = event.timeStamp
159 method, type, directions, amounts, properties, adjustment, extra
161 prefs.root.get('general.smoothScroll') and
162 prefs.root.get("general.smoothScroll.#{type}")
166 # Temporarily set Firefox’s “spring constant” pref to get the desired smooth
167 # scrolling speed. Reset it `reset_timeout` milliseconds after the last
168 # scrolling command was invoked.
169 scrollData.nonce = nonce = {}
170 scrollData.springConstant ?= prefs.root.get(SPRING_CONSTANT_PREF)
172 SPRING_CONSTANT_PREF,
173 vim.options["smoothScroll.#{type}.spring-constant"]
176 vim.window.setTimeout((->
177 return unless scrollData.nonce == nonce
178 prefs.root.set(SPRING_CONSTANT_PREF, scrollData.springConstant)
179 scrollData.nonce = null
180 scrollData.springConstant = null
181 ), vim.options['scroll.reset_timeout'])
183 {isUIEvent = vim.isUIEvent(event)} = extra
184 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
185 if isUIEvent or helpScroll
186 activeElement = helpScroll or utils.getActiveElement(vim.window)
187 if vim._state.scrollableElements.has(activeElement) or helpScroll
188 viewportUtils.scroll(activeElement, options)
192 vim._run(name, options, reset)
195 helper_scrollByLinesX = (amount, {vim, event, count = 1}) ->
196 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
197 boost = if event.repeat then vim.options['scroll.horizontal_boost'] else 1
199 vim, event, 'scrollBy', 'lines', ['left'],
200 [amount * distance * boost * count * 5]
203 helper_scrollByLinesY = (amount, {vim, event, count = 1}) ->
204 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
205 boost = if event.repeat then vim.options['scroll.vertical_boost'] else 1
207 vim, event, 'scrollBy', 'lines', ['top'],
208 [amount * distance * boost * count * 20]
211 helper_scrollByPagesY = (amount, type, {vim, event, count = 1}) ->
212 adjustment = vim.options["scroll.#{type}_page_adjustment"]
214 vim, event, 'scrollBy', 'pages', ['top'], [amount * count],
215 ['clientHeight'], adjustment
218 helper_scrollToX = (amount, {vim, event}) ->
219 helper_mark_last_scroll_position(vim)
221 vim, event, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
224 helper_scrollToY = (amount, {vim, event}) ->
225 helper_mark_last_scroll_position(vim)
227 vim, event, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
230 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
231 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
232 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
233 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
234 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
235 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
236 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
237 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
238 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
239 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
240 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
241 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
243 helper_mark_last_scroll_position = (vim) ->
244 keyStr = vim.options['scroll.last_position_mark']
245 vim._run('mark_scroll_position', {keyStr, notify: false, addToJumpList: true})
247 commands.mark_scroll_position = ({vim}) ->
248 vim._enterMode('marks', (keyStr) ->
249 vim._run('mark_scroll_position', {keyStr})
251 vim.notify(translate('notification.mark_scroll_position.enter'))
253 commands.scroll_to_mark = ({vim, event}) ->
254 vim._enterMode('marks', (keyStr) ->
255 lastPositionMark = vim.options['scroll.last_position_mark']
257 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
258 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_mark'
259 {keyStr, lastPositionMark, isUIEvent: false}
261 vim.hideNotification()
263 vim.notify(translate('notification.scroll_to_mark.enter'))
265 helper_scroll_to_position = (direction, {vim, event, count = 1}) ->
266 lastPositionMark = vim.options['scroll.last_position_mark']
268 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
269 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_position'
270 {count, direction, lastPositionMark, isUIEvent: false}
273 commands.scroll_to_previous_position =
274 helper_scroll_to_position.bind(null, 'previous')
276 commands.scroll_to_next_position =
277 helper_scroll_to_position.bind(null, 'next')
281 commands.tab_new = ({vim}) ->
282 utils.nextTick(vim.window, ->
283 vim.window.BrowserOpenTab()
286 commands.tab_new_after_current = ({vim}) ->
288 newTabPosition = window.gBrowser.selectedTab._tPos + 1
289 utils.nextTick(window, ->
290 utils.listenOnce(window, 'TabOpen', (event) ->
291 newTab = event.originalTarget
292 window.gBrowser.moveTabTo(newTab, newTabPosition)
294 window.BrowserOpenTab()
297 commands.tab_duplicate = ({vim}) ->
298 {gBrowser} = vim.window
299 utils.nextTick(vim.window, ->
300 gBrowser.duplicateTab(gBrowser.selectedTab)
303 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
304 tabs = gBrowser.visibleTabs
305 {selectedTab} = gBrowser
307 currentIndex = tabs.indexOf(selectedTab)
308 absoluteIndex = currentIndex + relativeIndex
309 numTabsTotal = tabs.length
310 numPinnedTabs = gBrowser._numPinnedTabs
312 [numTabs, min] = switch
313 when not pinnedSeparate
315 when selectedTab.pinned
318 [numTabsTotal - numPinnedTabs, numPinnedTabs]
320 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
322 if (relativeIndex < 0 and currentIndex == min) or
323 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
324 if absoluteIndex < min
325 absoluteIndex += numTabs
326 else if absoluteIndex >= min + numTabs
327 absoluteIndex -= numTabs
329 absoluteIndex = Math.max(min, absoluteIndex)
330 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
334 helper_switch_tab = (direction, {vim, count = 1}) ->
335 {gBrowser} = vim.window
336 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
337 utils.nextTick(vim.window, ->
338 gBrowser.selectTabAtIndex(index)
341 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
343 commands.tab_select_next = helper_switch_tab.bind(null, +1)
345 helper_is_visited = (tab) ->
346 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
348 commands.tab_select_most_recent = ({vim, count = 1}) ->
349 {gBrowser} = vim.window
351 Array.prototype.filter.call(
353 (tab) -> not tab.closing and helper_is_visited(tab)
354 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
355 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
357 gBrowser.selectedTab = tab
359 vim.notify(translate('notification.tab_select_most_recent.none'))
361 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
362 {gBrowser} = vim.window
364 Array.prototype.filter.call(
366 (tab) -> not tab.closing and not helper_is_visited(tab)
367 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
368 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
370 gBrowser.selectedTab = tab
372 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
374 helper_move_tab = (direction, {vim, count = 1}) ->
375 {gBrowser} = vim.window
376 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
377 utils.nextTick(vim.window, ->
378 gBrowser.moveTabTo(gBrowser.selectedTab, index)
381 commands.tab_move_backward = helper_move_tab.bind(null, -1)
383 commands.tab_move_forward = helper_move_tab.bind(null, +1)
385 commands.tab_move_to_window = ({vim}) ->
386 {gBrowser} = vim.window
387 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
389 commands.tab_select_first = ({vim, count = 1}) ->
390 utils.nextTick(vim.window, ->
391 vim.window.gBrowser.selectTabAtIndex(count - 1)
394 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
395 firstNonPinned = vim.window.gBrowser._numPinnedTabs
396 utils.nextTick(vim.window, ->
397 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
400 commands.tab_select_last = ({vim, count = 1}) ->
401 utils.nextTick(vim.window, ->
402 vim.window.gBrowser.selectTabAtIndex(-count)
405 commands.tab_toggle_pinned = ({vim}) ->
406 currentTab = vim.window.gBrowser.selectedTab
408 vim.window.gBrowser.unpinTab(currentTab)
410 vim.window.gBrowser.pinTab(currentTab)
412 commands.tab_close = ({vim, count = 1}) ->
413 {gBrowser} = vim.window
414 return if gBrowser.selectedTab.pinned
415 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
416 utils.nextTick(vim.window, ->
417 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
418 gBrowser.removeTab(tab)
422 commands.tab_restore = ({vim, count = 1}) ->
423 utils.nextTick(vim.window, ->
424 for index in [0...count] by 1
425 restoredTab = vim.window.undoCloseTab()
426 if not restoredTab and index == 0
427 vim.notify(translate('notification.tab_restore.none'))
432 commands.tab_restore_list = ({vim}) ->
434 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
437 if fragment.childElementCount == 0
438 vim.notify(translate('notification.tab_restore.none'))
440 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
442 commands.tab_close_to_end = ({vim}) ->
443 {gBrowser} = vim.window
444 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
446 commands.tab_close_other = ({vim}) ->
447 {gBrowser} = vim.window
448 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
452 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
454 vim.markPageInteraction()
455 help.removeHelp(window)
457 markerContainer = new MarkerContainer({
459 hintChars: vim.options['hints.chars']
460 getComplementaryWrappers: (callback) ->
461 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
462 # `markerContainer.container` is `null`ed out when leaving Hints mode.
463 # If this callback is called after we’ve left Hints mode (and perhaps
464 # even entered it again), simply discard the result.
465 return unless markerContainer.container
466 if wrappers.length == 0
467 vim.notify(translate('notification.follow.none'))
468 callback({wrappers, viewport})
471 MarkerContainer.remove(window) # Better safe than sorry.
472 window.gBrowser.selectedBrowser.parentNode.appendChild(
473 markerContainer.container
476 chooseCallback = (marker, timesLeft, keyStr) ->
478 {type, href = null, elementIndex} = marker.wrapper
479 return callbackOverride({type, href, id: elementIndex, timesLeft})
481 return callback(marker, timesLeft, keyStr)
483 # Enter Hints mode immediately, with an empty set of markers. The user might
484 # press keys before any hints have been generated. Those keypresses should be
485 # handled in Hints mode, not Normal mode.
486 vim._enterMode('hints', {
487 markerContainer, count
488 callback: chooseCallback
489 matchText: vim.options['hints.match_text']
490 sleep: vim.options['hints.sleep']
493 injectHints = ({wrappers, viewport, pass}) ->
494 # See `getComplementaryWrappers` above.
495 return unless markerContainer.container
497 if wrappers.length == 0
498 if pass in ['single', 'second'] and markerContainer.markers.length == 0
499 vim.notify(translate('notification.follow.none'))
500 vim._enterMode('normal')
502 markerContainer.injectHints(wrappers, viewport, pass)
505 vim._run(name, {pass: 'second'}, injectHints)
507 vim._run(name, {pass: 'auto'}, injectHints)
509 helper_follow_clickable = (options, args) ->
512 callback = (marker, timesLeft, keyStr) ->
513 {inTab, inBackground} = options
514 {type, elementIndex} = marker.wrapper
515 isLast = (timesLeft == 1)
516 isLink = (type == 'link')
520 when keyStr.startsWith(vim.options['hints.toggle_in_tab'])
522 when keyStr.startsWith(vim.options['hints.toggle_in_background'])
524 inBackground = not inBackground
530 inTab = false unless isLink
532 if type == 'text' or (isLink and not (inTab and inBackground))
535 vim._focusMarkerElement(elementIndex)
538 contentAreaClick = (json, browser) ->
539 # Note this function is shortened from the same-named one currently in
540 # mozilla-central/browser/actors/ClickHandlerParent.jsm. Keep in sync!
541 window = browser.ownerGlobal
543 charset: browser.characterSet,
544 referrerInfo: E10SUtils.deserializeReferrerInfo(json.referrerInfo),
545 allowMixedContent: json.allowMixedContent,
546 isContentWindowPrivate: json.isContentWindowPrivate,
547 originPrincipal: json.originPrincipal,
548 originStoragePrincipal: json.originStoragePrincipal,
549 triggeringPrincipal: json.triggeringPrincipal,
550 csp: if json.csp then E10SUtils.deserializeCSP(json.csp) else null,
551 frameOuterWindowID: json.frameOuterWindowID,
552 allowInheritPrincipal: true,
554 if json.originAttributes.userContextId
555 params.userContextId = json.originAttributes.userContextId
556 try if not PrivateBrowsingUtils.isWindowPrivate(window)
557 PlacesUIUtils.markPageAsFollowedLink(json.href)
558 window.openLinkIn(json.href, window.whereToOpenLink(json), params)
560 utils.nextTick(window, ->
561 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
562 # links using the mouse. Using that instead of simply
563 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
564 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
565 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
567 href: marker.wrapper.href
568 shiftKey: not inBackground
571 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
572 triggeringPrincipal: window.document.nodePrincipal
577 # The point of “clicking” scrollable elements is focusing them (which is
578 # done above) so that scrolling commands may scroll them. Simulating a click
579 # here usually _unfocuses_ the element.
580 else if type != 'scrollable'
581 vim._run('click_marker_element', {
583 browserOffset: vim._getBrowserOffset()
584 preventTargetBlank: vim.options.prevent_target_blank
589 name = if options.inTab then 'follow_in_tab' else 'follow'
590 helper_follow({name, callback}, args)
593 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
595 commands.follow_in_tab =
596 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
598 commands.follow_in_focused_tab =
599 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
601 helper_follow_in_window = (options, args) ->
604 callback = (marker) ->
605 vim._focusMarkerElement(marker.wrapper.elementIndex)
606 {href} = marker.wrapper
607 vim.window.openLinkIn(href, 'window', options) if href
610 helper_follow({name: 'follow_in_tab', callback}, args)
612 commands.follow_in_window =
613 helper_follow_in_window.bind(null, {})
615 commands.follow_in_private_window =
616 helper_follow_in_window.bind(null, {private: true})
618 commands.follow_multiple = (args) ->
619 args.count = Infinity
620 commands.follow(args)
622 commands.follow_copy = (args) ->
625 callback = (marker) ->
626 property = switch marker.wrapper.type
631 when 'contenteditable', 'complementary'
633 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
636 helper_follow({name: 'follow_copy', callback}, args)
638 commands.follow_focus = (args) ->
641 callback = (marker) ->
642 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
645 helper_follow({name: 'follow_focus', callback}, args)
647 commands.open_context_menu = (args) ->
650 callback = (marker) ->
651 {type, elementIndex} = marker.wrapper
652 vim._run('click_marker_element', {
654 browserOffset: vim._getBrowserOffset()
658 helper_follow({name: 'follow_context', callback}, args)
660 commands.click_browser_element = ({vim}) ->
664 getButtonMenu = (element) ->
665 if element.localName == 'dropmarker' and
666 element.parentNode?.localName == 'toolbarbutton'
667 return element.parentNode.querySelector('menupopup')
671 filter = ({complementary}, element, getElementShape) ->
673 when vim._state.scrollableElements.has(element)
675 when getButtonMenu(element)
677 when utils.isFocusable(element) or element.onclick
681 type = if type then null else 'complementary'
685 # `getElementShape(element, -1)` is intentionally _not_ used in the
686 # `complementary` run, because it results in tons of useless hints for
687 # hidden context menus.
688 shape = getElementShape(element)
689 return unless shape.nonCoveredPoint
691 # The tabs and their close buttons as well as the tab bar scroll arrows get
692 # better hints, since switching or closing tabs is the most common use case
693 # for the `eb` command.
694 isTab = element.classList?.contains('tabbrowser-tab')
697 element.classList?.contains('tab-close-button') or
698 element.classList?.contains('scrollbutton-up') or
699 element.classList?.contains('scrollbutton-down')
701 length = markerElements.push(element)
703 type, shape, isTab, isPrioritized,
704 combinedArea: shape.area,
705 elementIndex: length - 1,
708 callback = (marker) ->
709 element = markerElements[marker.wrapper.elementIndex]
710 switch marker.wrapper.type
712 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
714 getButtonMenu(element).openPopup(
715 element.parentNode, # Anchor node.
716 'after_end', # Position.
718 false, # Isn’t a context menu.
719 true, # Allow the 'position' attribute to override the above position.
721 when 'clickable', 'complementary'
722 # VimFx’s own button won’t trigger unless the click is simulated in the
723 # next tick. This might be true for other buttons as well.
724 utils.nextTick(window, ->
725 utils.focusElement(element)
726 browserOffset = {x: window.screenX, y: window.screenY}
728 when element.localName == 'tab'
729 # Only 'mousedown' seems to be able to activate tabs.
730 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
731 when element.closest('tab')
732 # If `.click()` is used on a tab close button, its tab will be
733 # selected first, which might cause the selected tab to change.
734 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
736 # `.click()` seems to trigger more buttons (such as NoScript’s
737 # button and Firefox’s “hamburger” menu button) than simulating
740 utils.openDropdown(element)
744 wrappers = markableElements.find(
745 window, filter.bind(null, {complementary: false})
748 if wrappers.length > 0
749 viewport = viewportUtils.getWindowViewport(window)
751 markerContainer = new MarkerContainer({
753 hintChars: vim.options['hints.chars']
756 getComplementaryWrappers: (callback) ->
757 newWrappers = markableElements.find(
758 window, filter.bind(null, {complementary: true})
760 callback({wrappers: newWrappers, viewport})
762 MarkerContainer.remove(window) # Better safe than sorry.
763 markerContainer.container.classList.add('ui')
764 mainWindow = window.document.body or
765 window.document.getElementById('main-window') # fallback <fx72
766 mainWindow.insertBefore(
767 markerContainer.container,
768 mainWindow.firstChild
771 [firstWrappers, secondWrappers] =
772 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
774 numChars = markerContainer.alphabet.length
775 numPrimary = markerContainer.primaryHintChars.length
776 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
779 for wrapper in firstWrappers
781 # Given the hint chars `abc de`, give the tabs weights so that the hints
782 # consistently become `a b ca cb cc cd cea ceb cec ced ceea ceeb` and so
783 # on. The rule is that the weight of a tab must be larger than the sum
784 # of all tabs with a longer hint. We start out at `1` and then use
785 # smaller and smaller fractions. This is to make sure that the tabs get
786 # consistent hints as the number of tabs or the size of the window
788 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
789 wrapper.combinedArea = 1 / numChars ** exponent
792 # Make sure that the tab close buttons and the tab bar scroll buttons
793 # come after all the tabs. Treating them all as the same size is fine.
794 # Their sum must be small enough in order not to affect the tab hints.
795 # It might look like using `0` is a good idea, but that results in
796 # increasingly worse hints the more tab close buttons there are.
797 wrapper.combinedArea = 1 / numChars ** numTabs
799 # Since most of the best hint characters might be used for the tabs, make
800 # sure that all other elements don’t get really bad hints. First, favor
801 # larger elements by sorting them. Then, give them all the same weight so
802 # that larger elements (such as the location bar, search bar, the web
803 # console input and other large areas in the devtools) don’t overpower the
804 # smaller ones. The usual “the larger the element, the better the hint” rule
805 # doesn’t really apply the same way for browser UI elements as in web pages.
806 secondWrappers.sort((a, b) -> b.combinedArea - a.combinedArea)
807 for wrapper in secondWrappers
808 wrapper.combinedArea = 1
810 markerContainer.injectHints(firstWrappers, viewport, 'first')
811 markerContainer.injectHints(secondWrappers, viewport, 'second')
812 vim._enterMode('hints', {markerContainer, callback, matchText: false})
815 vim.notify(translate('notification.follow.none'))
817 helper_follow_pattern = (type, {vim}) ->
819 pattern_selector: vim.options.pattern_selector
820 pattern_attrs: vim.options.pattern_attrs
821 patterns: vim.options["#{type}_patterns"]
823 browserOffset = vim._getBrowserOffset()
824 vim._run('follow_pattern', {type, browserOffset, options})
826 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
828 commands.follow_next = helper_follow_pattern.bind(null, 'next')
830 commands.focus_text_input = ({vim, count}) ->
831 vim.markPageInteraction()
832 vim._run('focus_text_input', {count})
834 helper_follow_selectable = ({select}, args) ->
837 callback = (marker) ->
838 vim._run('element_text_select', {
839 elementIndex: marker.wrapper.elementIndex
843 vim._enterMode('caret', {select})
846 helper_follow({name: 'follow_selectable', callback}, args)
848 commands.element_text_caret =
849 helper_follow_selectable.bind(null, {select: false})
851 commands.element_text_select =
852 helper_follow_selectable.bind(null, {select: true})
854 commands.element_text_copy = (args) ->
857 callback = (marker) ->
858 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
861 helper_follow({name: 'follow_selectable', callback}, args)
863 helper_copy_marker_element = (vim, elementIndex, property) ->
864 if property == '_selection'
865 # Selecting the text and then copying that selection is better than copying
866 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
867 # and then includes those backticks in the compiled output (!), in hidden
868 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
869 # elements, text selection gives better whitespace than `.textContent`.
870 vim._run('element_text_select', {elementIndex, full: true}, ->
871 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
872 vim._run('clear_selection')
875 vim._run('copy_marker_element', {elementIndex, property})
884 helper_find_from_top_of_viewport = (vim, direction, callback) ->
885 if vim.options.find_from_top_of_viewport
886 vim._run('find_from_top_of_viewport', {direction}, ->
892 helper_find = ({highlight, linksOnly = false}, {vim}) ->
894 # Make sure to enter find mode here, since that’s where `findStorage.busy`
895 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
896 vim._enterMode('find')
899 helpSearchInput = help.getSearchInput(vim.window)
901 helpSearchInput.select()
904 # Important: Enter Find mode immediately. See `onInput` for Find mode.
905 findStorage.busy = true
906 vim._enterMode('find')
908 helper_mark_last_scroll_position(vim)
909 vim._run('mark_scroll_position', {
910 keyStr: vim.options['scroll.last_find_mark']
914 helper_find_from_top_of_viewport(vim, FORWARD, ->
915 return unless vim.mode == 'find'
916 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
917 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
918 findBar.startFind(mode)
919 utils.focusElement(findBar._findField, {select: true})
922 return unless highlightButton = findBar.getElement('highlight')
923 if highlightButton.checked != highlight
924 highlightButton.click()
928 commands.find = helper_find.bind(null, {highlight: false})
930 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
932 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
934 helper_find_again = (direction, {vim}) ->
935 return if findStorage.busy
937 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
938 if findStorage.lastSearchString.length == 0
939 vim.notify(translate('notification.find_again.none'))
942 findStorage.busy = true
944 helper_mark_last_scroll_position(vim)
945 helper_find_from_top_of_viewport(vim, direction, ->
946 findBar._findField.value = findStorage.lastSearchString
948 # `.onFindResult` is temporarily hacked to be able to know when the
949 # asynchronous `.onFindAgainCommand` is done. When PDFs are shown using
950 # PDF.js, `.updateControlState` is called instead of `.onFindResult`, so
952 originalOnFindResult = findBar.onFindResult
953 originalUpdateControlState = findBar.updateControlState
955 findBar.onFindResult = (data) ->
956 # Prevent the find bar from re-opening if there are no matches.
957 data.storeResult = false
958 findBar.onFindResult = originalOnFindResult
959 findBar.updateControlState = originalUpdateControlState
960 findBar.onFindResult(data)
963 findBar.updateControlState = (args...) ->
964 # Firefox inconsistently _doesn’t_ re-open the find bar if there are no
965 # matches here, so no need to take care of that in this case.
966 findBar.onFindResult = originalOnFindResult
967 findBar.updateControlState = originalUpdateControlState
968 findBar.updateControlState(args...)
972 message = findBar._findStatusDesc.textContent
973 vim.notify(message) if message
974 findStorage.busy = false
976 findBar.onFindAgainCommand(not direction)
980 commands.find_next = helper_find_again.bind(null, FORWARD)
982 commands.find_previous = helper_find_again.bind(null, BACKWARD)
986 commands.window_new = ({vim}) ->
987 vim.window.OpenBrowserWindow()
989 commands.window_new_private = ({vim}) ->
990 vim.window.OpenBrowserWindow({private: true})
992 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
993 type = if blacklist then 'blacklist' else 'explicit'
994 vim._enterMode('ignore', {type})
996 # Quote next keypress (pass it through to the page).
997 commands.quote = ({vim, count = 1}) ->
998 vim._enterMode('ignore', {type: 'explicit', count})
1000 commands.enter_reader_view = ({vim}) ->
1001 button = vim.window.document.getElementById('reader-mode-button')
1002 if not button?.hidden
1005 vim.notify(translate('notification.enter_reader_view.none'))
1007 commands.reload_config_file = ({vim}) ->
1008 vim._parent.emit('shutdown')
1009 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
1011 vim.notify(translate('notification.reload_config_file.none'))
1013 vim.notify(translate('notification.reload_config_file.success'))
1015 vim.notify(translate('notification.reload_config_file.failure'))
1018 commands.edit_blacklist = ({vim}) ->
1019 url = vim.browser.currentURI.spec
1020 location = new vim.window.URL(url)
1021 newPattern = if location.host then "*#{location.host}*" else location.href
1023 blacklistString = prefs.get('blacklist')
1025 if vim._isBlacklisted(url)
1026 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
1027 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
1028 return vim.options.blacklist[index].test(url)
1030 newBlacklistString = "
1031 #{matching.join(delimiter)}\
1032 #{delimiter.repeat(7)}\
1033 #{nonMatching.join(delimiter)}
1035 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1037 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1038 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1041 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1046 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
1047 return if input == null
1048 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
1049 # and let the regular pref parsing take care of it.
1050 prefs.set('blacklist', input)
1051 vim._onLocationChange(url)
1054 commands.help = ({vim}) ->
1055 help.toggleHelp(vim.window, vim._parent)
1057 commands.esc = ({vim}) ->
1059 vim.hideNotification()
1061 # Firefox does things differently when blurring the location bar, depending on
1062 # whether the autocomplete popup is open or not. To be consistent, always
1063 # close the autocomplete popup before blurring.
1065 vim.window.gURLBar.view.close()
1067 vim.window.gURLBar.closePopup() # pre mozilla64
1069 utils.blurActiveBrowserElement(vim)
1070 utils.getFindBar(vim.window.gBrowser).then((findBar) -> findBar.close())
1072 # Better safe than sorry.
1073 MarkerContainer.remove(vim.window)
1074 vim._parent.resetCaretBrowsing()
1076 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1077 help.removeHelp(vim.window)
1079 vim._setFocusType('none') # Better safe than sorry.