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