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