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