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