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