]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Always treat the hint chars' case as-is
[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, uiEvent, args...) ->
156 [
157 method, type, directions, amounts
158 properties = null, adjustment = 0, name = 'scroll'
159 ] = args
160 options = {
161 method, type, directions, amounts, properties, adjustment
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 uiEvent 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, uiEvent, count = 1}) ->
197 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
198 helper_scroll(
199 vim, uiEvent, 'scrollBy', 'lines', ['left'], [amount * distance * count * 5]
200 )
201
202 helper_scrollByLinesY = (amount, {vim, uiEvent, count = 1}) ->
203 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
204 helper_scroll(
205 vim, uiEvent, 'scrollBy', 'lines', ['top'], [amount * distance * count * 20]
206 )
207
208 helper_scrollByPagesY = (amount, type, {vim, uiEvent, count = 1}) ->
209 adjustment = vim.options["scroll.#{type}_page_adjustment"]
210 helper_scroll(
211 vim, uiEvent, 'scrollBy', 'pages', ['top'], [amount * count],
212 ['clientHeight'], adjustment
213 )
214
215 helper_scrollToX = (amount, {vim, uiEvent}) ->
216 helper_mark_last_scroll_position(vim)
217 helper_scroll(
218 vim, uiEvent, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
219 )
220
221 helper_scrollToY = (amount, {vim, uiEvent}) ->
222 helper_mark_last_scroll_position(vim)
223 helper_scroll(
224 vim, uiEvent, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
225 )
226
227 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
228 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
229 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
230 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
231 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
232 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
233 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
234 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
235 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
236 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
237 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
238 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
239
240 helper_mark_last_scroll_position = (vim) ->
241 keyStr = vim.options['scroll.last_position_mark']
242 vim._run('mark_scroll_position', {keyStr, notify: false})
243
244 commands.mark_scroll_position = ({vim}) ->
245 vim._enterMode('marks', (keyStr) ->
246 vim._run('mark_scroll_position', {keyStr})
247 )
248 vim.notify(translate('notification.mark_scroll_position.enter'))
249
250 commands.scroll_to_mark = ({vim}) ->
251 vim._enterMode('marks', (keyStr) ->
252 unless keyStr == vim.options['scroll.last_position_mark']
253 helper_mark_last_scroll_position(vim)
254 helper_scroll(
255 vim, null, 'scrollTo', 'other', ['top', 'left'], keyStr,
256 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark'
257 )
258 vim.hideNotification()
259 )
260 vim.notify(translate('notification.scroll_to_mark.enter'))
261
262
263
264 commands.tab_new = ({vim}) ->
265 utils.nextTick(vim.window, ->
266 vim.window.BrowserOpenTab()
267 )
268
269 commands.tab_new_after_current = ({vim}) ->
270 {window} = vim
271 newTabPosition = window.gBrowser.selectedTab._tPos + 1
272 utils.nextTick(window, ->
273 utils.listenOnce(window, 'TabOpen', (event) ->
274 newTab = event.originalTarget
275 window.gBrowser.moveTabTo(newTab, newTabPosition)
276 )
277 window.BrowserOpenTab()
278 )
279
280 commands.tab_duplicate = ({vim}) ->
281 {gBrowser} = vim.window
282 utils.nextTick(vim.window, ->
283 gBrowser.duplicateTab(gBrowser.selectedTab)
284 )
285
286 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
287 tabs = gBrowser.visibleTabs
288 {selectedTab} = gBrowser
289
290 currentIndex = tabs.indexOf(selectedTab)
291 absoluteIndex = currentIndex + relativeIndex
292 numTabsTotal = tabs.length
293 numPinnedTabs = gBrowser._numPinnedTabs
294
295 [numTabs, min] = switch
296 when not pinnedSeparate
297 [numTabsTotal, 0]
298 when selectedTab.pinned
299 [numPinnedTabs, 0]
300 else
301 [numTabsTotal - numPinnedTabs, numPinnedTabs]
302
303 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
304 # current direction.
305 if (relativeIndex < 0 and currentIndex == min) or
306 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
307 if absoluteIndex < min
308 absoluteIndex += numTabs
309 else if absoluteIndex >= min + numTabs
310 absoluteIndex -= numTabs
311
312 absoluteIndex = Math.max(min, absoluteIndex)
313 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
314
315 return absoluteIndex
316
317 helper_switch_tab = (direction, {vim, count = 1}) ->
318 {gBrowser} = vim.window
319 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
320 utils.nextTick(vim.window, ->
321 gBrowser.selectTabAtIndex(index)
322 )
323
324 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
325
326 commands.tab_select_next = helper_switch_tab.bind(null, +1)
327
328 helper_is_visited = (tab) ->
329 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
330
331 commands.tab_select_most_recent = ({vim, count = 1}) ->
332 {gBrowser} = vim.window
333 tabsSorted =
334 Array.filter(
335 gBrowser.tabs,
336 (tab) -> not tab.closing and helper_is_visited(tab)
337 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
338 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
339 if tab
340 gBrowser.selectedTab = tab
341 else
342 vim.notify(translate('notification.tab_select_most_recent.none'))
343
344 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
345 {gBrowser} = vim.window
346 tabsSorted =
347 Array.filter(
348 gBrowser.tabs,
349 (tab) -> not tab.closing and not helper_is_visited(tab)
350 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
351 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
352 if tab
353 gBrowser.selectedTab = tab
354 else
355 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
356
357 helper_move_tab = (direction, {vim, count = 1}) ->
358 {gBrowser} = vim.window
359 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
360 utils.nextTick(vim.window, ->
361 gBrowser.moveTabTo(gBrowser.selectedTab, index)
362 )
363
364 commands.tab_move_backward = helper_move_tab.bind(null, -1)
365
366 commands.tab_move_forward = helper_move_tab.bind(null, +1)
367
368 commands.tab_move_to_window = ({vim}) ->
369 {gBrowser} = vim.window
370 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
371
372 commands.tab_select_first = ({vim, count = 1}) ->
373 utils.nextTick(vim.window, ->
374 vim.window.gBrowser.selectTabAtIndex(count - 1)
375 )
376
377 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
378 firstNonPinned = vim.window.gBrowser._numPinnedTabs
379 utils.nextTick(vim.window, ->
380 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
381 )
382
383 commands.tab_select_last = ({vim, count = 1}) ->
384 utils.nextTick(vim.window, ->
385 vim.window.gBrowser.selectTabAtIndex(-count)
386 )
387
388 commands.tab_toggle_pinned = ({vim}) ->
389 currentTab = vim.window.gBrowser.selectedTab
390 if currentTab.pinned
391 vim.window.gBrowser.unpinTab(currentTab)
392 else
393 vim.window.gBrowser.pinTab(currentTab)
394
395 commands.tab_close = ({vim, count = 1}) ->
396 {gBrowser} = vim.window
397 return if gBrowser.selectedTab.pinned
398 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
399 utils.nextTick(vim.window, ->
400 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
401 gBrowser.removeTab(tab)
402 return
403 )
404
405 commands.tab_restore = ({vim, count = 1}) ->
406 utils.nextTick(vim.window, ->
407 for index in [0...count] by 1
408 restoredTab = vim.window.undoCloseTab()
409 if not restoredTab and index == 0
410 vim.notify(translate('notification.tab_restore.none'))
411 break
412 return
413 )
414
415 commands.tab_restore_list = ({vim}) ->
416 {window} = vim
417 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
418 window, 'menuitem'
419 )
420 if fragment.childElementCount == 0
421 vim.notify(translate('notification.tab_restore.none'))
422 else
423 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
424
425 commands.tab_close_to_end = ({vim}) ->
426 {gBrowser} = vim.window
427 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
428
429 commands.tab_close_other = ({vim}) ->
430 {gBrowser} = vim.window
431 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
432
433
434
435 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
436 {window} = vim
437 vim.markPageInteraction()
438 help.removeHelp(window)
439
440 markerContainer = new MarkerContainer({
441 window
442 hintChars: vim.options['hints.chars']
443 getComplementaryWrappers: (callback) ->
444 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
445 # `markerContainer.container` is `null`ed out when leaving Hints mode.
446 # If this callback is called after we’ve left Hints mode (and perhaps
447 # even entered it again), simply discard the result.
448 return unless markerContainer.container
449 if wrappers.length == 0
450 vim.notify(translate('notification.follow.none'))
451 callback({wrappers, viewport})
452 )
453 })
454 MarkerContainer.remove(window) # Better safe than sorry.
455 window.gBrowser.selectedBrowser.parentNode.appendChild(
456 markerContainer.container
457 )
458
459 chooseCallback = (marker, timesLeft, keyStr) ->
460 if callbackOverride
461 {type, href = null, elementIndex} = marker.wrapper
462 return callbackOverride({type, href, id: elementIndex, timesLeft})
463 else
464 return callback(marker, timesLeft, keyStr)
465
466 # Enter Hints mode immediately, with an empty set of markers. The user might
467 # press keys before any hints have been generated. Those key presses should be
468 # handled in Hints mode, not Normal mode.
469 vim._enterMode('hints', {
470 markerContainer, count
471 callback: chooseCallback
472 matchText: vim.options['hints.match_text']
473 sleep: vim.options['hints.sleep']
474 })
475
476 injectHints = ({wrappers, viewport, pass}) ->
477 # See `getComplementaryWrappers` above.
478 return unless markerContainer.container
479
480 if wrappers.length == 0
481 if pass in ['single', 'second'] and markerContainer.markers.length == 0
482 vim.notify(translate('notification.follow.none'))
483 vim._enterMode('normal')
484 else
485 markerContainer.injectHints(wrappers, viewport, pass)
486
487 if pass == 'first'
488 vim._run(name, {pass: 'second'}, injectHints)
489
490 vim._run(name, {pass: 'auto'}, injectHints)
491
492 helper_follow_clickable = (options, args) ->
493 {vim} = args
494
495 callback = (marker, timesLeft, keyStr) ->
496 {inTab, inBackground} = options
497 {type, elementIndex} = marker.wrapper
498 isLast = (timesLeft == 1)
499 isLink = (type == 'link')
500 {window} = vim
501
502 switch
503 when keyStr.startsWith(vim.options['hints.toggle_in_tab'])
504 inTab = not inTab
505 when keyStr.startsWith(vim.options['hints.toggle_in_background'])
506 inTab = true
507 inBackground = not inBackground
508 else
509 unless isLast
510 inTab = true
511 inBackground = true
512
513 inTab = false unless isLink
514
515 if type == 'text' or (isLink and not (inTab and inBackground))
516 isLast = true
517
518 vim._focusMarkerElement(elementIndex)
519
520 if inTab
521 utils.nextTick(window, ->
522 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
523 # links using the mouse. Using that instead of simply
524 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
525 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
526 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
527 ContentClick.contentAreaClick({
528 href: marker.wrapper.href
529 shiftKey: not inBackground
530 ctrlKey: true
531 metaKey: true
532 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
533 }, vim.browser)
534 reset()
535 )
536 else
537 vim._run('click_marker_element', {
538 elementIndex, type
539 browserOffset: vim._getBrowserOffset()
540 preventTargetBlank: vim.options.prevent_target_blank
541 })
542
543 return not isLast
544
545 name = if options.inTab then 'follow_in_tab' else 'follow'
546 helper_follow({name, callback}, args)
547
548 commands.follow =
549 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
550
551 commands.follow_in_tab =
552 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
553
554 commands.follow_in_focused_tab =
555 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
556
557 helper_follow_in_window = (options, args) ->
558 {vim} = args
559
560 callback = (marker) ->
561 vim._focusMarkerElement(marker.wrapper.elementIndex)
562 {href} = marker.wrapper
563 vim.window.openLinkIn(href, 'window', options) if href
564 return false
565
566 helper_follow({name: 'follow_in_tab', callback}, args)
567
568 commands.follow_in_window =
569 helper_follow_in_window.bind(null, {})
570
571 commands.follow_in_private_window =
572 helper_follow_in_window.bind(null, {private: true})
573
574 commands.follow_multiple = (args) ->
575 args.count = Infinity
576 commands.follow(args)
577
578 commands.follow_copy = (args) ->
579 {vim} = args
580
581 callback = (marker) ->
582 property = switch marker.wrapper.type
583 when 'link'
584 'href'
585 when 'text'
586 'value'
587 when 'contenteditable', 'complementary'
588 '_selection'
589 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
590 return false
591
592 helper_follow({name: 'follow_copy', callback}, args)
593
594 commands.follow_focus = (args) ->
595 {vim} = args
596
597 callback = (marker) ->
598 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
599 return false
600
601 helper_follow({name: 'follow_focus', callback}, args)
602
603 commands.open_context_menu = (args) ->
604 {vim} = args
605
606 callback = (marker) ->
607 {type, elementIndex} = marker.wrapper
608 vim._run('click_marker_element', {
609 elementIndex, type
610 browserOffset: vim._getBrowserOffset()
611 })
612 return false
613
614 helper_follow({name: 'follow_context', callback}, args)
615
616 commands.click_browser_element = ({vim}) ->
617 {window} = vim
618 markerElements = []
619
620 getButtonMenu = (element) ->
621 if element.localName == 'dropmarker' and
622 element.parentNode?.localName == 'toolbarbutton'
623 return element.parentNode.querySelector('menupopup')
624 else
625 return null
626
627 filter = ({complementary}, element, getElementShape) ->
628 type = switch
629 when vim._state.scrollableElements.has(element)
630 'scrollable'
631 when getButtonMenu(element)
632 'dropmarker'
633 when utils.isFocusable(element) or
634 (element.onclick and element.localName != 'statuspanel')
635 'clickable'
636
637 if complementary
638 type = if type then null else 'complementary'
639
640 return unless type
641
642 # `getElementShape(element, -1)` is intentionally _not_ used in the
643 # `complementary` run, because it results in tons of useless hints for
644 # hidden context menus.
645 shape = getElementShape(element)
646 return unless shape.nonCoveredPoint
647
648 length = markerElements.push(element)
649 return {type, shape, elementIndex: length - 1}
650
651 callback = (marker) ->
652 element = markerElements[marker.wrapper.elementIndex]
653 switch marker.wrapper.type
654 when 'scrollable'
655 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
656 when 'dropmarker'
657 getButtonMenu(element).openPopup(
658 element.parentNode, # Anchor node.
659 'after_end', # Position.
660 0, 0, # Offset.
661 false, # Isn’t a context menu.
662 true, # Allow the 'position' attribute to override the above position.
663 )
664 when 'clickable', 'complementary'
665 # VimFx’s own button won’t trigger unless the click is simulated in the
666 # next tick. This might be true for other buttons as well.
667 utils.nextTick(window, ->
668 utils.focusElement(element)
669 browserOffset = {x: window.screenX, y: window.screenY}
670 switch
671 when element.localName == 'tab'
672 # Only 'mousedown' seems to be able to activate tabs.
673 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
674 when element.closest('tab')
675 # If `.click()` is used on a tab close button, its tab will be
676 # selected first, which might cause the selected tab to change.
677 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
678 else
679 # `.click()` seems to trigger more buttons (such as NoScript’s
680 # button and Firefox’s “hamburger” menu button) than simulating
681 # 'click-xul'.
682 element.click()
683 utils.openDropdown(element)
684 )
685 return false
686
687 wrappers = markableElements.find(
688 window, filter.bind(null, {complementary: false})
689 )
690
691 if wrappers.length > 0
692 viewport = viewportUtils.getWindowViewport(window)
693
694 markerContainer = new MarkerContainer({
695 window
696 hintChars: vim.options['hints.chars']
697 adjustZoom: false
698 getComplementaryWrappers: (callback) ->
699 newWrappers = markableElements.find(
700 window, filter.bind(null, {complementary: true})
701 )
702 callback({wrappers: newWrappers, viewport})
703 })
704 MarkerContainer.remove(window) # Better safe than sorry.
705 markerContainer.container.classList.add('ui')
706 window.document.getElementById('browser-panel').appendChild(
707 markerContainer.container
708 )
709
710 markerContainer.injectHints(wrappers, viewport, 'single')
711 vim._enterMode('hints', {markerContainer, callback, matchText: false})
712
713 else
714 vim.notify(translate('notification.follow.none'))
715
716 helper_follow_pattern = (type, {vim}) ->
717 options = {
718 pattern_selector: vim.options.pattern_selector
719 pattern_attrs: vim.options.pattern_attrs
720 patterns: vim.options["#{type}_patterns"]
721 }
722 browserOffset = vim._getBrowserOffset()
723 vim._run('follow_pattern', {type, browserOffset, options})
724
725 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
726
727 commands.follow_next = helper_follow_pattern.bind(null, 'next')
728
729 commands.focus_text_input = ({vim, count}) ->
730 vim.markPageInteraction()
731 vim._run('focus_text_input', {count})
732
733 helper_follow_selectable = ({select}, args) ->
734 {vim} = args
735
736 callback = (marker) ->
737 vim._run('element_text_select', {
738 elementIndex: marker.wrapper.elementIndex
739 full: select
740 scroll: select
741 })
742 vim._enterMode('caret', {select})
743 return false
744
745 helper_follow({name: 'follow_selectable', callback}, args)
746
747 commands.element_text_caret =
748 helper_follow_selectable.bind(null, {select: false})
749
750 commands.element_text_select =
751 helper_follow_selectable.bind(null, {select: true})
752
753 commands.element_text_copy = (args) ->
754 {vim} = args
755
756 callback = (marker) ->
757 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
758 return false
759
760 helper_follow({name: 'follow_selectable', callback}, args)
761
762 helper_copy_marker_element = (vim, elementIndex, property) ->
763 if property == '_selection'
764 # Selecting the text and then copying that selection is better than copying
765 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
766 # and then includes those backticks in the compiled output (!), in hidden
767 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
768 # elements, text selection gives better whitespace than `.textContent`.
769 vim._run('element_text_select', {elementIndex, full: true}, ->
770 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
771 vim._run('clear_selection')
772 )
773 else
774 vim._run('copy_marker_element', {elementIndex, property})
775
776
777
778 findStorage = {
779 lastSearchString: ''
780 busy: false
781 }
782
783 helper_find_from_top_of_viewport = (vim, direction, callback) ->
784 if vim.options.find_from_top_of_viewport
785 vim._run('find_from_top_of_viewport', {direction}, ->
786 callback()
787 )
788 else
789 callback()
790
791 helper_find = ({highlight, linksOnly = false}, {vim}) ->
792 if findStorage.busy
793 # Make sure to enter find mode here, since that’s where `findStorage.busy`
794 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
795 vim._enterMode('find')
796 return
797
798 helpSearchInput = help.getSearchInput(vim.window)
799 if helpSearchInput
800 helpSearchInput.select()
801 return
802
803 # Important: Enter Find mode immediately. See `onInput` for Find mode.
804 findStorage.busy = true
805 vim._enterMode('find')
806
807 helper_mark_last_scroll_position(vim)
808 helper_find_from_top_of_viewport(vim, FORWARD, ->
809 return unless vim.mode == 'find'
810 findBar = vim.window.gBrowser.getFindBar()
811
812 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
813 findBar.startFind(mode)
814 utils.focusElement(findBar._findField, {select: true})
815
816 return if linksOnly
817 return unless highlightButton = findBar.getElement('highlight')
818 if highlightButton.checked != highlight
819 highlightButton.click()
820 )
821
822 commands.find = helper_find.bind(null, {highlight: false})
823
824 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
825
826 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
827
828 helper_find_again = (direction, {vim}) ->
829 return if findStorage.busy
830
831 findBar = vim.window.gBrowser.getFindBar()
832 if findStorage.lastSearchString.length == 0
833 vim.notify(translate('notification.find_again.none'))
834 return
835
836 findStorage.busy = true
837
838 helper_mark_last_scroll_position(vim)
839 helper_find_from_top_of_viewport(vim, direction, ->
840 findBar._findField.value = findStorage.lastSearchString
841
842 # Temporarily hack `.onFindResult` to be able to know when the asynchronous
843 # `.onFindAgainCommand` is done.
844 originalOnFindResult = findBar.onFindResult
845 findBar.onFindResult = (data) ->
846 # Prevent the find bar from re-opening if there are no matches.
847 data.storeResult = false
848 findBar.onFindResult = originalOnFindResult
849 findBar.onFindResult(data)
850 message = findBar._findStatusDesc.textContent
851 vim.notify(message) if message
852 findStorage.busy = false
853
854 findBar.onFindAgainCommand(not direction)
855 )
856
857 commands.find_next = helper_find_again.bind(null, FORWARD)
858
859 commands.find_previous = helper_find_again.bind(null, BACKWARD)
860
861
862
863 commands.window_new = ({vim}) ->
864 vim.window.OpenBrowserWindow()
865
866 commands.window_new_private = ({vim}) ->
867 vim.window.OpenBrowserWindow({private: true})
868
869 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
870 type = if blacklist then 'blacklist' else 'explicit'
871 vim._enterMode('ignore', {type})
872
873 # Quote next keypress (pass it through to the page).
874 commands.quote = ({vim, count = 1}) ->
875 vim._enterMode('ignore', {type: 'explicit', count})
876
877 commands.enter_reader_view = ({vim}) ->
878 button = vim.window.document.getElementById('reader-mode-button')
879 if not button?.hidden
880 button.click()
881 else
882 vim.notify(translate('notification.enter_reader_view.none'))
883
884 commands.reload_config_file = ({vim}) ->
885 vim._parent.emit('shutdown')
886 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
887 when null
888 vim.notify(translate('notification.reload_config_file.none'))
889 when true
890 vim.notify(translate('notification.reload_config_file.success'))
891 else
892 vim.notify(translate('notification.reload_config_file.failure'))
893 )
894
895 commands.edit_blacklist = ({vim}) ->
896 url = vim.browser.currentURI.spec
897 location = new vim.window.URL(url)
898 domain = location.host or location.href
899 newPattern = "*#{domain}*"
900 delimiter = ' '
901 blacklistString = prefs.get('blacklist')
902
903 if vim._isBlacklisted(url)
904 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
905 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
906 return vim.options.blacklist[index].test(url)
907 )
908 newBlacklistString = "
909 #{matching.join(delimiter)}\
910 #{delimiter.repeat(7)}\
911 #{nonMatching.join(delimiter)}
912 "
913 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
914 else
915 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
916 extraMessage = translate('pref.blacklist.extra.added', newPattern)
917
918 message = """
919 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
920
921 #{extraMessage}
922 """
923
924 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
925 return if input == null
926 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
927 # and let the regular pref parsing take care of it.
928 prefs.set('blacklist', input)
929 vim._onLocationChange(url)
930 )
931
932 commands.help = ({vim}) ->
933 help.toggleHelp(vim.window, vim._parent)
934
935 commands.dev = ({vim}) ->
936 vim.window.DeveloperToolbar.show(true) # `true` to focus.
937
938 commands.esc = ({vim}) ->
939 vim._run('esc')
940 vim.hideNotification()
941 utils.blurActiveBrowserElement(vim)
942 vim.window.gBrowser.getFindBar().close()
943 MarkerContainer.remove(vim.window) # Better safe than sorry.
944
945 # Calling `.hide()` when the toolbar is not open can destroy it for the rest
946 # of the Firefox session. The code here is taken from the `.toggle()` method.
947 {DeveloperToolbar} = vim.window
948 if DeveloperToolbar.visible
949 DeveloperToolbar.hide().catch(console.error)
950
951 unless help.getSearchInput(vim.window)?.getAttribute('focused')
952 help.removeHelp(vim.window)
953
954 vim._setFocusType('none') # Better safe than sorry.
955
956
957
958 module.exports = {
959 commands
960 findStorage
961 }
Imprint / Impressum