]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
update support for user contexts (containers)
[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 {PlacesUIUtils} = Cu.import('resource:///modules/PlacesUIUtils.jsm', {})
20 {PrivateBrowsingUtils} =
21 Cu.import('resource://gre/modules/PrivateBrowsingUtils.jsm', {})
22 {E10SUtils} = Cu.import('resource://gre/modules/E10SUtils.jsm', {})
23 {FORWARD, BACKWARD} = SelectionManager
24
25 READER_VIEW_PREFIX = 'about:reader?url='
26 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
27 USER_CONTEXT_ID_ATTRIBUTE_NAME = 'usercontextid'
28
29 commands = {}
30
31
32
33 commands.focus_location_bar = ({vim}) ->
34 try
35 vim.window.gURLBar.select() # fx76+
36 catch
37 vim.window.focusAndSelectUrlBar()
38
39 commands.focus_search_bar = ({vim, count}) ->
40 # The `.webSearch()` method opens a search engine in a tab if the search bar
41 # has been removed. Therefore we first check if it exists.
42 if vim.window.BrowserSearch.searchBar
43 vim.window.BrowserSearch.webSearch()
44 else
45 vim.notify(translate('notification.focus_search_bar.none'))
46
47 helper_paste_and_go = (props, {vim}) ->
48 {gURLBar} = vim.window
49 gURLBar.value = vim.window.readFromClipboard()
50 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
51
52 commands.paste_and_go = helper_paste_and_go.bind(null, null)
53
54 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
55
56 commands.copy_current_url = ({vim}) ->
57 url = vim.window.gBrowser.currentURI.spec
58 adjustedUrl =
59 if url.startsWith(READER_VIEW_PREFIX)
60 decodeURIComponent(url[READER_VIEW_PREFIX.length..])
61 else
62 url
63 utils.writeToClipboard(adjustedUrl)
64 vim.notify(translate('notification.copy_current_url.success'))
65
66 commands.go_up_path = ({vim, count}) ->
67 vim._run('go_up_path', {count})
68
69 commands.go_to_root = ({vim}) ->
70 vim._run('go_to_root')
71
72 commands.go_home = ({vim}) ->
73 vim.window.BrowserHome()
74
75 helper_go_history = (direction, {vim, count = 1}) ->
76 {window} = vim
77 {SessionStore, gBrowser} = window
78
79 if (direction == 'back' and not gBrowser.canGoBack) or
80 (direction == 'forward' and not gBrowser.canGoForward)
81 vim.notify(translate("notification.history_#{direction}.limit"))
82 return
83
84 # `SessionStore.getSessionHistory()` (used below to support counts) starts
85 # lots of asynchronous tasks internally, which is a bit unreliable, it has
86 # turned out. The primary use of the `history_back` and `history_forward`
87 # commands is to go _one_ step back or forward, though, so those cases are
88 # optimized to use more reliable ways of going back and forward. Also, some
89 # extensions override the following functions, so calling them also gives
90 # better interoperability.
91 if count == 1
92 if direction == 'back'
93 window.BrowserBack()
94 else
95 window.BrowserForward()
96 return
97
98 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
99 {index} = sessionHistory
100 newIndex = index + count * (if direction == 'back' then -1 else 1)
101 newIndex = Math.max(newIndex, 0)
102 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
103 gBrowser.gotoIndex(newIndex)
104 )
105
106 commands.history_back = helper_go_history.bind(null, 'back')
107
108 commands.history_forward = helper_go_history.bind(null, 'forward')
109
110 commands.history_list = ({vim}) ->
111 menu = vim.window.document.getElementById('backForwardMenu')
112 utils.openPopup(menu)
113 if menu.childElementCount == 0
114 vim.notify(translate('notification.history_list.none'))
115
116 commands.reload = ({vim}) ->
117 vim.window.BrowserReload()
118
119 commands.reload_force = ({vim}) ->
120 vim.window.BrowserReloadSkipCache()
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.BrowserStop()
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.BrowserOpenTab()
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.BrowserOpenTab()
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 contentAreaClick = (json, browser) ->
555 # Note this function is shortened from the same-named one currently in
556 # mozilla-central/browser/actors/ClickHandlerParent.jsm. Keep in sync!
557 window = browser.ownerGlobal
558 params = {
559 charset: browser.characterSet,
560 referrerInfo: E10SUtils.deserializeReferrerInfo(json.referrerInfo),
561 allowMixedContent: json.allowMixedContent, # <=fx88
562 isContentWindowPrivate: json.isContentWindowPrivate,
563 originPrincipal: json.originPrincipal,
564 originStoragePrincipal: json.originStoragePrincipal,
565 triggeringPrincipal: json.triggeringPrincipal,
566 csp: if json.csp then E10SUtils.deserializeCSP(json.csp) else null,
567 frameOuterWindowID: json.frameOuterWindowID, # <=fx79
568 frameID: json.frameID, # >=fx80
569 allowInheritPrincipal: true,
570 }
571 if json.originAttributes.userContextId
572 params.userContextId = json.originAttributes.userContextId
573 try if not PrivateBrowsingUtils.isWindowPrivate(window)
574 PlacesUIUtils.markPageAsFollowedLink(json.href)
575 window.openLinkIn(json.href, window.whereToOpenLink(json), params)
576
577 utils.nextTick(window, ->
578 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
579 # links using the mouse. Using that instead of simply
580 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
581 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
582 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
583 contentAreaClick({
584 href: marker.wrapper.href
585 shiftKey: not inBackground
586 ctrlKey: true
587 metaKey: true
588 originAttributes: helper_add_user_context_id(
589 vim.browser.ownerGlobal.gBrowser,
590 window.document.nodePrincipal?.originAttributes ? {}
591 )
592 triggeringPrincipal: window.document.nodePrincipal
593 }, vim.browser)
594 reset()
595 )
596
597 # The point of “clicking” scrollable elements is focusing them (which is
598 # done above) so that scrolling commands may scroll them. Simulating a click
599 # here usually _unfocuses_ the element.
600 else if type != 'scrollable'
601 vim._run('click_marker_element', {
602 elementIndex, type
603 browserOffset: vim._getBrowserOffset()
604 preventTargetBlank: vim.options.prevent_target_blank
605 })
606
607 return not isLast
608
609 name = if options.inTab then 'follow_in_tab' else 'follow'
610 helper_follow({name, callback}, args)
611
612 commands.follow =
613 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
614
615 commands.follow_in_tab =
616 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
617
618 commands.follow_in_focused_tab =
619 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
620
621 helper_follow_in_window = (options, args) ->
622 {vim} = args
623
624 callback = (marker) ->
625 vim._focusMarkerElement(marker.wrapper.elementIndex)
626 {href} = marker.wrapper
627 options.triggeringPrincipal = vim.window.document.nodePrincipal
628 options = helper_add_user_context_id(vim.window.gBrowser, options)
629
630 vim.window.openLinkIn(href, 'window', options) if href
631 return false
632
633 helper_follow({name: 'follow_in_tab', callback}, args)
634
635 commands.follow_in_window =
636 helper_follow_in_window.bind(null, {})
637
638 commands.follow_in_private_window =
639 helper_follow_in_window.bind(null, {private: true})
640
641 commands.follow_multiple = (args) ->
642 args.count = Infinity
643 commands.follow(args)
644
645 commands.follow_copy = (args) ->
646 {vim} = args
647
648 callback = (marker) ->
649 property = switch marker.wrapper.type
650 when 'link'
651 'href'
652 when 'text'
653 'value'
654 when 'contenteditable', 'complementary'
655 '_selection'
656 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
657 return false
658
659 helper_follow({name: 'follow_copy', callback}, args)
660
661 commands.follow_focus = (args) ->
662 {vim} = args
663
664 callback = (marker) ->
665 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
666 return false
667
668 helper_follow({name: 'follow_focus', callback}, args)
669
670 commands.open_context_menu = (args) ->
671 {vim} = args
672
673 callback = (marker) ->
674 {type, elementIndex} = marker.wrapper
675 vim._run('click_marker_element', {
676 elementIndex, type
677 browserOffset: vim._getBrowserOffset()
678 })
679 return false
680
681 helper_follow({name: 'follow_context', callback}, args)
682
683 commands.click_browser_element = ({vim}) ->
684 {window} = vim
685 markerElements = []
686
687 getButtonMenu = (element) ->
688 if element.localName == 'dropmarker' and
689 element.parentNode?.localName == 'toolbarbutton'
690 return element.parentNode.querySelector('menupopup')
691 else
692 return null
693
694 filter = ({complementary}, element, getElementShape) ->
695 type = switch
696 when vim._state.scrollableElements.has(element)
697 'scrollable'
698 when getButtonMenu(element)
699 'dropmarker'
700 when utils.isFocusable(element) or element.onclick
701 'clickable'
702
703 if complementary
704 type = if type then null else 'complementary'
705
706 return unless type
707
708 # `getElementShape(element, -1)` is intentionally _not_ used in the
709 # `complementary` run, because it results in tons of useless hints for
710 # hidden context menus.
711 shape = getElementShape(element)
712 return unless shape.nonCoveredPoint
713
714 # The tabs and their close buttons as well as the tab bar scroll arrows get
715 # better hints, since switching or closing tabs is the most common use case
716 # for the `eb` command.
717 isTab = element.classList?.contains('tabbrowser-tab')
718 isPrioritized =
719 isTab or
720 element.classList?.contains('tab-close-button') or
721 element.classList?.contains('scrollbutton-up') or
722 element.classList?.contains('scrollbutton-down')
723
724 length = markerElements.push(element)
725 return {
726 type, shape, isTab, isPrioritized,
727 combinedArea: shape.area,
728 elementIndex: length - 1,
729 }
730
731 callback = (marker) ->
732 element = markerElements[marker.wrapper.elementIndex]
733 switch marker.wrapper.type
734 when 'scrollable'
735 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
736 when 'dropmarker'
737 getButtonMenu(element).openPopup(
738 element.parentNode, # Anchor node.
739 'after_end', # Position.
740 0, 0, # Offset.
741 false, # Isn’t a context menu.
742 true, # Allow the 'position' attribute to override the above position.
743 )
744 when 'clickable', 'complementary'
745 # VimFx’s own button won’t trigger unless the click is simulated in the
746 # next tick. This might be true for other buttons as well.
747 utils.nextTick(window, ->
748 utils.focusElement(element)
749 browserOffset = {x: window.screenX, y: window.screenY}
750 switch
751 when element.localName == 'tab'
752 # Only 'mousedown' seems to be able to activate tabs.
753 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
754 when element.closest('tab')
755 # If `.click()` is used on a tab close button, its tab will be
756 # selected first, which might cause the selected tab to change.
757 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
758 else
759 # `.click()` seems to trigger more buttons (such as NoScript’s
760 # button and Firefox’s “hamburger” menu button) than simulating
761 # 'click-xul'.
762 element.click()
763 utils.openDropdown(element)
764 )
765 return false
766
767 wrappers = markableElements.find(
768 window, filter.bind(null, {complementary: false})
769 )
770
771 if wrappers.length > 0
772 viewport = viewportUtils.getWindowViewport(window)
773
774 markerContainer = new MarkerContainer({
775 window
776 hintChars: vim.options['hints.chars']
777 adjustZoom: false
778 minWeightDiff: 0
779 getComplementaryWrappers: (callback) ->
780 newWrappers = markableElements.find(
781 window, filter.bind(null, {complementary: true})
782 )
783 callback({wrappers: newWrappers, viewport})
784 })
785 MarkerContainer.remove(window) # Better safe than sorry.
786 markerContainer.container.classList.add('ui')
787 mainWindow = window.document.body or
788 window.document.getElementById('main-window') # fallback <fx72
789 mainWindow.insertBefore(
790 markerContainer.container,
791 mainWindow.firstChild
792 )
793
794 [firstWrappers, secondWrappers] =
795 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
796
797 numChars = markerContainer.alphabet.length
798 numPrimary = markerContainer.primaryHintChars.length
799 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
800 index = 0
801
802 for wrapper in firstWrappers
803 if wrapper.isTab
804 # Given the hint chars `abc de`, give the tabs weights so that the hints
805 # consistently become `a b ca cb cc cd cea ceb cec ced ceea ceeb` and so
806 # on. The rule is that the weight of a tab must be larger than the sum
807 # of all tabs with a longer hint. We start out at `1` and then use
808 # smaller and smaller fractions. This is to make sure that the tabs get
809 # consistent hints as the number of tabs or the size of the window
810 # changes.
811 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
812 wrapper.combinedArea = 1 / numChars ** exponent
813 index += 1
814 else
815 # Make sure that the tab close buttons and the tab bar scroll buttons
816 # come after all the tabs. Treating them all as the same size is fine.
817 # Their sum must be small enough in order not to affect the tab hints.
818 # It might look like using `0` is a good idea, but that results in
819 # increasingly worse hints the more tab close buttons there are.
820 wrapper.combinedArea = 1 / numChars ** numTabs
821
822 # Since most of the best hint characters might be used for the tabs, make
823 # sure that all other elements don’t get really bad hints. First, favor
824 # larger elements by sorting them. Then, give them all the same weight so
825 # that larger elements (such as the location bar, search bar, the web
826 # console input and other large areas in the devtools) don’t overpower the
827 # smaller ones. The usual “the larger the element, the better the hint” rule
828 # doesn’t really apply the same way for browser UI elements as in web pages.
829 secondWrappers.sort((a, b) -> b.combinedArea - a.combinedArea)
830 for wrapper in secondWrappers
831 wrapper.combinedArea = 1
832
833 markerContainer.injectHints(firstWrappers, viewport, 'first')
834 markerContainer.injectHints(secondWrappers, viewport, 'second')
835 vim._enterMode('hints', {markerContainer, callback, matchText: false})
836
837 else
838 vim.notify(translate('notification.follow.none'))
839
840 helper_follow_pattern = (type, {vim}) ->
841 options = {
842 pattern_selector: vim.options.pattern_selector
843 pattern_attrs: vim.options.pattern_attrs
844 patterns: vim.options["#{type}_patterns"]
845 }
846 browserOffset = vim._getBrowserOffset()
847 vim._run('follow_pattern', {type, browserOffset, options})
848
849 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
850
851 commands.follow_next = helper_follow_pattern.bind(null, 'next')
852
853 commands.focus_text_input = ({vim, count}) ->
854 vim.markPageInteraction()
855 vim._run('focus_text_input', {count})
856
857 helper_follow_selectable = ({select}, args) ->
858 {vim} = args
859
860 callback = (marker) ->
861 vim._run('element_text_select', {
862 elementIndex: marker.wrapper.elementIndex
863 full: select
864 scroll: select
865 })
866 vim._enterMode('caret', {select})
867 return false
868
869 helper_follow({name: 'follow_selectable', callback}, args)
870
871 commands.element_text_caret =
872 helper_follow_selectable.bind(null, {select: false})
873
874 commands.element_text_select =
875 helper_follow_selectable.bind(null, {select: true})
876
877 commands.element_text_copy = (args) ->
878 {vim} = args
879
880 callback = (marker) ->
881 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
882 return false
883
884 helper_follow({name: 'follow_selectable', callback}, args)
885
886 helper_copy_marker_element = (vim, elementIndex, property) ->
887 if property == '_selection'
888 # Selecting the text and then copying that selection is better than copying
889 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
890 # and then includes those backticks in the compiled output (!), in hidden
891 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
892 # elements, text selection gives better whitespace than `.textContent`.
893 vim._run('element_text_select', {elementIndex, full: true}, ->
894 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
895 vim._run('clear_selection')
896 )
897 else
898 vim._run('copy_marker_element', {elementIndex, property})
899
900
901
902 findStorage = {
903 lastSearchString: ''
904 busy: false
905 }
906
907 helper_find_from_top_of_viewport = (vim, direction, callback) ->
908 if vim.options.find_from_top_of_viewport
909 vim._run('find_from_top_of_viewport', {direction}, ->
910 callback()
911 )
912 else
913 callback()
914
915 helper_find = ({highlight, linksOnly = false}, {vim}) ->
916 if findStorage.busy
917 # Make sure to enter find mode here, since that’s where `findStorage.busy`
918 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
919 vim._enterMode('find')
920 return
921
922 helpSearchInput = help.getSearchInput(vim.window)
923 if helpSearchInput
924 helpSearchInput.select()
925 return
926
927 # Important: Enter Find mode immediately. See `onInput` for Find mode.
928 findStorage.busy = true
929 vim._enterMode('find')
930
931 helper_mark_last_scroll_position(vim)
932 vim._run('mark_scroll_position', {
933 keyStr: vim.options['scroll.last_find_mark']
934 notify: false
935 })
936
937 helper_find_from_top_of_viewport(vim, FORWARD, ->
938 return unless vim.mode == 'find'
939 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
940 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
941 findBar.startFind(mode)
942 utils.focusElement(findBar._findField, {select: true})
943
944 return if linksOnly
945 return unless highlightButton = findBar.getElement('highlight')
946 if highlightButton.checked != highlight
947 highlightButton.click()
948 )
949 )
950
951 commands.find = helper_find.bind(null, {highlight: false})
952
953 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
954
955 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
956
957 helper_find_again = (direction, {vim}) ->
958 return if findStorage.busy
959
960 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
961 if findStorage.lastSearchString.length == 0
962 vim.notify(translate('notification.find_again.none'))
963 return
964
965 findStorage.busy = true
966
967 helper_mark_last_scroll_position(vim)
968 helper_find_from_top_of_viewport(vim, direction, ->
969 findBar._findField.value = findStorage.lastSearchString
970
971 # `.onFindResult` is temporarily hacked to be able to know when the
972 # asynchronous `.onFindAgainCommand` is done. When PDFs are shown using
973 # PDF.js, `.updateControlState` is called instead of `.onFindResult`, so
974 # hack that one too.
975 originalOnFindResult = findBar.onFindResult
976 originalUpdateControlState = findBar.updateControlState
977
978 findBar.onFindResult = (data) ->
979 # Prevent the find bar from re-opening if there are no matches.
980 data.storeResult = false
981 findBar.onFindResult = originalOnFindResult
982 findBar.updateControlState = originalUpdateControlState
983 findBar.onFindResult(data)
984 callback()
985
986 findBar.updateControlState = (args...) ->
987 # Firefox inconsistently _doesn’t_ re-open the find bar if there are no
988 # matches here, so no need to take care of that in this case.
989 findBar.onFindResult = originalOnFindResult
990 findBar.updateControlState = originalUpdateControlState
991 findBar.updateControlState(args...)
992 callback()
993
994 callback = ->
995 message = findBar._findStatusDesc.textContent
996 vim.notify(message) if message
997 findStorage.busy = false
998
999 findBar.onFindAgainCommand(not direction)
1000 )
1001 )
1002
1003 commands.find_next = helper_find_again.bind(null, FORWARD)
1004
1005 commands.find_previous = helper_find_again.bind(null, BACKWARD)
1006
1007
1008
1009 commands.window_new = ({vim}) ->
1010 vim.window.OpenBrowserWindow()
1011
1012 commands.window_new_private = ({vim}) ->
1013 vim.window.OpenBrowserWindow({private: true})
1014
1015 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
1016 type = if blacklist then 'blacklist' else 'explicit'
1017 vim._enterMode('ignore', {type})
1018
1019 # Quote next keypress (pass it through to the page).
1020 commands.quote = ({vim, count = 1}) ->
1021 vim._enterMode('ignore', {type: 'explicit', count})
1022
1023 commands.enter_reader_view = ({vim}) ->
1024 button = vim.window.document.getElementById('reader-mode-button')
1025 if not button?.hidden
1026 button.click()
1027 else
1028 vim.notify(translate('notification.enter_reader_view.none'))
1029
1030 commands.reload_config_file = ({vim}) ->
1031 vim._parent.emit('shutdown')
1032 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
1033 when null
1034 vim.notify(translate('notification.reload_config_file.none'))
1035 when true
1036 vim.notify(translate('notification.reload_config_file.success'))
1037 else
1038 vim.notify(translate('notification.reload_config_file.failure'))
1039 )
1040
1041 commands.edit_blacklist = ({vim}) ->
1042 url = vim.browser.currentURI.spec
1043 location = new vim.window.URL(url)
1044 newPattern = if location.host then "*#{location.host}*" else location.href
1045 delimiter = ' '
1046 blacklistString = prefs.get('blacklist')
1047
1048 if vim._isBlacklisted(url)
1049 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
1050 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
1051 return vim.options.blacklist[index].test(url)
1052 )
1053 newBlacklistString = "
1054 #{matching.join(delimiter)}\
1055 #{delimiter.repeat(7)}\
1056 #{nonMatching.join(delimiter)}
1057 "
1058 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1059 else
1060 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1061 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1062
1063 message = """
1064 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1065
1066 #{extraMessage}
1067 """
1068
1069 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
1070 return if input == null
1071 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
1072 # and let the regular pref parsing take care of it.
1073 prefs.set('blacklist', input)
1074 vim._onLocationChange(url)
1075 )
1076
1077 commands.help = ({vim}) ->
1078 help.toggleHelp(vim.window, vim._parent)
1079
1080 commands.esc = ({vim}) ->
1081 vim._run('esc')
1082 vim.hideNotification()
1083
1084 # Firefox does things differently when blurring the location bar, depending on
1085 # whether the autocomplete popup is open or not. To be consistent, always
1086 # close the autocomplete popup before blurring.
1087 vim.window.gURLBar.view.close()
1088
1089 utils.blurActiveBrowserElement(vim)
1090 utils.getFindBar(vim.window.gBrowser).then((findBar) -> findBar.close())
1091
1092 # Better safe than sorry.
1093 MarkerContainer.remove(vim.window)
1094 vim._parent.resetCaretBrowsing()
1095
1096 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1097 help.removeHelp(vim.window)
1098
1099 vim._setFocusType('none') # Better safe than sorry.
1100
1101
1102
1103 module.exports = {
1104 commands
1105 findStorage
1106 }
Imprint / Impressum