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}) ->
34 vim.window.gURLBar.select() # fx76+
36 vim.window.focusAndSelectUrlBar()
38 commands.focus_search_bar = ({vim, count}) ->
39 # The `.webSearch()` method opens a search engine in a tab if the search bar
40 # has been removed. Therefore we first check if it exists.
41 if vim.window.BrowserSearch.searchBar
42 vim.window.BrowserSearch.webSearch()
44 vim.notify(translate('notification.focus_search_bar.none'))
46 helper_paste_and_go = (props, {vim}) ->
47 {gURLBar} = vim.window
48 gURLBar.value = vim.window.readFromClipboard()
49 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
51 commands.paste_and_go = helper_paste_and_go.bind(null, null)
53 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
55 commands.copy_current_url = ({vim}) ->
56 url = vim.window.gBrowser.currentURI.spec
58 if url.startsWith(READER_VIEW_PREFIX)
59 decodeURIComponent(url[READER_VIEW_PREFIX.length..])
62 utils.writeToClipboard(adjustedUrl)
63 vim.notify(translate('notification.copy_current_url.success'))
65 commands.go_up_path = ({vim, count}) ->
66 vim._run('go_up_path', {count})
68 commands.go_to_root = ({vim}) ->
69 vim._run('go_to_root')
71 commands.go_home = ({vim}) ->
72 vim.window.BrowserHome()
74 helper_go_history = (direction, {vim, count = 1}) ->
76 {SessionStore, gBrowser} = window
78 if (direction == 'back' and not gBrowser.canGoBack) or
79 (direction == 'forward' and not gBrowser.canGoForward)
80 vim.notify(translate("notification.history_#{direction}.limit"))
83 # `SessionStore.getSessionHistory()` (used below to support counts) starts
84 # lots of asynchronous tasks internally, which is a bit unreliable, it has
85 # turned out. The primary use of the `history_back` and `history_forward`
86 # commands is to go _one_ step back or forward, though, so those cases are
87 # optimized to use more reliable ways of going back and forward. Also, some
88 # extensions override the following functions, so calling them also gives
89 # better interoperability.
91 if direction == 'back'
94 window.BrowserForward()
97 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
98 {index} = sessionHistory
99 newIndex = index + count * (if direction == 'back' then -1 else 1)
100 newIndex = Math.max(newIndex, 0)
101 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
102 gBrowser.gotoIndex(newIndex)
105 commands.history_back = helper_go_history.bind(null, 'back')
107 commands.history_forward = helper_go_history.bind(null, 'forward')
109 commands.history_list = ({vim}) ->
110 menu = vim.window.document.getElementById('backForwardMenu')
111 utils.openPopup(menu)
112 if menu.childElementCount == 0
113 vim.notify(translate('notification.history_list.none'))
115 commands.reload = ({vim}) ->
116 vim.window.BrowserReload()
118 commands.reload_force = ({vim}) ->
119 vim.window.BrowserReloadSkipCache()
121 commands.reload_all = ({vim}) ->
122 vim.window.gBrowser.reloadAllTabs()
124 commands.reload_all_force = ({vim}) ->
125 for tab in vim.window.gBrowser.visibleTabs
126 gBrowser = tab.linkedBrowser
127 consts = gBrowser.webNavigation
128 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
129 gBrowser.reload(flags)
132 commands.stop = ({vim}) ->
133 vim.window.BrowserStop()
135 commands.stop_all = ({vim}) ->
136 for tab in vim.window.gBrowser.visibleTabs
137 tab.linkedBrowser.stop()
148 helper_scroll = (vim, event, args...) ->
150 method, type, directions, amounts
151 properties = null, adjustment = 0, name = 'scroll', extra = {}
154 elapsed = event.timeStamp - scrollData.lastRepeat
156 if event.repeat and elapsed < vim.options['scroll.repeat_timeout']
159 scrollData.lastRepeat = event.timeStamp
162 method, type, directions, amounts, properties, adjustment, extra
164 prefs.root.get('general.smoothScroll') and
165 prefs.root.get("general.smoothScroll.#{type}")
169 # Temporarily set Firefox’s “spring constant” pref to get the desired smooth
170 # scrolling speed. Reset it `reset_timeout` milliseconds after the last
171 # scrolling command was invoked.
172 scrollData.nonce = nonce = {}
173 scrollData.springConstant ?= prefs.root.get(SPRING_CONSTANT_PREF)
175 SPRING_CONSTANT_PREF,
176 vim.options["smoothScroll.#{type}.spring-constant"]
179 vim.window.setTimeout((->
180 return unless scrollData.nonce == nonce
181 prefs.root.set(SPRING_CONSTANT_PREF, scrollData.springConstant)
182 scrollData.nonce = null
183 scrollData.springConstant = null
184 ), vim.options['scroll.reset_timeout'])
186 {isUIEvent = vim.isUIEvent(event)} = extra
187 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
188 if isUIEvent or helpScroll
189 activeElement = helpScroll or utils.getActiveElement(vim.window)
190 if vim._state.scrollableElements.has(activeElement) or helpScroll
191 viewportUtils.scroll(activeElement, options)
195 vim._run(name, options, reset)
198 helper_scrollByLinesX = (amount, {vim, event, count = 1}) ->
199 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
200 boost = if event.repeat then vim.options['scroll.horizontal_boost'] else 1
202 vim, event, 'scrollBy', 'lines', ['left'],
203 [amount * distance * boost * count * 5]
206 helper_scrollByLinesY = (amount, {vim, event, count = 1}) ->
207 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
208 boost = if event.repeat then vim.options['scroll.vertical_boost'] else 1
210 vim, event, 'scrollBy', 'lines', ['top'],
211 [amount * distance * boost * count * 20]
214 helper_scrollByPagesY = (amount, type, {vim, event, count = 1}) ->
215 adjustment = vim.options["scroll.#{type}_page_adjustment"]
217 vim, event, 'scrollBy', 'pages', ['top'], [amount * count],
218 ['clientHeight'], adjustment
221 helper_scrollToX = (amount, {vim, event}) ->
222 helper_mark_last_scroll_position(vim)
224 vim, event, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
227 helper_scrollToY = (amount, {vim, event}) ->
228 helper_mark_last_scroll_position(vim)
230 vim, event, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
233 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
234 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
235 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
236 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
237 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
238 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
239 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
240 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
241 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
242 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
243 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
244 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
246 helper_mark_last_scroll_position = (vim) ->
247 keyStr = vim.options['scroll.last_position_mark']
248 vim._run('mark_scroll_position', {keyStr, notify: false, addToJumpList: true})
250 commands.mark_scroll_position = ({vim}) ->
251 vim._enterMode('marks', (keyStr) ->
252 vim._run('mark_scroll_position', {keyStr})
254 vim.notify(translate('notification.mark_scroll_position.enter'))
256 commands.scroll_to_mark = ({vim, event}) ->
257 vim._enterMode('marks', (keyStr) ->
258 lastPositionMark = vim.options['scroll.last_position_mark']
260 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
261 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_mark'
262 {keyStr, lastPositionMark, isUIEvent: false}
264 vim.hideNotification()
266 vim.notify(translate('notification.scroll_to_mark.enter'))
268 helper_scroll_to_position = (direction, {vim, event, count = 1}) ->
269 lastPositionMark = vim.options['scroll.last_position_mark']
271 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
272 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_position'
273 {count, direction, lastPositionMark, isUIEvent: false}
276 commands.scroll_to_previous_position =
277 helper_scroll_to_position.bind(null, 'previous')
279 commands.scroll_to_next_position =
280 helper_scroll_to_position.bind(null, 'next')
284 commands.tab_new = ({vim}) ->
285 utils.nextTick(vim.window, ->
286 vim.window.BrowserOpenTab()
289 commands.tab_new_after_current = ({vim}) ->
291 newTabPosition = window.gBrowser.selectedTab._tPos + 1
292 utils.nextTick(window, ->
293 utils.listenOnce(window, 'TabOpen', (event) ->
294 newTab = event.originalTarget
295 window.gBrowser.moveTabTo(newTab, newTabPosition)
297 window.BrowserOpenTab()
300 commands.tab_duplicate = ({vim}) ->
301 {gBrowser} = vim.window
302 utils.nextTick(vim.window, ->
303 gBrowser.duplicateTab(gBrowser.selectedTab)
306 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
307 tabs = gBrowser.visibleTabs
308 {selectedTab} = gBrowser
310 currentIndex = tabs.indexOf(selectedTab)
311 absoluteIndex = currentIndex + relativeIndex
312 numTabsTotal = tabs.length
313 numPinnedTabs = gBrowser._numPinnedTabs
315 [numTabs, min] = switch
316 when not pinnedSeparate
318 when selectedTab.pinned
321 [numTabsTotal - numPinnedTabs, numPinnedTabs]
323 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
325 if (relativeIndex < 0 and currentIndex == min) or
326 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
327 if absoluteIndex < min
328 absoluteIndex += numTabs
329 else if absoluteIndex >= min + numTabs
330 absoluteIndex -= numTabs
332 absoluteIndex = Math.max(min, absoluteIndex)
333 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
337 helper_switch_tab = (direction, {vim, count = 1}) ->
338 {gBrowser} = vim.window
339 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
340 utils.nextTick(vim.window, ->
341 gBrowser.selectTabAtIndex(index)
344 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
346 commands.tab_select_next = helper_switch_tab.bind(null, +1)
348 helper_is_visited = (tab) ->
349 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
351 commands.tab_select_most_recent = ({vim, count = 1}) ->
352 {gBrowser} = vim.window
354 Array.prototype.filter.call(
356 (tab) -> not tab.closing and helper_is_visited(tab)
357 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
358 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
360 gBrowser.selectedTab = tab
362 vim.notify(translate('notification.tab_select_most_recent.none'))
364 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
365 {gBrowser} = vim.window
367 Array.prototype.filter.call(
369 (tab) -> not tab.closing and not helper_is_visited(tab)
370 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
371 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
373 gBrowser.selectedTab = tab
375 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
377 helper_move_tab = (direction, {vim, count = 1}) ->
378 {gBrowser} = vim.window
379 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
380 utils.nextTick(vim.window, ->
381 gBrowser.moveTabTo(gBrowser.selectedTab, index)
384 commands.tab_move_backward = helper_move_tab.bind(null, -1)
386 commands.tab_move_forward = helper_move_tab.bind(null, +1)
388 commands.tab_move_to_window = ({vim}) ->
389 {gBrowser} = vim.window
390 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
392 commands.tab_select_first = ({vim, count = 1}) ->
393 utils.nextTick(vim.window, ->
394 vim.window.gBrowser.selectTabAtIndex(count - 1)
397 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
398 firstNonPinned = vim.window.gBrowser._numPinnedTabs
399 utils.nextTick(vim.window, ->
400 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
403 commands.tab_select_last = ({vim, count = 1}) ->
404 utils.nextTick(vim.window, ->
405 vim.window.gBrowser.selectTabAtIndex(-count)
408 commands.tab_toggle_pinned = ({vim}) ->
409 currentTab = vim.window.gBrowser.selectedTab
411 vim.window.gBrowser.unpinTab(currentTab)
413 vim.window.gBrowser.pinTab(currentTab)
415 commands.tab_close = ({vim, count = 1}) ->
416 {gBrowser} = vim.window
417 return if gBrowser.selectedTab.pinned
418 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
419 utils.nextTick(vim.window, ->
420 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
421 gBrowser.removeTab(tab)
425 commands.tab_restore = ({vim, count = 1}) ->
426 utils.nextTick(vim.window, ->
427 for index in [0...count] by 1
428 restoredTab = vim.window.undoCloseTab()
429 if not restoredTab and index == 0
430 vim.notify(translate('notification.tab_restore.none'))
435 commands.tab_restore_list = ({vim}) ->
437 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
440 if fragment.childElementCount == 0
441 vim.notify(translate('notification.tab_restore.none'))
443 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
445 commands.tab_close_to_end = ({vim}) ->
446 {gBrowser} = vim.window
447 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
449 commands.tab_close_other = ({vim}) ->
450 {gBrowser} = vim.window
451 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
455 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
457 vim.markPageInteraction()
458 help.removeHelp(window)
460 markerContainer = new MarkerContainer({
462 hintChars: vim.options['hints.chars']
463 getComplementaryWrappers: (callback) ->
464 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
465 # `markerContainer.container` is `null`ed out when leaving Hints mode.
466 # If this callback is called after we’ve left Hints mode (and perhaps
467 # even entered it again), simply discard the result.
468 return unless markerContainer.container
469 if wrappers.length == 0
470 vim.notify(translate('notification.follow.none'))
471 callback({wrappers, viewport})
474 MarkerContainer.remove(window) # Better safe than sorry.
475 window.gBrowser.selectedBrowser.parentNode.appendChild(
476 markerContainer.container
479 chooseCallback = (marker, timesLeft, keyStr) ->
481 {type, href = null, elementIndex} = marker.wrapper
482 return callbackOverride({type, href, id: elementIndex, timesLeft})
484 return callback(marker, timesLeft, keyStr)
486 # Enter Hints mode immediately, with an empty set of markers. The user might
487 # press keys before any hints have been generated. Those keypresses should be
488 # handled in Hints mode, not Normal mode.
489 vim._enterMode('hints', {
490 markerContainer, count
491 callback: chooseCallback
492 matchText: vim.options['hints.match_text']
493 sleep: vim.options['hints.sleep']
496 injectHints = ({wrappers, viewport, pass}) ->
497 # See `getComplementaryWrappers` above.
498 return unless markerContainer.container
500 if wrappers.length == 0
501 if pass in ['single', 'second'] and markerContainer.markers.length == 0
502 vim.notify(translate('notification.follow.none'))
503 vim._enterMode('normal')
505 markerContainer.injectHints(wrappers, viewport, pass)
508 vim._run(name, {pass: 'second'}, injectHints)
510 vim._run(name, {pass: 'auto'}, injectHints)
512 helper_follow_clickable = (options, args) ->
515 callback = (marker, timesLeft, keyStr) ->
516 {inTab, inBackground} = options
517 {type, elementIndex} = marker.wrapper
518 isLast = (timesLeft == 1)
519 isLink = (type == 'link')
523 when keyStr.startsWith(vim.options['hints.toggle_in_tab'])
525 when keyStr.startsWith(vim.options['hints.toggle_in_background'])
527 inBackground = not inBackground
533 inTab = false unless isLink
535 if type == 'text' or (isLink and not (inTab and inBackground))
538 vim._focusMarkerElement(elementIndex)
541 contentAreaClick = (json, browser) ->
542 # Note this function is shortened from the same-named one currently in
543 # mozilla-central/browser/actors/ClickHandlerParent.jsm. Keep in sync!
544 window = browser.ownerGlobal
546 charset: browser.characterSet,
547 referrerInfo: E10SUtils.deserializeReferrerInfo(json.referrerInfo),
548 allowMixedContent: json.allowMixedContent,
549 isContentWindowPrivate: json.isContentWindowPrivate,
550 originPrincipal: json.originPrincipal,
551 originStoragePrincipal: json.originStoragePrincipal,
552 triggeringPrincipal: json.triggeringPrincipal,
553 csp: if json.csp then E10SUtils.deserializeCSP(json.csp) else null,
554 frameOuterWindowID: json.frameOuterWindowID, # <=fx79
555 frameID: json.frameID, # >=fx80
556 allowInheritPrincipal: true,
558 if json.originAttributes.userContextId
559 params.userContextId = json.originAttributes.userContextId
560 try if not PrivateBrowsingUtils.isWindowPrivate(window)
561 PlacesUIUtils.markPageAsFollowedLink(json.href)
562 window.openLinkIn(json.href, window.whereToOpenLink(json), params)
564 utils.nextTick(window, ->
565 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
566 # links using the mouse. Using that instead of simply
567 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
568 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
569 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
571 href: marker.wrapper.href
572 shiftKey: not inBackground
575 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
576 triggeringPrincipal: window.document.nodePrincipal
581 # The point of “clicking” scrollable elements is focusing them (which is
582 # done above) so that scrolling commands may scroll them. Simulating a click
583 # here usually _unfocuses_ the element.
584 else if type != 'scrollable'
585 vim._run('click_marker_element', {
587 browserOffset: vim._getBrowserOffset()
588 preventTargetBlank: vim.options.prevent_target_blank
593 name = if options.inTab then 'follow_in_tab' else 'follow'
594 helper_follow({name, callback}, args)
597 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
599 commands.follow_in_tab =
600 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
602 commands.follow_in_focused_tab =
603 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
605 helper_follow_in_window = (options, args) ->
608 callback = (marker) ->
609 vim._focusMarkerElement(marker.wrapper.elementIndex)
610 {href} = marker.wrapper
611 vim.window.openLinkIn(href, 'window', options) if href
614 helper_follow({name: 'follow_in_tab', callback}, args)
616 commands.follow_in_window =
617 helper_follow_in_window.bind(null, {})
619 commands.follow_in_private_window =
620 helper_follow_in_window.bind(null, {private: true})
622 commands.follow_multiple = (args) ->
623 args.count = Infinity
624 commands.follow(args)
626 commands.follow_copy = (args) ->
629 callback = (marker) ->
630 property = switch marker.wrapper.type
635 when 'contenteditable', 'complementary'
637 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
640 helper_follow({name: 'follow_copy', callback}, args)
642 commands.follow_focus = (args) ->
645 callback = (marker) ->
646 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
649 helper_follow({name: 'follow_focus', callback}, args)
651 commands.open_context_menu = (args) ->
654 callback = (marker) ->
655 {type, elementIndex} = marker.wrapper
656 vim._run('click_marker_element', {
658 browserOffset: vim._getBrowserOffset()
662 helper_follow({name: 'follow_context', callback}, args)
664 commands.click_browser_element = ({vim}) ->
668 getButtonMenu = (element) ->
669 if element.localName == 'dropmarker' and
670 element.parentNode?.localName == 'toolbarbutton'
671 return element.parentNode.querySelector('menupopup')
675 filter = ({complementary}, element, getElementShape) ->
677 when vim._state.scrollableElements.has(element)
679 when getButtonMenu(element)
681 when utils.isFocusable(element) or element.onclick
685 type = if type then null else 'complementary'
689 # `getElementShape(element, -1)` is intentionally _not_ used in the
690 # `complementary` run, because it results in tons of useless hints for
691 # hidden context menus.
692 shape = getElementShape(element)
693 return unless shape.nonCoveredPoint
695 # The tabs and their close buttons as well as the tab bar scroll arrows get
696 # better hints, since switching or closing tabs is the most common use case
697 # for the `eb` command.
698 isTab = element.classList?.contains('tabbrowser-tab')
701 element.classList?.contains('tab-close-button') or
702 element.classList?.contains('scrollbutton-up') or
703 element.classList?.contains('scrollbutton-down')
705 length = markerElements.push(element)
707 type, shape, isTab, isPrioritized,
708 combinedArea: shape.area,
709 elementIndex: length - 1,
712 callback = (marker) ->
713 element = markerElements[marker.wrapper.elementIndex]
714 switch marker.wrapper.type
716 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
718 getButtonMenu(element).openPopup(
719 element.parentNode, # Anchor node.
720 'after_end', # Position.
722 false, # Isn’t a context menu.
723 true, # Allow the 'position' attribute to override the above position.
725 when 'clickable', 'complementary'
726 # VimFx’s own button won’t trigger unless the click is simulated in the
727 # next tick. This might be true for other buttons as well.
728 utils.nextTick(window, ->
729 utils.focusElement(element)
730 browserOffset = {x: window.screenX, y: window.screenY}
732 when element.localName == 'tab'
733 # Only 'mousedown' seems to be able to activate tabs.
734 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
735 when element.closest('tab')
736 # If `.click()` is used on a tab close button, its tab will be
737 # selected first, which might cause the selected tab to change.
738 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
740 # `.click()` seems to trigger more buttons (such as NoScript’s
741 # button and Firefox’s “hamburger” menu button) than simulating
744 utils.openDropdown(element)
748 wrappers = markableElements.find(
749 window, filter.bind(null, {complementary: false})
752 if wrappers.length > 0
753 viewport = viewportUtils.getWindowViewport(window)
755 markerContainer = new MarkerContainer({
757 hintChars: vim.options['hints.chars']
760 getComplementaryWrappers: (callback) ->
761 newWrappers = markableElements.find(
762 window, filter.bind(null, {complementary: true})
764 callback({wrappers: newWrappers, viewport})
766 MarkerContainer.remove(window) # Better safe than sorry.
767 markerContainer.container.classList.add('ui')
768 mainWindow = window.document.body or
769 window.document.getElementById('main-window') # fallback <fx72
770 mainWindow.insertBefore(
771 markerContainer.container,
772 mainWindow.firstChild
775 [firstWrappers, secondWrappers] =
776 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
778 numChars = markerContainer.alphabet.length
779 numPrimary = markerContainer.primaryHintChars.length
780 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
783 for wrapper in firstWrappers
785 # Given the hint chars `abc de`, give the tabs weights so that the hints
786 # consistently become `a b ca cb cc cd cea ceb cec ced ceea ceeb` and so
787 # on. The rule is that the weight of a tab must be larger than the sum
788 # of all tabs with a longer hint. We start out at `1` and then use
789 # smaller and smaller fractions. This is to make sure that the tabs get
790 # consistent hints as the number of tabs or the size of the window
792 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
793 wrapper.combinedArea = 1 / numChars ** exponent
796 # Make sure that the tab close buttons and the tab bar scroll buttons
797 # come after all the tabs. Treating them all as the same size is fine.
798 # Their sum must be small enough in order not to affect the tab hints.
799 # It might look like using `0` is a good idea, but that results in
800 # increasingly worse hints the more tab close buttons there are.
801 wrapper.combinedArea = 1 / numChars ** numTabs
803 # Since most of the best hint characters might be used for the tabs, make
804 # sure that all other elements don’t get really bad hints. First, favor
805 # larger elements by sorting them. Then, give them all the same weight so
806 # that larger elements (such as the location bar, search bar, the web
807 # console input and other large areas in the devtools) don’t overpower the
808 # smaller ones. The usual “the larger the element, the better the hint” rule
809 # doesn’t really apply the same way for browser UI elements as in web pages.
810 secondWrappers.sort((a, b) -> b.combinedArea - a.combinedArea)
811 for wrapper in secondWrappers
812 wrapper.combinedArea = 1
814 markerContainer.injectHints(firstWrappers, viewport, 'first')
815 markerContainer.injectHints(secondWrappers, viewport, 'second')
816 vim._enterMode('hints', {markerContainer, callback, matchText: false})
819 vim.notify(translate('notification.follow.none'))
821 helper_follow_pattern = (type, {vim}) ->
823 pattern_selector: vim.options.pattern_selector
824 pattern_attrs: vim.options.pattern_attrs
825 patterns: vim.options["#{type}_patterns"]
827 browserOffset = vim._getBrowserOffset()
828 vim._run('follow_pattern', {type, browserOffset, options})
830 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
832 commands.follow_next = helper_follow_pattern.bind(null, 'next')
834 commands.focus_text_input = ({vim, count}) ->
835 vim.markPageInteraction()
836 vim._run('focus_text_input', {count})
838 helper_follow_selectable = ({select}, args) ->
841 callback = (marker) ->
842 vim._run('element_text_select', {
843 elementIndex: marker.wrapper.elementIndex
847 vim._enterMode('caret', {select})
850 helper_follow({name: 'follow_selectable', callback}, args)
852 commands.element_text_caret =
853 helper_follow_selectable.bind(null, {select: false})
855 commands.element_text_select =
856 helper_follow_selectable.bind(null, {select: true})
858 commands.element_text_copy = (args) ->
861 callback = (marker) ->
862 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
865 helper_follow({name: 'follow_selectable', callback}, args)
867 helper_copy_marker_element = (vim, elementIndex, property) ->
868 if property == '_selection'
869 # Selecting the text and then copying that selection is better than copying
870 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
871 # and then includes those backticks in the compiled output (!), in hidden
872 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
873 # elements, text selection gives better whitespace than `.textContent`.
874 vim._run('element_text_select', {elementIndex, full: true}, ->
875 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
876 vim._run('clear_selection')
879 vim._run('copy_marker_element', {elementIndex, property})
888 helper_find_from_top_of_viewport = (vim, direction, callback) ->
889 if vim.options.find_from_top_of_viewport
890 vim._run('find_from_top_of_viewport', {direction}, ->
896 helper_find = ({highlight, linksOnly = false}, {vim}) ->
898 # Make sure to enter find mode here, since that’s where `findStorage.busy`
899 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
900 vim._enterMode('find')
903 helpSearchInput = help.getSearchInput(vim.window)
905 helpSearchInput.select()
908 # Important: Enter Find mode immediately. See `onInput` for Find mode.
909 findStorage.busy = true
910 vim._enterMode('find')
912 helper_mark_last_scroll_position(vim)
913 vim._run('mark_scroll_position', {
914 keyStr: vim.options['scroll.last_find_mark']
918 helper_find_from_top_of_viewport(vim, FORWARD, ->
919 return unless vim.mode == 'find'
920 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
921 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
922 findBar.startFind(mode)
923 utils.focusElement(findBar._findField, {select: true})
926 return unless highlightButton = findBar.getElement('highlight')
927 if highlightButton.checked != highlight
928 highlightButton.click()
932 commands.find = helper_find.bind(null, {highlight: false})
934 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
936 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
938 helper_find_again = (direction, {vim}) ->
939 return if findStorage.busy
941 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
942 if findStorage.lastSearchString.length == 0
943 vim.notify(translate('notification.find_again.none'))
946 findStorage.busy = true
948 helper_mark_last_scroll_position(vim)
949 helper_find_from_top_of_viewport(vim, direction, ->
950 findBar._findField.value = findStorage.lastSearchString
952 # `.onFindResult` is temporarily hacked to be able to know when the
953 # asynchronous `.onFindAgainCommand` is done. When PDFs are shown using
954 # PDF.js, `.updateControlState` is called instead of `.onFindResult`, so
956 originalOnFindResult = findBar.onFindResult
957 originalUpdateControlState = findBar.updateControlState
959 findBar.onFindResult = (data) ->
960 # Prevent the find bar from re-opening if there are no matches.
961 data.storeResult = false
962 findBar.onFindResult = originalOnFindResult
963 findBar.updateControlState = originalUpdateControlState
964 findBar.onFindResult(data)
967 findBar.updateControlState = (args...) ->
968 # Firefox inconsistently _doesn’t_ re-open the find bar if there are no
969 # matches here, so no need to take care of that in this case.
970 findBar.onFindResult = originalOnFindResult
971 findBar.updateControlState = originalUpdateControlState
972 findBar.updateControlState(args...)
976 message = findBar._findStatusDesc.textContent
977 vim.notify(message) if message
978 findStorage.busy = false
980 findBar.onFindAgainCommand(not direction)
984 commands.find_next = helper_find_again.bind(null, FORWARD)
986 commands.find_previous = helper_find_again.bind(null, BACKWARD)
990 commands.window_new = ({vim}) ->
991 vim.window.OpenBrowserWindow()
993 commands.window_new_private = ({vim}) ->
994 vim.window.OpenBrowserWindow({private: true})
996 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
997 type = if blacklist then 'blacklist' else 'explicit'
998 vim._enterMode('ignore', {type})
1000 # Quote next keypress (pass it through to the page).
1001 commands.quote = ({vim, count = 1}) ->
1002 vim._enterMode('ignore', {type: 'explicit', count})
1004 commands.enter_reader_view = ({vim}) ->
1005 button = vim.window.document.getElementById('reader-mode-button')
1006 if not button?.hidden
1009 vim.notify(translate('notification.enter_reader_view.none'))
1011 commands.reload_config_file = ({vim}) ->
1012 vim._parent.emit('shutdown')
1013 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
1015 vim.notify(translate('notification.reload_config_file.none'))
1017 vim.notify(translate('notification.reload_config_file.success'))
1019 vim.notify(translate('notification.reload_config_file.failure'))
1022 commands.edit_blacklist = ({vim}) ->
1023 url = vim.browser.currentURI.spec
1024 location = new vim.window.URL(url)
1025 newPattern = if location.host then "*#{location.host}*" else location.href
1027 blacklistString = prefs.get('blacklist')
1029 if vim._isBlacklisted(url)
1030 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
1031 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
1032 return vim.options.blacklist[index].test(url)
1034 newBlacklistString = "
1035 #{matching.join(delimiter)}\
1036 #{delimiter.repeat(7)}\
1037 #{nonMatching.join(delimiter)}
1039 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1041 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1042 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1045 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1050 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
1051 return if input == null
1052 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
1053 # and let the regular pref parsing take care of it.
1054 prefs.set('blacklist', input)
1055 vim._onLocationChange(url)
1058 commands.help = ({vim}) ->
1059 help.toggleHelp(vim.window, vim._parent)
1061 commands.esc = ({vim}) ->
1063 vim.hideNotification()
1065 # Firefox does things differently when blurring the location bar, depending on
1066 # whether the autocomplete popup is open or not. To be consistent, always
1067 # close the autocomplete popup before blurring.
1068 vim.window.gURLBar.view.close()
1070 utils.blurActiveBrowserElement(vim)
1071 utils.getFindBar(vim.window.gBrowser).then((findBar) -> findBar.close())
1073 # Better safe than sorry.
1074 MarkerContainer.remove(vim.window)
1075 vim._parent.resetCaretBrowsing()
1077 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1078 help.removeHelp(vim.window)
1080 vim._setFocusType('none') # Better safe than sorry.