]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Fix TypeError when hitting ESC
[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 {ContentClick} = Cu.import('resource:///modules/ContentClick.jsm', {})
20 {FORWARD, BACKWARD} = SelectionManager
21
22 READER_VIEW_PREFIX = 'about:reader?url='
23 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
24
25 commands = {}
26
27
28
29 commands.focus_location_bar = ({vim}) ->
30 vim.window.focusAndSelectUrlBar()
31
32 commands.focus_search_bar = ({vim, count}) ->
33 # The `.webSearch()` method opens a search engine in a tab if the search bar
34 # has been removed. Therefore we first check if it exists.
35 if vim.window.BrowserSearch.searchBar
36 vim.window.BrowserSearch.webSearch()
37 else
38 vim.notify(translate('notification.focus_search_bar.none'))
39
40 helper_paste_and_go = (props, {vim}) ->
41 {gURLBar} = vim.window
42 gURLBar.value = vim.window.readFromClipboard()
43 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
44
45 commands.paste_and_go = helper_paste_and_go.bind(null, null)
46
47 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
48
49 commands.copy_current_url = ({vim}) ->
50 url = vim.window.gBrowser.currentURI.spec
51 adjustedUrl =
52 if url.startsWith(READER_VIEW_PREFIX)
53 decodeURIComponent(url[READER_VIEW_PREFIX.length..])
54 else
55 url
56 utils.writeToClipboard(adjustedUrl)
57 vim.notify(translate('notification.copy_current_url.success'))
58
59 commands.go_up_path = ({vim, count}) ->
60 vim._run('go_up_path', {count})
61
62 commands.go_to_root = ({vim}) ->
63 vim._run('go_to_root')
64
65 commands.go_home = ({vim}) ->
66 vim.window.BrowserHome()
67
68 helper_go_history = (direction, {vim, count = 1}) ->
69 {window} = vim
70 {SessionStore, gBrowser} = window
71
72 if (direction == 'back' and not gBrowser.canGoBack) or
73 (direction == 'forward' and not gBrowser.canGoForward)
74 vim.notify(translate("notification.history_#{direction}.limit"))
75 return
76
77 # `SessionStore.getSessionHistory()` (used below to support counts) starts
78 # lots of asynchronous tasks internally, which is a bit unreliable, it has
79 # turned out. The primary use of the `history_back` and `history_forward`
80 # commands is to go _one_ step back or forward, though, so those cases are
81 # optimized to use more reliable ways of going back and forward. Also, some
82 # extensions override the following functions, so calling them also gives
83 # better interoperability.
84 if count == 1
85 if direction == 'back'
86 window.BrowserBack()
87 else
88 window.BrowserForward()
89 return
90
91 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
92 {index} = sessionHistory
93 newIndex = index + count * (if direction == 'back' then -1 else 1)
94 newIndex = Math.max(newIndex, 0)
95 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
96 gBrowser.gotoIndex(newIndex)
97 )
98
99 commands.history_back = helper_go_history.bind(null, 'back')
100
101 commands.history_forward = helper_go_history.bind(null, 'forward')
102
103 commands.history_list = ({vim}) ->
104 menu = vim.window.document.getElementById('backForwardMenu')
105 utils.openPopup(menu)
106 if menu.childElementCount == 0
107 vim.notify(translate('notification.history_list.none'))
108
109 commands.reload = ({vim}) ->
110 vim.window.BrowserReload()
111
112 commands.reload_force = ({vim}) ->
113 vim.window.BrowserReloadSkipCache()
114
115 commands.reload_all = ({vim}) ->
116 vim.window.gBrowser.reloadAllTabs()
117
118 commands.reload_all_force = ({vim}) ->
119 for tab in vim.window.gBrowser.visibleTabs
120 gBrowser = tab.linkedBrowser
121 consts = gBrowser.webNavigation
122 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
123 gBrowser.reload(flags)
124 return
125
126 commands.stop = ({vim}) ->
127 vim.window.BrowserStop()
128
129 commands.stop_all = ({vim}) ->
130 for tab in vim.window.gBrowser.visibleTabs
131 tab.linkedBrowser.stop()
132 return
133
134
135
136 scrollData = {
137 nonce: null
138 springConstant: null
139 lastRepeat: 0
140 }
141
142 helper_scroll = (vim, event, args...) ->
143 [
144 method, type, directions, amounts
145 properties = null, adjustment = 0, name = 'scroll', extra = {}
146 ] = args
147
148 elapsed = event.timeStamp - scrollData.lastRepeat
149
150 if event.repeat and elapsed < vim.options['scroll.repeat_timeout']
151 return
152
153 scrollData.lastRepeat = event.timeStamp
154
155 options = {
156 method, type, directions, amounts, properties, adjustment, extra
157 smooth: (
158 prefs.root.get('general.smoothScroll') and
159 prefs.root.get("general.smoothScroll.#{type}")
160 )
161 }
162
163 # Temporarily set Firefox’s “spring constant” pref to get the desired smooth
164 # scrolling speed. Reset it `reset_timeout` milliseconds after the last
165 # scrolling command was invoked.
166 scrollData.nonce = nonce = {}
167 scrollData.springConstant ?= prefs.root.get(SPRING_CONSTANT_PREF)
168 prefs.root.set(
169 SPRING_CONSTANT_PREF,
170 vim.options["smoothScroll.#{type}.spring-constant"]
171 )
172 reset = ->
173 vim.window.setTimeout((->
174 return unless scrollData.nonce == nonce
175 prefs.root.set(SPRING_CONSTANT_PREF, scrollData.springConstant)
176 scrollData.nonce = null
177 scrollData.springConstant = null
178 ), vim.options['scroll.reset_timeout'])
179
180 {isUIEvent = vim.isUIEvent(event)} = extra
181 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
182 if isUIEvent or helpScroll
183 activeElement = helpScroll or utils.getActiveElement(vim.window)
184 if vim._state.scrollableElements.has(activeElement) or helpScroll
185 viewportUtils.scroll(activeElement, options)
186 reset()
187 return
188
189 vim._run(name, options, reset)
190
191
192 helper_scrollByLinesX = (amount, {vim, event, count = 1}) ->
193 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
194 boost = if event.repeat then vim.options['scroll.horizontal_boost'] else 1
195 helper_scroll(
196 vim, event, 'scrollBy', 'lines', ['left'],
197 [amount * distance * boost * count * 5]
198 )
199
200 helper_scrollByLinesY = (amount, {vim, event, count = 1}) ->
201 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
202 boost = if event.repeat then vim.options['scroll.vertical_boost'] else 1
203 helper_scroll(
204 vim, event, 'scrollBy', 'lines', ['top'],
205 [amount * distance * boost * count * 20]
206 )
207
208 helper_scrollByPagesY = (amount, type, {vim, event, count = 1}) ->
209 adjustment = vim.options["scroll.#{type}_page_adjustment"]
210 helper_scroll(
211 vim, event, 'scrollBy', 'pages', ['top'], [amount * count],
212 ['clientHeight'], adjustment
213 )
214
215 helper_scrollToX = (amount, {vim, event}) ->
216 helper_mark_last_scroll_position(vim)
217 helper_scroll(
218 vim, event, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
219 )
220
221 helper_scrollToY = (amount, {vim, event}) ->
222 helper_mark_last_scroll_position(vim)
223 helper_scroll(
224 vim, event, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
225 )
226
227 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
228 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
229 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
230 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
231 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
232 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
233 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
234 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
235 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
236 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
237 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
238 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
239
240 helper_mark_last_scroll_position = (vim) ->
241 keyStr = vim.options['scroll.last_position_mark']
242 vim._run('mark_scroll_position', {keyStr, notify: false, addToJumpList: true})
243
244 commands.mark_scroll_position = ({vim}) ->
245 vim._enterMode('marks', (keyStr) ->
246 vim._run('mark_scroll_position', {keyStr})
247 )
248 vim.notify(translate('notification.mark_scroll_position.enter'))
249
250 commands.scroll_to_mark = ({vim, event}) ->
251 vim._enterMode('marks', (keyStr) ->
252 lastPositionMark = vim.options['scroll.last_position_mark']
253 helper_scroll(
254 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
255 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_mark'
256 {keyStr, lastPositionMark, isUIEvent: false}
257 )
258 vim.hideNotification()
259 )
260 vim.notify(translate('notification.scroll_to_mark.enter'))
261
262 helper_scroll_to_position = (direction, {vim, event, count = 1}) ->
263 lastPositionMark = vim.options['scroll.last_position_mark']
264 helper_scroll(
265 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
266 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_position'
267 {count, direction, lastPositionMark, isUIEvent: false}
268 )
269
270 commands.scroll_to_previous_position =
271 helper_scroll_to_position.bind(null, 'previous')
272
273 commands.scroll_to_next_position =
274 helper_scroll_to_position.bind(null, 'next')
275
276
277
278 commands.tab_new = ({vim}) ->
279 utils.nextTick(vim.window, ->
280 vim.window.BrowserOpenTab()
281 )
282
283 commands.tab_new_after_current = ({vim}) ->
284 {window} = vim
285 newTabPosition = window.gBrowser.selectedTab._tPos + 1
286 utils.nextTick(window, ->
287 utils.listenOnce(window, 'TabOpen', (event) ->
288 newTab = event.originalTarget
289 window.gBrowser.moveTabTo(newTab, newTabPosition)
290 )
291 window.BrowserOpenTab()
292 )
293
294 commands.tab_duplicate = ({vim}) ->
295 {gBrowser} = vim.window
296 utils.nextTick(vim.window, ->
297 gBrowser.duplicateTab(gBrowser.selectedTab)
298 )
299
300 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
301 tabs = gBrowser.visibleTabs
302 {selectedTab} = gBrowser
303
304 currentIndex = tabs.indexOf(selectedTab)
305 absoluteIndex = currentIndex + relativeIndex
306 numTabsTotal = tabs.length
307 numPinnedTabs = gBrowser._numPinnedTabs
308
309 [numTabs, min] = switch
310 when not pinnedSeparate
311 [numTabsTotal, 0]
312 when selectedTab.pinned
313 [numPinnedTabs, 0]
314 else
315 [numTabsTotal - numPinnedTabs, numPinnedTabs]
316
317 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
318 # current direction.
319 if (relativeIndex < 0 and currentIndex == min) or
320 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
321 if absoluteIndex < min
322 absoluteIndex += numTabs
323 else if absoluteIndex >= min + numTabs
324 absoluteIndex -= numTabs
325
326 absoluteIndex = Math.max(min, absoluteIndex)
327 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
328
329 return absoluteIndex
330
331 helper_switch_tab = (direction, {vim, count = 1}) ->
332 {gBrowser} = vim.window
333 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
334 utils.nextTick(vim.window, ->
335 gBrowser.selectTabAtIndex(index)
336 )
337
338 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
339
340 commands.tab_select_next = helper_switch_tab.bind(null, +1)
341
342 helper_is_visited = (tab) ->
343 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
344
345 commands.tab_select_most_recent = ({vim, count = 1}) ->
346 {gBrowser} = vim.window
347 tabsSorted =
348 Array.prototype.filter.call(
349 gBrowser.tabs,
350 (tab) -> not tab.closing and helper_is_visited(tab)
351 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
352 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
353 if tab
354 gBrowser.selectedTab = tab
355 else
356 vim.notify(translate('notification.tab_select_most_recent.none'))
357
358 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
359 {gBrowser} = vim.window
360 tabsSorted =
361 Array.prototype.filter.call(
362 gBrowser.tabs,
363 (tab) -> not tab.closing and not helper_is_visited(tab)
364 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
365 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
366 if tab
367 gBrowser.selectedTab = tab
368 else
369 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
370
371 helper_move_tab = (direction, {vim, count = 1}) ->
372 {gBrowser} = vim.window
373 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
374 utils.nextTick(vim.window, ->
375 gBrowser.moveTabTo(gBrowser.selectedTab, index)
376 )
377
378 commands.tab_move_backward = helper_move_tab.bind(null, -1)
379
380 commands.tab_move_forward = helper_move_tab.bind(null, +1)
381
382 commands.tab_move_to_window = ({vim}) ->
383 {gBrowser} = vim.window
384 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
385
386 commands.tab_select_first = ({vim, count = 1}) ->
387 utils.nextTick(vim.window, ->
388 vim.window.gBrowser.selectTabAtIndex(count - 1)
389 )
390
391 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
392 firstNonPinned = vim.window.gBrowser._numPinnedTabs
393 utils.nextTick(vim.window, ->
394 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
395 )
396
397 commands.tab_select_last = ({vim, count = 1}) ->
398 utils.nextTick(vim.window, ->
399 vim.window.gBrowser.selectTabAtIndex(-count)
400 )
401
402 commands.tab_toggle_pinned = ({vim}) ->
403 currentTab = vim.window.gBrowser.selectedTab
404 if currentTab.pinned
405 vim.window.gBrowser.unpinTab(currentTab)
406 else
407 vim.window.gBrowser.pinTab(currentTab)
408
409 commands.tab_close = ({vim, count = 1}) ->
410 {gBrowser} = vim.window
411 return if gBrowser.selectedTab.pinned
412 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
413 utils.nextTick(vim.window, ->
414 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
415 gBrowser.removeTab(tab)
416 return
417 )
418
419 commands.tab_restore = ({vim, count = 1}) ->
420 utils.nextTick(vim.window, ->
421 for index in [0...count] by 1
422 restoredTab = vim.window.undoCloseTab()
423 if not restoredTab and index == 0
424 vim.notify(translate('notification.tab_restore.none'))
425 break
426 return
427 )
428
429 commands.tab_restore_list = ({vim}) ->
430 {window} = vim
431 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
432 window, 'menuitem'
433 )
434 if fragment.childElementCount == 0
435 vim.notify(translate('notification.tab_restore.none'))
436 else
437 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
438
439 commands.tab_close_to_end = ({vim}) ->
440 {gBrowser} = vim.window
441 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
442
443 commands.tab_close_other = ({vim}) ->
444 {gBrowser} = vim.window
445 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
446
447
448
449 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
450 {window} = vim
451 vim.markPageInteraction()
452 help.removeHelp(window)
453
454 markerContainer = new MarkerContainer({
455 window
456 hintChars: vim.options['hints.chars']
457 getComplementaryWrappers: (callback) ->
458 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
459 # `markerContainer.container` is `null`ed out when leaving Hints mode.
460 # If this callback is called after we’ve left Hints mode (and perhaps
461 # even entered it again), simply discard the result.
462 return unless markerContainer.container
463 if wrappers.length == 0
464 vim.notify(translate('notification.follow.none'))
465 callback({wrappers, viewport})
466 )
467 })
468 MarkerContainer.remove(window) # Better safe than sorry.
469 window.gBrowser.selectedBrowser.parentNode.appendChild(
470 markerContainer.container
471 )
472
473 chooseCallback = (marker, timesLeft, keyStr) ->
474 if callbackOverride
475 {type, href = null, elementIndex} = marker.wrapper
476 return callbackOverride({type, href, id: elementIndex, timesLeft})
477 else
478 return callback(marker, timesLeft, keyStr)
479
480 # Enter Hints mode immediately, with an empty set of markers. The user might
481 # press keys before any hints have been generated. Those keypresses should be
482 # handled in Hints mode, not Normal mode.
483 vim._enterMode('hints', {
484 markerContainer, count
485 callback: chooseCallback
486 matchText: vim.options['hints.match_text']
487 sleep: vim.options['hints.sleep']
488 })
489
490 injectHints = ({wrappers, viewport, pass}) ->
491 # See `getComplementaryWrappers` above.
492 return unless markerContainer.container
493
494 if wrappers.length == 0
495 if pass in ['single', 'second'] and markerContainer.markers.length == 0
496 vim.notify(translate('notification.follow.none'))
497 vim._enterMode('normal')
498 else
499 markerContainer.injectHints(wrappers, viewport, pass)
500
501 if pass == 'first'
502 vim._run(name, {pass: 'second'}, injectHints)
503
504 vim._run(name, {pass: 'auto'}, injectHints)
505
506 helper_follow_clickable = (options, args) ->
507 {vim} = args
508
509 callback = (marker, timesLeft, keyStr) ->
510 {inTab, inBackground} = options
511 {type, elementIndex} = marker.wrapper
512 isLast = (timesLeft == 1)
513 isLink = (type == 'link')
514 {window} = vim
515
516 switch
517 when keyStr.startsWith(vim.options['hints.toggle_in_tab'])
518 inTab = not inTab
519 when keyStr.startsWith(vim.options['hints.toggle_in_background'])
520 inTab = true
521 inBackground = not inBackground
522 else
523 unless isLast
524 inTab = true
525 inBackground = true
526
527 inTab = false unless isLink
528
529 if type == 'text' or (isLink and not (inTab and inBackground))
530 isLast = true
531
532 vim._focusMarkerElement(elementIndex)
533
534 if inTab
535 utils.nextTick(window, ->
536 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
537 # links using the mouse. Using that instead of simply
538 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
539 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
540 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
541 ContentClick.contentAreaClick({
542 href: marker.wrapper.href
543 shiftKey: not inBackground
544 ctrlKey: true
545 metaKey: true
546 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
547 triggeringPrincipal: window.document.nodePrincipal
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('main-window').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.esc = ({vim}) ->
1031 vim._run('esc')
1032 vim.hideNotification()
1033
1034 # Firefox does things differently when blurring the location bar, depending on
1035 # whether the autocomplete popup is open or not. To be consistent, always
1036 # close the autocomplete popup before blurring.
1037 vim.window.gURLBar.closePopup()
1038
1039 utils.blurActiveBrowserElement(vim)
1040 utils.getFindBar(vim.window.gBrowser).then((findBar) -> findBar.close())
1041
1042 # Better safe than sorry.
1043 MarkerContainer.remove(vim.window)
1044 vim._parent.resetCaretBrowsing()
1045
1046 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1047 help.removeHelp(vim.window)
1048
1049 vim._setFocusType('none') # Better safe than sorry.
1050
1051
1052
1053 module.exports = {
1054 commands
1055 findStorage
1056 }
Imprint / Impressum