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