]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
hotfix: 'F'
[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, # <=fx79
555 frameID: json.frameID, # >=fx80
556 allowInheritPrincipal: true,
557 }
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)
563
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)
570 contentAreaClick({
571 href: marker.wrapper.href
572 shiftKey: not inBackground
573 ctrlKey: true
574 metaKey: true
575 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
576 triggeringPrincipal: window.document.nodePrincipal
577 }, vim.browser)
578 reset()
579 )
580
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', {
586 elementIndex, type
587 browserOffset: vim._getBrowserOffset()
588 preventTargetBlank: vim.options.prevent_target_blank
589 })
590
591 return not isLast
592
593 name = if options.inTab then 'follow_in_tab' else 'follow'
594 helper_follow({name, callback}, args)
595
596 commands.follow =
597 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
598
599 commands.follow_in_tab =
600 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
601
602 commands.follow_in_focused_tab =
603 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
604
605 helper_follow_in_window = (options, args) ->
606 {vim} = args
607
608 callback = (marker) ->
609 vim._focusMarkerElement(marker.wrapper.elementIndex)
610 {href} = marker.wrapper
611 vim.window.openLinkIn(href, 'window', options) if href
612 return false
613
614 helper_follow({name: 'follow_in_tab', callback}, args)
615
616 commands.follow_in_window =
617 helper_follow_in_window.bind(null, {})
618
619 commands.follow_in_private_window =
620 helper_follow_in_window.bind(null, {private: true})
621
622 commands.follow_multiple = (args) ->
623 args.count = Infinity
624 commands.follow(args)
625
626 commands.follow_copy = (args) ->
627 {vim} = args
628
629 callback = (marker) ->
630 property = switch marker.wrapper.type
631 when 'link'
632 'href'
633 when 'text'
634 'value'
635 when 'contenteditable', 'complementary'
636 '_selection'
637 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
638 return false
639
640 helper_follow({name: 'follow_copy', callback}, args)
641
642 commands.follow_focus = (args) ->
643 {vim} = args
644
645 callback = (marker) ->
646 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
647 return false
648
649 helper_follow({name: 'follow_focus', callback}, args)
650
651 commands.open_context_menu = (args) ->
652 {vim} = args
653
654 callback = (marker) ->
655 {type, elementIndex} = marker.wrapper
656 vim._run('click_marker_element', {
657 elementIndex, type
658 browserOffset: vim._getBrowserOffset()
659 })
660 return false
661
662 helper_follow({name: 'follow_context', callback}, args)
663
664 commands.click_browser_element = ({vim}) ->
665 {window} = vim
666 markerElements = []
667
668 getButtonMenu = (element) ->
669 if element.localName == 'dropmarker' and
670 element.parentNode?.localName == 'toolbarbutton'
671 return element.parentNode.querySelector('menupopup')
672 else
673 return null
674
675 filter = ({complementary}, element, getElementShape) ->
676 type = switch
677 when vim._state.scrollableElements.has(element)
678 'scrollable'
679 when getButtonMenu(element)
680 'dropmarker'
681 when utils.isFocusable(element) or element.onclick
682 'clickable'
683
684 if complementary
685 type = if type then null else 'complementary'
686
687 return unless type
688
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
694
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')
699 isPrioritized =
700 isTab or
701 element.classList?.contains('tab-close-button') or
702 element.classList?.contains('scrollbutton-up') or
703 element.classList?.contains('scrollbutton-down')
704
705 length = markerElements.push(element)
706 return {
707 type, shape, isTab, isPrioritized,
708 combinedArea: shape.area,
709 elementIndex: length - 1,
710 }
711
712 callback = (marker) ->
713 element = markerElements[marker.wrapper.elementIndex]
714 switch marker.wrapper.type
715 when 'scrollable'
716 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
717 when 'dropmarker'
718 getButtonMenu(element).openPopup(
719 element.parentNode, # Anchor node.
720 'after_end', # Position.
721 0, 0, # Offset.
722 false, # Isn’t a context menu.
723 true, # Allow the 'position' attribute to override the above position.
724 )
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}
731 switch
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)
739 else
740 # `.click()` seems to trigger more buttons (such as NoScript’s
741 # button and Firefox’s “hamburger” menu button) than simulating
742 # 'click-xul'.
743 element.click()
744 utils.openDropdown(element)
745 )
746 return false
747
748 wrappers = markableElements.find(
749 window, filter.bind(null, {complementary: false})
750 )
751
752 if wrappers.length > 0
753 viewport = viewportUtils.getWindowViewport(window)
754
755 markerContainer = new MarkerContainer({
756 window
757 hintChars: vim.options['hints.chars']
758 adjustZoom: false
759 minWeightDiff: 0
760 getComplementaryWrappers: (callback) ->
761 newWrappers = markableElements.find(
762 window, filter.bind(null, {complementary: true})
763 )
764 callback({wrappers: newWrappers, viewport})
765 })
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
773 )
774
775 [firstWrappers, secondWrappers] =
776 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
777
778 numChars = markerContainer.alphabet.length
779 numPrimary = markerContainer.primaryHintChars.length
780 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
781 index = 0
782
783 for wrapper in firstWrappers
784 if wrapper.isTab
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
791 # changes.
792 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
793 wrapper.combinedArea = 1 / numChars ** exponent
794 index += 1
795 else
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
802
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
813
814 markerContainer.injectHints(firstWrappers, viewport, 'first')
815 markerContainer.injectHints(secondWrappers, viewport, 'second')
816 vim._enterMode('hints', {markerContainer, callback, matchText: false})
817
818 else
819 vim.notify(translate('notification.follow.none'))
820
821 helper_follow_pattern = (type, {vim}) ->
822 options = {
823 pattern_selector: vim.options.pattern_selector
824 pattern_attrs: vim.options.pattern_attrs
825 patterns: vim.options["#{type}_patterns"]
826 }
827 browserOffset = vim._getBrowserOffset()
828 vim._run('follow_pattern', {type, browserOffset, options})
829
830 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
831
832 commands.follow_next = helper_follow_pattern.bind(null, 'next')
833
834 commands.focus_text_input = ({vim, count}) ->
835 vim.markPageInteraction()
836 vim._run('focus_text_input', {count})
837
838 helper_follow_selectable = ({select}, args) ->
839 {vim} = args
840
841 callback = (marker) ->
842 vim._run('element_text_select', {
843 elementIndex: marker.wrapper.elementIndex
844 full: select
845 scroll: select
846 })
847 vim._enterMode('caret', {select})
848 return false
849
850 helper_follow({name: 'follow_selectable', callback}, args)
851
852 commands.element_text_caret =
853 helper_follow_selectable.bind(null, {select: false})
854
855 commands.element_text_select =
856 helper_follow_selectable.bind(null, {select: true})
857
858 commands.element_text_copy = (args) ->
859 {vim} = args
860
861 callback = (marker) ->
862 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
863 return false
864
865 helper_follow({name: 'follow_selectable', callback}, args)
866
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')
877 )
878 else
879 vim._run('copy_marker_element', {elementIndex, property})
880
881
882
883 findStorage = {
884 lastSearchString: ''
885 busy: false
886 }
887
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}, ->
891 callback()
892 )
893 else
894 callback()
895
896 helper_find = ({highlight, linksOnly = false}, {vim}) ->
897 if findStorage.busy
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')
901 return
902
903 helpSearchInput = help.getSearchInput(vim.window)
904 if helpSearchInput
905 helpSearchInput.select()
906 return
907
908 # Important: Enter Find mode immediately. See `onInput` for Find mode.
909 findStorage.busy = true
910 vim._enterMode('find')
911
912 helper_mark_last_scroll_position(vim)
913 vim._run('mark_scroll_position', {
914 keyStr: vim.options['scroll.last_find_mark']
915 notify: false
916 })
917
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})
924
925 return if linksOnly
926 return unless highlightButton = findBar.getElement('highlight')
927 if highlightButton.checked != highlight
928 highlightButton.click()
929 )
930 )
931
932 commands.find = helper_find.bind(null, {highlight: false})
933
934 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
935
936 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
937
938 helper_find_again = (direction, {vim}) ->
939 return if findStorage.busy
940
941 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
942 if findStorage.lastSearchString.length == 0
943 vim.notify(translate('notification.find_again.none'))
944 return
945
946 findStorage.busy = true
947
948 helper_mark_last_scroll_position(vim)
949 helper_find_from_top_of_viewport(vim, direction, ->
950 findBar._findField.value = findStorage.lastSearchString
951
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
955 # hack that one too.
956 originalOnFindResult = findBar.onFindResult
957 originalUpdateControlState = findBar.updateControlState
958
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)
965 callback()
966
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...)
973 callback()
974
975 callback = ->
976 message = findBar._findStatusDesc.textContent
977 vim.notify(message) if message
978 findStorage.busy = false
979
980 findBar.onFindAgainCommand(not direction)
981 )
982 )
983
984 commands.find_next = helper_find_again.bind(null, FORWARD)
985
986 commands.find_previous = helper_find_again.bind(null, BACKWARD)
987
988
989
990 commands.window_new = ({vim}) ->
991 vim.window.OpenBrowserWindow()
992
993 commands.window_new_private = ({vim}) ->
994 vim.window.OpenBrowserWindow({private: true})
995
996 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
997 type = if blacklist then 'blacklist' else 'explicit'
998 vim._enterMode('ignore', {type})
999
1000 # Quote next keypress (pass it through to the page).
1001 commands.quote = ({vim, count = 1}) ->
1002 vim._enterMode('ignore', {type: 'explicit', count})
1003
1004 commands.enter_reader_view = ({vim}) ->
1005 button = vim.window.document.getElementById('reader-mode-button')
1006 if not button?.hidden
1007 button.click()
1008 else
1009 vim.notify(translate('notification.enter_reader_view.none'))
1010
1011 commands.reload_config_file = ({vim}) ->
1012 vim._parent.emit('shutdown')
1013 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
1014 when null
1015 vim.notify(translate('notification.reload_config_file.none'))
1016 when true
1017 vim.notify(translate('notification.reload_config_file.success'))
1018 else
1019 vim.notify(translate('notification.reload_config_file.failure'))
1020 )
1021
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
1026 delimiter = ' '
1027 blacklistString = prefs.get('blacklist')
1028
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)
1033 )
1034 newBlacklistString = "
1035 #{matching.join(delimiter)}\
1036 #{delimiter.repeat(7)}\
1037 #{nonMatching.join(delimiter)}
1038 "
1039 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1040 else
1041 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1042 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1043
1044 message = """
1045 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1046
1047 #{extraMessage}
1048 """
1049
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)
1056 )
1057
1058 commands.help = ({vim}) ->
1059 help.toggleHelp(vim.window, vim._parent)
1060
1061 commands.esc = ({vim}) ->
1062 vim._run('esc')
1063 vim.hideNotification()
1064
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()
1069
1070 utils.blurActiveBrowserElement(vim)
1071 utils.getFindBar(vim.window.gBrowser).then((findBar) -> findBar.close())
1072
1073 # Better safe than sorry.
1074 MarkerContainer.remove(vim.window)
1075 vim._parent.resetCaretBrowsing()
1076
1077 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1078 help.removeHelp(vim.window)
1079
1080 vim._setFocusType('none') # Better safe than sorry.
1081
1082
1083
1084 module.exports = {
1085 commands
1086 findStorage
1087 }
Imprint / Impressum