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