]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Since developer tool bar was removed, this prevented Esc from working at
[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 }, vim.browser)
550 reset()
551 )
552
553 # The point of “clicking” scrollable elements is focusing them (which is
554 # done above) so that scrolling commands may scroll them. Simulating a click
555 # here usually _unfocuses_ the element.
556 else if type != 'scrollable'
557 vim._run('click_marker_element', {
558 elementIndex, type
559 browserOffset: vim._getBrowserOffset()
560 preventTargetBlank: vim.options.prevent_target_blank
561 })
562
563 return not isLast
564
565 name = if options.inTab then 'follow_in_tab' else 'follow'
566 helper_follow({name, callback}, args)
567
568 commands.follow =
569 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
570
571 commands.follow_in_tab =
572 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
573
574 commands.follow_in_focused_tab =
575 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
576
577 helper_follow_in_window = (options, args) ->
578 {vim} = args
579
580 callback = (marker) ->
581 vim._focusMarkerElement(marker.wrapper.elementIndex)
582 {href} = marker.wrapper
583 vim.window.openLinkIn(href, 'window', options) if href
584 return false
585
586 helper_follow({name: 'follow_in_tab', callback}, args)
587
588 commands.follow_in_window =
589 helper_follow_in_window.bind(null, {})
590
591 commands.follow_in_private_window =
592 helper_follow_in_window.bind(null, {private: true})
593
594 commands.follow_multiple = (args) ->
595 args.count = Infinity
596 commands.follow(args)
597
598 commands.follow_copy = (args) ->
599 {vim} = args
600
601 callback = (marker) ->
602 property = switch marker.wrapper.type
603 when 'link'
604 'href'
605 when 'text'
606 'value'
607 when 'contenteditable', 'complementary'
608 '_selection'
609 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
610 return false
611
612 helper_follow({name: 'follow_copy', callback}, args)
613
614 commands.follow_focus = (args) ->
615 {vim} = args
616
617 callback = (marker) ->
618 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
619 return false
620
621 helper_follow({name: 'follow_focus', callback}, args)
622
623 commands.open_context_menu = (args) ->
624 {vim} = args
625
626 callback = (marker) ->
627 {type, elementIndex} = marker.wrapper
628 vim._run('click_marker_element', {
629 elementIndex, type
630 browserOffset: vim._getBrowserOffset()
631 })
632 return false
633
634 helper_follow({name: 'follow_context', callback}, args)
635
636 commands.click_browser_element = ({vim}) ->
637 {window} = vim
638 markerElements = []
639
640 getButtonMenu = (element) ->
641 if element.localName == 'dropmarker' and
642 element.parentNode?.localName == 'toolbarbutton'
643 return element.parentNode.querySelector('menupopup')
644 else
645 return null
646
647 filter = ({complementary}, element, getElementShape) ->
648 type = switch
649 when vim._state.scrollableElements.has(element)
650 'scrollable'
651 when getButtonMenu(element)
652 'dropmarker'
653 when utils.isFocusable(element) or
654 (element.onclick and element.localName != 'statuspanel')
655 'clickable'
656
657 if complementary
658 type = if type then null else 'complementary'
659
660 return unless type
661
662 # `getElementShape(element, -1)` is intentionally _not_ used in the
663 # `complementary` run, because it results in tons of useless hints for
664 # hidden context menus.
665 shape = getElementShape(element)
666 return unless shape.nonCoveredPoint
667
668 # The tabs and their close buttons as well as the tab bar scroll arrows get
669 # better hints, since switching or closing tabs is the most common use case
670 # for the `eb` command.
671 isTab = element.classList?.contains('tabbrowser-tab')
672 isPrioritized =
673 isTab or
674 element.classList?.contains('tab-close-button') or
675 element.classList?.contains('scrollbutton-up') or
676 element.classList?.contains('scrollbutton-down')
677
678 length = markerElements.push(element)
679 return {
680 type, shape, isTab, isPrioritized,
681 combinedArea: shape.area,
682 elementIndex: length - 1,
683 }
684
685 callback = (marker) ->
686 element = markerElements[marker.wrapper.elementIndex]
687 switch marker.wrapper.type
688 when 'scrollable'
689 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
690 when 'dropmarker'
691 getButtonMenu(element).openPopup(
692 element.parentNode, # Anchor node.
693 'after_end', # Position.
694 0, 0, # Offset.
695 false, # Isn’t a context menu.
696 true, # Allow the 'position' attribute to override the above position.
697 )
698 when 'clickable', 'complementary'
699 # VimFx’s own button won’t trigger unless the click is simulated in the
700 # next tick. This might be true for other buttons as well.
701 utils.nextTick(window, ->
702 utils.focusElement(element)
703 browserOffset = {x: window.screenX, y: window.screenY}
704 switch
705 when element.localName == 'tab'
706 # Only 'mousedown' seems to be able to activate tabs.
707 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
708 when element.closest('tab')
709 # If `.click()` is used on a tab close button, its tab will be
710 # selected first, which might cause the selected tab to change.
711 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
712 else
713 # `.click()` seems to trigger more buttons (such as NoScript’s
714 # button and Firefox’s “hamburger” menu button) than simulating
715 # 'click-xul'.
716 element.click()
717 utils.openDropdown(element)
718 )
719 return false
720
721 wrappers = markableElements.find(
722 window, filter.bind(null, {complementary: false})
723 )
724
725 if wrappers.length > 0
726 viewport = viewportUtils.getWindowViewport(window)
727
728 markerContainer = new MarkerContainer({
729 window
730 hintChars: vim.options['hints.chars']
731 adjustZoom: false
732 minWeightDiff: 0
733 getComplementaryWrappers: (callback) ->
734 newWrappers = markableElements.find(
735 window, filter.bind(null, {complementary: true})
736 )
737 callback({wrappers: newWrappers, viewport})
738 })
739 MarkerContainer.remove(window) # Better safe than sorry.
740 markerContainer.container.classList.add('ui')
741 window.document.getElementById('browser-panel').appendChild(
742 markerContainer.container
743 )
744
745 [firstWrappers, secondWrappers] =
746 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
747
748 numChars = markerContainer.alphabet.length
749 numPrimary = markerContainer.primaryHintChars.length
750 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
751 index = 0
752
753 for wrapper in firstWrappers
754 if wrapper.isTab
755 # Given the hint chars `abc de`, give the tabs weights so that the hints
756 # consistently become `a b ca cb cc cd cea ceb cec ced ceea ceeb` and so
757 # on. The rule is that the weight of a tab must be larger than the sum
758 # of all tabs with a longer hint. We start out at `1` and then use
759 # smaller and smaller fractions. This is to make sure that the tabs get
760 # consistent hints as the number of tabs or the size of the window
761 # changes.
762 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
763 wrapper.combinedArea = 1 / numChars ** exponent
764 index += 1
765 else
766 # Make sure that the tab close buttons and the tab bar scroll buttons
767 # come after all the tabs. Treating them all as the same size is fine.
768 # Their sum must be small enough in order not to affect the tab hints.
769 # It might look like using `0` is a good idea, but that results in
770 # increasingly worse hints the more tab close buttons there are.
771 wrapper.combinedArea = 1 / numChars ** numTabs
772
773 # Since most of the best hint characters might be used for the tabs, make
774 # sure that all other elements don’t get really bad hints. First, favor
775 # larger elements by sorting them. Then, give them all the same weight so
776 # that larger elements (such as the location bar, search bar, the web
777 # console input and other large areas in the devtools) don’t overpower the
778 # smaller ones. The usual “the larger the element, the better the hint” rule
779 # doesn’t really apply the same way for browser UI elements as in web pages.
780 secondWrappers.sort((a, b) -> b.combinedArea - a.combinedArea)
781 for wrapper in secondWrappers
782 wrapper.combinedArea = 1
783
784 markerContainer.injectHints(firstWrappers, viewport, 'first')
785 markerContainer.injectHints(secondWrappers, viewport, 'second')
786 vim._enterMode('hints', {markerContainer, callback, matchText: false})
787
788 else
789 vim.notify(translate('notification.follow.none'))
790
791 helper_follow_pattern = (type, {vim}) ->
792 options = {
793 pattern_selector: vim.options.pattern_selector
794 pattern_attrs: vim.options.pattern_attrs
795 patterns: vim.options["#{type}_patterns"]
796 }
797 browserOffset = vim._getBrowserOffset()
798 vim._run('follow_pattern', {type, browserOffset, options})
799
800 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
801
802 commands.follow_next = helper_follow_pattern.bind(null, 'next')
803
804 commands.focus_text_input = ({vim, count}) ->
805 vim.markPageInteraction()
806 vim._run('focus_text_input', {count})
807
808 helper_follow_selectable = ({select}, args) ->
809 {vim} = args
810
811 callback = (marker) ->
812 vim._run('element_text_select', {
813 elementIndex: marker.wrapper.elementIndex
814 full: select
815 scroll: select
816 })
817 vim._enterMode('caret', {select})
818 return false
819
820 helper_follow({name: 'follow_selectable', callback}, args)
821
822 commands.element_text_caret =
823 helper_follow_selectable.bind(null, {select: false})
824
825 commands.element_text_select =
826 helper_follow_selectable.bind(null, {select: true})
827
828 commands.element_text_copy = (args) ->
829 {vim} = args
830
831 callback = (marker) ->
832 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
833 return false
834
835 helper_follow({name: 'follow_selectable', callback}, args)
836
837 helper_copy_marker_element = (vim, elementIndex, property) ->
838 if property == '_selection'
839 # Selecting the text and then copying that selection is better than copying
840 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
841 # and then includes those backticks in the compiled output (!), in hidden
842 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
843 # elements, text selection gives better whitespace than `.textContent`.
844 vim._run('element_text_select', {elementIndex, full: true}, ->
845 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
846 vim._run('clear_selection')
847 )
848 else
849 vim._run('copy_marker_element', {elementIndex, property})
850
851
852
853 findStorage = {
854 lastSearchString: ''
855 busy: false
856 }
857
858 helper_find_from_top_of_viewport = (vim, direction, callback) ->
859 if vim.options.find_from_top_of_viewport
860 vim._run('find_from_top_of_viewport', {direction}, ->
861 callback()
862 )
863 else
864 callback()
865
866 helper_find = ({highlight, linksOnly = false}, {vim}) ->
867 if findStorage.busy
868 # Make sure to enter find mode here, since that’s where `findStorage.busy`
869 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
870 vim._enterMode('find')
871 return
872
873 helpSearchInput = help.getSearchInput(vim.window)
874 if helpSearchInput
875 helpSearchInput.select()
876 return
877
878 # Important: Enter Find mode immediately. See `onInput` for Find mode.
879 findStorage.busy = true
880 vim._enterMode('find')
881
882 helper_mark_last_scroll_position(vim)
883 vim._run('mark_scroll_position', {
884 keyStr: vim.options['scroll.last_find_mark']
885 notify: false
886 })
887
888 helper_find_from_top_of_viewport(vim, FORWARD, ->
889 return unless vim.mode == 'find'
890 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
891 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
892 findBar.startFind(mode)
893 utils.focusElement(findBar._findField, {select: true})
894
895 return if linksOnly
896 return unless highlightButton = findBar.getElement('highlight')
897 if highlightButton.checked != highlight
898 highlightButton.click()
899 )
900 )
901
902 commands.find = helper_find.bind(null, {highlight: false})
903
904 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
905
906 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
907
908 helper_find_again = (direction, {vim}) ->
909 return if findStorage.busy
910
911 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
912 if findStorage.lastSearchString.length == 0
913 vim.notify(translate('notification.find_again.none'))
914 return
915
916 findStorage.busy = true
917
918 helper_mark_last_scroll_position(vim)
919 helper_find_from_top_of_viewport(vim, direction, ->
920 findBar._findField.value = findStorage.lastSearchString
921
922 # `.onFindResult` is temporarily hacked to be able to know when the
923 # asynchronous `.onFindAgainCommand` is done. When PDFs are shown using
924 # PDF.js, `.updateControlState` is called instead of `.onFindResult`, so
925 # hack that one too.
926 originalOnFindResult = findBar.onFindResult
927 originalUpdateControlState = findBar.updateControlState
928
929 findBar.onFindResult = (data) ->
930 # Prevent the find bar from re-opening if there are no matches.
931 data.storeResult = false
932 findBar.onFindResult = originalOnFindResult
933 findBar.updateControlState = originalUpdateControlState
934 findBar.onFindResult(data)
935 callback()
936
937 findBar.updateControlState = (args...) ->
938 # Firefox inconsistently _doesn’t_ re-open the find bar if there are no
939 # matches here, so no need to take care of that in this case.
940 findBar.onFindResult = originalOnFindResult
941 findBar.updateControlState = originalUpdateControlState
942 findBar.updateControlState(args...)
943 callback()
944
945 callback = ->
946 message = findBar._findStatusDesc.textContent
947 vim.notify(message) if message
948 findStorage.busy = false
949
950 findBar.onFindAgainCommand(not direction)
951 )
952 )
953
954 commands.find_next = helper_find_again.bind(null, FORWARD)
955
956 commands.find_previous = helper_find_again.bind(null, BACKWARD)
957
958
959
960 commands.window_new = ({vim}) ->
961 vim.window.OpenBrowserWindow()
962
963 commands.window_new_private = ({vim}) ->
964 vim.window.OpenBrowserWindow({private: true})
965
966 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
967 type = if blacklist then 'blacklist' else 'explicit'
968 vim._enterMode('ignore', {type})
969
970 # Quote next keypress (pass it through to the page).
971 commands.quote = ({vim, count = 1}) ->
972 vim._enterMode('ignore', {type: 'explicit', count})
973
974 commands.enter_reader_view = ({vim}) ->
975 button = vim.window.document.getElementById('reader-mode-button')
976 if not button?.hidden
977 button.click()
978 else
979 vim.notify(translate('notification.enter_reader_view.none'))
980
981 commands.reload_config_file = ({vim}) ->
982 vim._parent.emit('shutdown')
983 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
984 when null
985 vim.notify(translate('notification.reload_config_file.none'))
986 when true
987 vim.notify(translate('notification.reload_config_file.success'))
988 else
989 vim.notify(translate('notification.reload_config_file.failure'))
990 )
991
992 commands.edit_blacklist = ({vim}) ->
993 url = vim.browser.currentURI.spec
994 location = new vim.window.URL(url)
995 newPattern = if location.host then "*#{location.host}*" else location.href
996 delimiter = ' '
997 blacklistString = prefs.get('blacklist')
998
999 if vim._isBlacklisted(url)
1000 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
1001 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
1002 return vim.options.blacklist[index].test(url)
1003 )
1004 newBlacklistString = "
1005 #{matching.join(delimiter)}\
1006 #{delimiter.repeat(7)}\
1007 #{nonMatching.join(delimiter)}
1008 "
1009 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1010 else
1011 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1012 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1013
1014 message = """
1015 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1016
1017 #{extraMessage}
1018 """
1019
1020 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
1021 return if input == null
1022 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
1023 # and let the regular pref parsing take care of it.
1024 prefs.set('blacklist', input)
1025 vim._onLocationChange(url)
1026 )
1027
1028 commands.help = ({vim}) ->
1029 help.toggleHelp(vim.window, vim._parent)
1030
1031 commands.dev = ({vim}) ->
1032 vim.window.DeveloperToolbar.show(true) # `true` to focus.
1033
1034 commands.esc = ({vim}) ->
1035 vim._run('esc')
1036 vim.hideNotification()
1037
1038 # Firefox does things differently when blurring the location bar, depending on
1039 # whether the autocomplete popup is open or not. To be consistent, always
1040 # close the autocomplete popup before blurring.
1041 vim.window.gURLBar.closePopup()
1042
1043 utils.blurActiveBrowserElement(vim)
1044 utils.getFindBar(vim.window.gBrowser).then((findBar) -> findBar.close())
1045
1046 # Better safe than sorry.
1047 MarkerContainer.remove(vim.window)
1048 vim._parent.resetCaretBrowsing()
1049
1050 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1051 help.removeHelp(vim.window)
1052
1053 vim._setFocusType('none') # Better safe than sorry.
1054
1055
1056
1057 module.exports = {
1058 commands
1059 findStorage
1060 }
Imprint / Impressum