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