]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Fix `o` in nightly 76 (Bug 1610479)
[VimFx.git] / extension / lib / commands.coffee
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.
4
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.
7
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')
18
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
24
25 READER_VIEW_PREFIX = 'about:reader?url='
26 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
27
28 commands = {}
29
30
31
32 commands.focus_location_bar = ({vim}) ->
33 try
34 vim.window.gURLBar.select() # fx76+
35 catch
36 vim.window.focusAndSelectUrlBar()
37
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()
43 else
44 vim.notify(translate('notification.focus_search_bar.none'))
45
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))
50
51 commands.paste_and_go = helper_paste_and_go.bind(null, null)
52
53 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
54
55 commands.copy_current_url = ({vim}) ->
56 url = vim.window.gBrowser.currentURI.spec
57 adjustedUrl =
58 if url.startsWith(READER_VIEW_PREFIX)
59 decodeURIComponent(url[READER_VIEW_PREFIX.length..])
60 else
61 url
62 utils.writeToClipboard(adjustedUrl)
63 vim.notify(translate('notification.copy_current_url.success'))
64
65 commands.go_up_path = ({vim, count}) ->
66 vim._run('go_up_path', {count})
67
68 commands.go_to_root = ({vim}) ->
69 vim._run('go_to_root')
70
71 commands.go_home = ({vim}) ->
72 vim.window.BrowserHome()
73
74 helper_go_history = (direction, {vim, count = 1}) ->
75 {window} = vim
76 {SessionStore, gBrowser} = window
77
78 if (direction == 'back' and not gBrowser.canGoBack) or
79 (direction == 'forward' and not gBrowser.canGoForward)
80 vim.notify(translate("notification.history_#{direction}.limit"))
81 return
82
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.
90 if count == 1
91 if direction == 'back'
92 window.BrowserBack()
93 else
94 window.BrowserForward()
95 return
96
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)
103 )
104
105 commands.history_back = helper_go_history.bind(null, 'back')
106
107 commands.history_forward = helper_go_history.bind(null, 'forward')
108
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'))
114
115 commands.reload = ({vim}) ->
116 vim.window.BrowserReload()
117
118 commands.reload_force = ({vim}) ->
119 vim.window.BrowserReloadSkipCache()
120
121 commands.reload_all = ({vim}) ->
122 vim.window.gBrowser.reloadAllTabs()
123
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)
130 return
131
132 commands.stop = ({vim}) ->
133 vim.window.BrowserStop()
134
135 commands.stop_all = ({vim}) ->
136 for tab in vim.window.gBrowser.visibleTabs
137 tab.linkedBrowser.stop()
138 return
139
140
141
142 scrollData = {
143 nonce: null
144 springConstant: null
145 lastRepeat: 0
146 }
147
148 helper_scroll = (vim, event, args...) ->
149 [
150 method, type, directions, amounts
151 properties = null, adjustment = 0, name = 'scroll', extra = {}
152 ] = args
153
154 elapsed = event.timeStamp - scrollData.lastRepeat
155
156 if event.repeat and elapsed < vim.options['scroll.repeat_timeout']
157 return
158
159 scrollData.lastRepeat = event.timeStamp
160
161 options = {
162 method, type, directions, amounts, properties, adjustment, extra
163 smooth: (
164 prefs.root.get('general.smoothScroll') and
165 prefs.root.get("general.smoothScroll.#{type}")
166 )
167 }
168
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)
174 prefs.root.set(
175 SPRING_CONSTANT_PREF,
176 vim.options["smoothScroll.#{type}.spring-constant"]
177 )
178 reset = ->
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'])
185
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)
192 reset()
193 return
194
195 vim._run(name, options, reset)
196
197
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
201 helper_scroll(
202 vim, event, 'scrollBy', 'lines', ['left'],
203 [amount * distance * boost * count * 5]
204 )
205
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
209 helper_scroll(
210 vim, event, 'scrollBy', 'lines', ['top'],
211 [amount * distance * boost * count * 20]
212 )
213
214 helper_scrollByPagesY = (amount, type, {vim, event, count = 1}) ->
215 adjustment = vim.options["scroll.#{type}_page_adjustment"]
216 helper_scroll(
217 vim, event, 'scrollBy', 'pages', ['top'], [amount * count],
218 ['clientHeight'], adjustment
219 )
220
221 helper_scrollToX = (amount, {vim, event}) ->
222 helper_mark_last_scroll_position(vim)
223 helper_scroll(
224 vim, event, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
225 )
226
227 helper_scrollToY = (amount, {vim, event}) ->
228 helper_mark_last_scroll_position(vim)
229 helper_scroll(
230 vim, event, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
231 )
232
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)
245
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})
249
250 commands.mark_scroll_position = ({vim}) ->
251 vim._enterMode('marks', (keyStr) ->
252 vim._run('mark_scroll_position', {keyStr})
253 )
254 vim.notify(translate('notification.mark_scroll_position.enter'))
255
256 commands.scroll_to_mark = ({vim, event}) ->
257 vim._enterMode('marks', (keyStr) ->
258 lastPositionMark = vim.options['scroll.last_position_mark']
259 helper_scroll(
260 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
261 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_mark'
262 {keyStr, lastPositionMark, isUIEvent: false}
263 )
264 vim.hideNotification()
265 )
266 vim.notify(translate('notification.scroll_to_mark.enter'))
267
268 helper_scroll_to_position = (direction, {vim, event, count = 1}) ->
269 lastPositionMark = vim.options['scroll.last_position_mark']
270 helper_scroll(
271 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
272 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_position'
273 {count, direction, lastPositionMark, isUIEvent: false}
274 )
275
276 commands.scroll_to_previous_position =
277 helper_scroll_to_position.bind(null, 'previous')
278
279 commands.scroll_to_next_position =
280 helper_scroll_to_position.bind(null, 'next')
281
282
283
284 commands.tab_new = ({vim}) ->
285 utils.nextTick(vim.window, ->
286 vim.window.BrowserOpenTab()
287 )
288
289 commands.tab_new_after_current = ({vim}) ->
290 {window} = 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)
296 )
297 window.BrowserOpenTab()
298 )
299
300 commands.tab_duplicate = ({vim}) ->
301 {gBrowser} = vim.window
302 utils.nextTick(vim.window, ->
303 gBrowser.duplicateTab(gBrowser.selectedTab)
304 )
305
306 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
307 tabs = gBrowser.visibleTabs
308 {selectedTab} = gBrowser
309
310 currentIndex = tabs.indexOf(selectedTab)
311 absoluteIndex = currentIndex + relativeIndex
312 numTabsTotal = tabs.length
313 numPinnedTabs = gBrowser._numPinnedTabs
314
315 [numTabs, min] = switch
316 when not pinnedSeparate
317 [numTabsTotal, 0]
318 when selectedTab.pinned
319 [numPinnedTabs, 0]
320 else
321 [numTabsTotal - numPinnedTabs, numPinnedTabs]
322
323 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
324 # current direction.
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
331
332 absoluteIndex = Math.max(min, absoluteIndex)
333 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
334
335 return absoluteIndex
336
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)
342 )
343
344 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
345
346 commands.tab_select_next = helper_switch_tab.bind(null, +1)
347
348 helper_is_visited = (tab) ->
349 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
350
351 commands.tab_select_most_recent = ({vim, count = 1}) ->
352 {gBrowser} = vim.window
353 tabsSorted =
354 Array.prototype.filter.call(
355 gBrowser.tabs,
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)]
359 if tab
360 gBrowser.selectedTab = tab
361 else
362 vim.notify(translate('notification.tab_select_most_recent.none'))
363
364 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
365 {gBrowser} = vim.window
366 tabsSorted =
367 Array.prototype.filter.call(
368 gBrowser.tabs,
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)]
372 if tab
373 gBrowser.selectedTab = tab
374 else
375 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
376
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)
382 )
383
384 commands.tab_move_backward = helper_move_tab.bind(null, -1)
385
386 commands.tab_move_forward = helper_move_tab.bind(null, +1)
387
388 commands.tab_move_to_window = ({vim}) ->
389 {gBrowser} = vim.window
390 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
391
392 commands.tab_select_first = ({vim, count = 1}) ->
393 utils.nextTick(vim.window, ->
394 vim.window.gBrowser.selectTabAtIndex(count - 1)
395 )
396
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)
401 )
402
403 commands.tab_select_last = ({vim, count = 1}) ->
404 utils.nextTick(vim.window, ->
405 vim.window.gBrowser.selectTabAtIndex(-count)
406 )
407
408 commands.tab_toggle_pinned = ({vim}) ->
409 currentTab = vim.window.gBrowser.selectedTab
410 if currentTab.pinned
411 vim.window.gBrowser.unpinTab(currentTab)
412 else
413 vim.window.gBrowser.pinTab(currentTab)
414
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)
422 return
423 )
424
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'))
431 break
432 return
433 )
434
435 commands.tab_restore_list = ({vim}) ->
436 {window} = vim
437 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
438 window, 'menuitem'
439 )
440 if fragment.childElementCount == 0
441 vim.notify(translate('notification.tab_restore.none'))
442 else
443 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
444
445 commands.tab_close_to_end = ({vim}) ->
446 {gBrowser} = vim.window
447 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
448
449 commands.tab_close_other = ({vim}) ->
450 {gBrowser} = vim.window
451 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
452
453
454
455 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
456 {window} = vim
457 vim.markPageInteraction()
458 help.removeHelp(window)
459
460 markerContainer = new MarkerContainer({
461 window
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})
472 )
473 })
474 MarkerContainer.remove(window) # Better safe than sorry.
475 window.gBrowser.selectedBrowser.parentNode.appendChild(
476 markerContainer.container
477 )
478
479 chooseCallback = (marker, timesLeft, keyStr) ->
480 if callbackOverride
481 {type, href = null, elementIndex} = marker.wrapper
482 return callbackOverride({type, href, id: elementIndex, timesLeft})
483 else
484 return callback(marker, timesLeft, keyStr)
485
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']
494 })
495
496 injectHints = ({wrappers, viewport, pass}) ->
497 # See `getComplementaryWrappers` above.
498 return unless markerContainer.container
499
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')
504 else
505 markerContainer.injectHints(wrappers, viewport, pass)
506
507 if pass == 'first'
508 vim._run(name, {pass: 'second'}, injectHints)
509
510 vim._run(name, {pass: 'auto'}, injectHints)
511
512 helper_follow_clickable = (options, args) ->
513 {vim} = args
514
515 callback = (marker, timesLeft, keyStr) ->
516 {inTab, inBackground} = options
517 {type, elementIndex} = marker.wrapper
518 isLast = (timesLeft == 1)
519 isLink = (type == 'link')
520 {window} = vim
521
522 switch
523 when keyStr.startsWith(vim.options['hints.toggle_in_tab'])
524 inTab = not inTab
525 when keyStr.startsWith(vim.options['hints.toggle_in_background'])
526 inTab = true
527 inBackground = not inBackground
528 else
529 unless isLast
530 inTab = true
531 inBackground = true
532
533 inTab = false unless isLink
534
535 if type == 'text' or (isLink and not (inTab and inBackground))
536 isLast = true
537
538 vim._focusMarkerElement(elementIndex)
539
540 if inTab
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
545 params = {
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,
555 allowInheritPrincipal: true,
556 }
557 if json.originAttributes.userContextId
558 params.userContextId = json.originAttributes.userContextId
559 try if not PrivateBrowsingUtils.isWindowPrivate(window)
560 PlacesUIUtils.markPageAsFollowedLink(json.href)
561 window.openLinkIn(json.href, window.whereToOpenLink(json), params)
562
563 utils.nextTick(window, ->
564 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
565 # links using the mouse. Using that instead of simply
566 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
567 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
568 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
569 contentAreaClick({
570 href: marker.wrapper.href
571 shiftKey: not inBackground
572 ctrlKey: true
573 metaKey: true
574 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
575 triggeringPrincipal: window.document.nodePrincipal
576 }, vim.browser)
577 reset()
578 )
579
580 # The point of “clicking” scrollable elements is focusing them (which is
581 # done above) so that scrolling commands may scroll them. Simulating a click
582 # here usually _unfocuses_ the element.
583 else if type != 'scrollable'
584 vim._run('click_marker_element', {
585 elementIndex, type
586 browserOffset: vim._getBrowserOffset()
587 preventTargetBlank: vim.options.prevent_target_blank
588 })
589
590 return not isLast
591
592 name = if options.inTab then 'follow_in_tab' else 'follow'
593 helper_follow({name, callback}, args)
594
595 commands.follow =
596 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
597
598 commands.follow_in_tab =
599 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
600
601 commands.follow_in_focused_tab =
602 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
603
604 helper_follow_in_window = (options, args) ->
605 {vim} = args
606
607 callback = (marker) ->
608 vim._focusMarkerElement(marker.wrapper.elementIndex)
609 {href} = marker.wrapper
610 vim.window.openLinkIn(href, 'window', options) if href
611 return false
612
613 helper_follow({name: 'follow_in_tab', callback}, args)
614
615 commands.follow_in_window =
616 helper_follow_in_window.bind(null, {})
617
618 commands.follow_in_private_window =
619 helper_follow_in_window.bind(null, {private: true})
620
621 commands.follow_multiple = (args) ->
622 args.count = Infinity
623 commands.follow(args)
624
625 commands.follow_copy = (args) ->
626 {vim} = args
627
628 callback = (marker) ->
629 property = switch marker.wrapper.type
630 when 'link'
631 'href'
632 when 'text'
633 'value'
634 when 'contenteditable', 'complementary'
635 '_selection'
636 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
637 return false
638
639 helper_follow({name: 'follow_copy', callback}, args)
640
641 commands.follow_focus = (args) ->
642 {vim} = args
643
644 callback = (marker) ->
645 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
646 return false
647
648 helper_follow({name: 'follow_focus', callback}, args)
649
650 commands.open_context_menu = (args) ->
651 {vim} = args
652
653 callback = (marker) ->
654 {type, elementIndex} = marker.wrapper
655 vim._run('click_marker_element', {
656 elementIndex, type
657 browserOffset: vim._getBrowserOffset()
658 })
659 return false
660
661 helper_follow({name: 'follow_context', callback}, args)
662
663 commands.click_browser_element = ({vim}) ->
664 {window} = vim
665 markerElements = []
666
667 getButtonMenu = (element) ->
668 if element.localName == 'dropmarker' and
669 element.parentNode?.localName == 'toolbarbutton'
670 return element.parentNode.querySelector('menupopup')
671 else
672 return null
673
674 filter = ({complementary}, element, getElementShape) ->
675 type = switch
676 when vim._state.scrollableElements.has(element)
677 'scrollable'
678 when getButtonMenu(element)
679 'dropmarker'
680 when utils.isFocusable(element) or element.onclick
681 'clickable'
682
683 if complementary
684 type = if type then null else 'complementary'
685
686 return unless type
687
688 # `getElementShape(element, -1)` is intentionally _not_ used in the
689 # `complementary` run, because it results in tons of useless hints for
690 # hidden context menus.
691 shape = getElementShape(element)
692 return unless shape.nonCoveredPoint
693
694 # The tabs and their close buttons as well as the tab bar scroll arrows get
695 # better hints, since switching or closing tabs is the most common use case
696 # for the `eb` command.
697 isTab = element.classList?.contains('tabbrowser-tab')
698 isPrioritized =
699 isTab or
700 element.classList?.contains('tab-close-button') or
701 element.classList?.contains('scrollbutton-up') or
702 element.classList?.contains('scrollbutton-down')
703
704 length = markerElements.push(element)
705 return {
706 type, shape, isTab, isPrioritized,
707 combinedArea: shape.area,
708 elementIndex: length - 1,
709 }
710
711 callback = (marker) ->
712 element = markerElements[marker.wrapper.elementIndex]
713 switch marker.wrapper.type
714 when 'scrollable'
715 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
716 when 'dropmarker'
717 getButtonMenu(element).openPopup(
718 element.parentNode, # Anchor node.
719 'after_end', # Position.
720 0, 0, # Offset.
721 false, # Isn’t a context menu.
722 true, # Allow the 'position' attribute to override the above position.
723 )
724 when 'clickable', 'complementary'
725 # VimFx’s own button won’t trigger unless the click is simulated in the
726 # next tick. This might be true for other buttons as well.
727 utils.nextTick(window, ->
728 utils.focusElement(element)
729 browserOffset = {x: window.screenX, y: window.screenY}
730 switch
731 when element.localName == 'tab'
732 # Only 'mousedown' seems to be able to activate tabs.
733 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
734 when element.closest('tab')
735 # If `.click()` is used on a tab close button, its tab will be
736 # selected first, which might cause the selected tab to change.
737 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
738 else
739 # `.click()` seems to trigger more buttons (such as NoScript’s
740 # button and Firefox’s “hamburger” menu button) than simulating
741 # 'click-xul'.
742 element.click()
743 utils.openDropdown(element)
744 )
745 return false
746
747 wrappers = markableElements.find(
748 window, filter.bind(null, {complementary: false})
749 )
750
751 if wrappers.length > 0
752 viewport = viewportUtils.getWindowViewport(window)
753
754 markerContainer = new MarkerContainer({
755 window
756 hintChars: vim.options['hints.chars']
757 adjustZoom: false
758 minWeightDiff: 0
759 getComplementaryWrappers: (callback) ->
760 newWrappers = markableElements.find(
761 window, filter.bind(null, {complementary: true})
762 )
763 callback({wrappers: newWrappers, viewport})
764 })
765 MarkerContainer.remove(window) # Better safe than sorry.
766 markerContainer.container.classList.add('ui')
767 mainWindow = window.document.body or
768 window.document.getElementById('main-window') # fallback <fx72
769 mainWindow.insertBefore(
770 markerContainer.container,
771 mainWindow.firstChild
772 )
773
774 [firstWrappers, secondWrappers] =
775 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
776
777 numChars = markerContainer.alphabet.length
778 numPrimary = markerContainer.primaryHintChars.length
779 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
780 index = 0
781
782 for wrapper in firstWrappers
783 if wrapper.isTab
784 # Given the hint chars `abc de`, give the tabs weights so that the hints
785 # consistently become `a b ca cb cc cd cea ceb cec ced ceea ceeb` and so
786 # on. The rule is that the weight of a tab must be larger than the sum
787 # of all tabs with a longer hint. We start out at `1` and then use
788 # smaller and smaller fractions. This is to make sure that the tabs get
789 # consistent hints as the number of tabs or the size of the window
790 # changes.
791 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
792 wrapper.combinedArea = 1 / numChars ** exponent
793 index += 1
794 else
795 # Make sure that the tab close buttons and the tab bar scroll buttons
796 # come after all the tabs. Treating them all as the same size is fine.
797 # Their sum must be small enough in order not to affect the tab hints.
798 # It might look like using `0` is a good idea, but that results in
799 # increasingly worse hints the more tab close buttons there are.
800 wrapper.combinedArea = 1 / numChars ** numTabs
801
802 # Since most of the best hint characters might be used for the tabs, make
803 # sure that all other elements don’t get really bad hints. First, favor
804 # larger elements by sorting them. Then, give them all the same weight so
805 # that larger elements (such as the location bar, search bar, the web
806 # console input and other large areas in the devtools) don’t overpower the
807 # smaller ones. The usual “the larger the element, the better the hint” rule
808 # doesn’t really apply the same way for browser UI elements as in web pages.
809 secondWrappers.sort((a, b) -> b.combinedArea - a.combinedArea)
810 for wrapper in secondWrappers
811 wrapper.combinedArea = 1
812
813 markerContainer.injectHints(firstWrappers, viewport, 'first')
814 markerContainer.injectHints(secondWrappers, viewport, 'second')
815 vim._enterMode('hints', {markerContainer, callback, matchText: false})
816
817 else
818 vim.notify(translate('notification.follow.none'))
819
820 helper_follow_pattern = (type, {vim}) ->
821 options = {
822 pattern_selector: vim.options.pattern_selector
823 pattern_attrs: vim.options.pattern_attrs
824 patterns: vim.options["#{type}_patterns"]
825 }
826 browserOffset = vim._getBrowserOffset()
827 vim._run('follow_pattern', {type, browserOffset, options})
828
829 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
830
831 commands.follow_next = helper_follow_pattern.bind(null, 'next')
832
833 commands.focus_text_input = ({vim, count}) ->
834 vim.markPageInteraction()
835 vim._run('focus_text_input', {count})
836
837 helper_follow_selectable = ({select}, args) ->
838 {vim} = args
839
840 callback = (marker) ->
841 vim._run('element_text_select', {
842 elementIndex: marker.wrapper.elementIndex
843 full: select
844 scroll: select
845 })
846 vim._enterMode('caret', {select})
847 return false
848
849 helper_follow({name: 'follow_selectable', callback}, args)
850
851 commands.element_text_caret =
852 helper_follow_selectable.bind(null, {select: false})
853
854 commands.element_text_select =
855 helper_follow_selectable.bind(null, {select: true})
856
857 commands.element_text_copy = (args) ->
858 {vim} = args
859
860 callback = (marker) ->
861 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
862 return false
863
864 helper_follow({name: 'follow_selectable', callback}, args)
865
866 helper_copy_marker_element = (vim, elementIndex, property) ->
867 if property == '_selection'
868 # Selecting the text and then copying that selection is better than copying
869 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
870 # and then includes those backticks in the compiled output (!), in hidden
871 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
872 # elements, text selection gives better whitespace than `.textContent`.
873 vim._run('element_text_select', {elementIndex, full: true}, ->
874 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
875 vim._run('clear_selection')
876 )
877 else
878 vim._run('copy_marker_element', {elementIndex, property})
879
880
881
882 findStorage = {
883 lastSearchString: ''
884 busy: false
885 }
886
887 helper_find_from_top_of_viewport = (vim, direction, callback) ->
888 if vim.options.find_from_top_of_viewport
889 vim._run('find_from_top_of_viewport', {direction}, ->
890 callback()
891 )
892 else
893 callback()
894
895 helper_find = ({highlight, linksOnly = false}, {vim}) ->
896 if findStorage.busy
897 # Make sure to enter find mode here, since that’s where `findStorage.busy`
898 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
899 vim._enterMode('find')
900 return
901
902 helpSearchInput = help.getSearchInput(vim.window)
903 if helpSearchInput
904 helpSearchInput.select()
905 return
906
907 # Important: Enter Find mode immediately. See `onInput` for Find mode.
908 findStorage.busy = true
909 vim._enterMode('find')
910
911 helper_mark_last_scroll_position(vim)
912 vim._run('mark_scroll_position', {
913 keyStr: vim.options['scroll.last_find_mark']
914 notify: false
915 })
916
917 helper_find_from_top_of_viewport(vim, FORWARD, ->
918 return unless vim.mode == 'find'
919 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
920 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
921 findBar.startFind(mode)
922 utils.focusElement(findBar._findField, {select: true})
923
924 return if linksOnly
925 return unless highlightButton = findBar.getElement('highlight')
926 if highlightButton.checked != highlight
927 highlightButton.click()
928 )
929 )
930
931 commands.find = helper_find.bind(null, {highlight: false})
932
933 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
934
935 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
936
937 helper_find_again = (direction, {vim}) ->
938 return if findStorage.busy
939
940 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
941 if findStorage.lastSearchString.length == 0
942 vim.notify(translate('notification.find_again.none'))
943 return
944
945 findStorage.busy = true
946
947 helper_mark_last_scroll_position(vim)
948 helper_find_from_top_of_viewport(vim, direction, ->
949 findBar._findField.value = findStorage.lastSearchString
950
951 # `.onFindResult` is temporarily hacked to be able to know when the
952 # asynchronous `.onFindAgainCommand` is done. When PDFs are shown using
953 # PDF.js, `.updateControlState` is called instead of `.onFindResult`, so
954 # hack that one too.
955 originalOnFindResult = findBar.onFindResult
956 originalUpdateControlState = findBar.updateControlState
957
958 findBar.onFindResult = (data) ->
959 # Prevent the find bar from re-opening if there are no matches.
960 data.storeResult = false
961 findBar.onFindResult = originalOnFindResult
962 findBar.updateControlState = originalUpdateControlState
963 findBar.onFindResult(data)
964 callback()
965
966 findBar.updateControlState = (args...) ->
967 # Firefox inconsistently _doesn’t_ re-open the find bar if there are no
968 # matches here, so no need to take care of that in this case.
969 findBar.onFindResult = originalOnFindResult
970 findBar.updateControlState = originalUpdateControlState
971 findBar.updateControlState(args...)
972 callback()
973
974 callback = ->
975 message = findBar._findStatusDesc.textContent
976 vim.notify(message) if message
977 findStorage.busy = false
978
979 findBar.onFindAgainCommand(not direction)
980 )
981 )
982
983 commands.find_next = helper_find_again.bind(null, FORWARD)
984
985 commands.find_previous = helper_find_again.bind(null, BACKWARD)
986
987
988
989 commands.window_new = ({vim}) ->
990 vim.window.OpenBrowserWindow()
991
992 commands.window_new_private = ({vim}) ->
993 vim.window.OpenBrowserWindow({private: true})
994
995 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
996 type = if blacklist then 'blacklist' else 'explicit'
997 vim._enterMode('ignore', {type})
998
999 # Quote next keypress (pass it through to the page).
1000 commands.quote = ({vim, count = 1}) ->
1001 vim._enterMode('ignore', {type: 'explicit', count})
1002
1003 commands.enter_reader_view = ({vim}) ->
1004 button = vim.window.document.getElementById('reader-mode-button')
1005 if not button?.hidden
1006 button.click()
1007 else
1008 vim.notify(translate('notification.enter_reader_view.none'))
1009
1010 commands.reload_config_file = ({vim}) ->
1011 vim._parent.emit('shutdown')
1012 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
1013 when null
1014 vim.notify(translate('notification.reload_config_file.none'))
1015 when true
1016 vim.notify(translate('notification.reload_config_file.success'))
1017 else
1018 vim.notify(translate('notification.reload_config_file.failure'))
1019 )
1020
1021 commands.edit_blacklist = ({vim}) ->
1022 url = vim.browser.currentURI.spec
1023 location = new vim.window.URL(url)
1024 newPattern = if location.host then "*#{location.host}*" else location.href
1025 delimiter = ' '
1026 blacklistString = prefs.get('blacklist')
1027
1028 if vim._isBlacklisted(url)
1029 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
1030 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
1031 return vim.options.blacklist[index].test(url)
1032 )
1033 newBlacklistString = "
1034 #{matching.join(delimiter)}\
1035 #{delimiter.repeat(7)}\
1036 #{nonMatching.join(delimiter)}
1037 "
1038 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1039 else
1040 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1041 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1042
1043 message = """
1044 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1045
1046 #{extraMessage}
1047 """
1048
1049 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
1050 return if input == null
1051 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
1052 # and let the regular pref parsing take care of it.
1053 prefs.set('blacklist', input)
1054 vim._onLocationChange(url)
1055 )
1056
1057 commands.help = ({vim}) ->
1058 help.toggleHelp(vim.window, vim._parent)
1059
1060 commands.esc = ({vim}) ->
1061 vim._run('esc')
1062 vim.hideNotification()
1063
1064 # Firefox does things differently when blurring the location bar, depending on
1065 # whether the autocomplete popup is open or not. To be consistent, always
1066 # close the autocomplete popup before blurring.
1067 vim.window.gURLBar.view.close()
1068
1069 utils.blurActiveBrowserElement(vim)
1070 utils.getFindBar(vim.window.gBrowser).then((findBar) -> findBar.close())
1071
1072 # Better safe than sorry.
1073 MarkerContainer.remove(vim.window)
1074 vim._parent.resetCaretBrowsing()
1075
1076 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1077 help.removeHelp(vim.window)
1078
1079 vim._setFocusType('none') # Better safe than sorry.
1080
1081
1082
1083 module.exports = {
1084 commands
1085 findStorage
1086 }
Imprint / Impressum