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