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