]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Improve CPU usage in Hints mode
[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 help = require('./help')
30 hints = require('./hints')
31 prefs = require('./prefs')
32 translate = require('./l10n')
33 utils = require('./utils')
34
35 commands = {}
36
37
38
39 commands.focus_location_bar = ({vim}) ->
40 vim.window.focusAndSelectUrlBar()
41
42 commands.focus_search_bar = ({vim, count}) ->
43 # The `.webSearch()` method opens a search engine in a tab if the search bar
44 # has been removed. Therefore we first check if it exists.
45 if vim.window.BrowserSearch.searchBar
46 vim.window.BrowserSearch.webSearch()
47
48 helper_paste_and_go = (props, {vim}) ->
49 {gURLBar} = vim.window
50 gURLBar.value = vim.window.readFromClipboard()
51 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
52
53 commands.paste_and_go = helper_paste_and_go.bind(null, null)
54
55 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
56
57 commands.copy_current_url = ({vim}) ->
58 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
59 vim.notify(translate('notification.copy_current_url'))
60
61 commands.go_up_path = ({vim, count}) ->
62 vim._run('go_up_path', {count})
63
64 commands.go_to_root = ({vim}) ->
65 vim._run('go_to_root')
66
67 commands.go_home = ({vim}) ->
68 vim.window.BrowserHome()
69
70 helper_go_history = (direction, {vim, count = 1}) ->
71 {SessionStore, gBrowser} = vim.window
72
73 # TODO: When Firefox 43 is released, only use the `.getSessionHistory`
74 # version and bump the minimum Firefox version.
75 if SessionStore.getSessionHistory
76 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
77 {index} = sessionHistory
78 newIndex = index + count * (if direction == 'back' then -1 else 1)
79 newIndex = Math.max(newIndex, 0)
80 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
81 if newIndex == index
82 vim.notify(translate("notification.history_#{direction}.limit"))
83 else
84 gBrowser.gotoIndex(newIndex)
85 )
86 else
87 # Until then, fall back to a no-count version.
88 if direction == 'back' then gBrowser.goBack() else gBrowser.goForward()
89
90 commands.history_back = helper_go_history.bind(null, 'back')
91
92 commands.history_forward = helper_go_history.bind(null, 'forward')
93
94 commands.history_list = ({vim}) ->
95 menu = vim.window.document.getElementById('backForwardMenu')
96 utils.openPopup(menu)
97 if menu.childElementCount == 0
98 vim.notify(translate('notification.history_list.none'))
99
100 commands.reload = ({vim}) ->
101 vim.window.BrowserReload()
102
103 commands.reload_force = ({vim}) ->
104 vim.window.BrowserReloadSkipCache()
105
106 commands.reload_all = ({vim}) ->
107 vim.window.gBrowser.reloadAllTabs()
108
109 commands.reload_all_force = ({vim}) ->
110 for tab in vim.window.gBrowser.visibleTabs
111 gBrowser = tab.linkedBrowser
112 consts = gBrowser.webNavigation
113 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
114 gBrowser.reload(flags)
115 return
116
117 commands.stop = ({vim}) ->
118 vim.window.BrowserStop()
119
120 commands.stop_all = ({vim}) ->
121 for tab in vim.window.gBrowser.visibleTabs
122 tab.linkedBrowser.stop()
123 return
124
125
126
127 helper_scroll = (vim, uiEvent, args...) ->
128 [
129 method, type, directions, amounts
130 properties = null, adjustment = 0, name = 'scroll'
131 ] = args
132 options = {
133 method, type, directions, amounts, properties, adjustment
134 smooth: (prefs.root.get('general.smoothScroll') and
135 prefs.root.get("general.smoothScroll.#{type}"))
136 }
137 reset = prefs.root.tmp(
138 'layout.css.scroll-behavior.spring-constant',
139 vim.options["smoothScroll.#{type}.spring-constant"]
140 )
141
142 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
143 if uiEvent or helpScroll
144 activeElement = helpScroll or utils.getActiveElement(vim.window)
145 if vim._state.scrollableElements.has(activeElement) or helpScroll
146 utils.scroll(activeElement, options)
147 reset()
148 return
149
150 vim._run(name, options, reset)
151
152
153 helper_scrollByLinesX = (amount, {vim, uiEvent, count = 1}) ->
154 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
155 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['left'],
156 [amount * distance * count * 5])
157
158 helper_scrollByLinesY = (amount, {vim, uiEvent, count = 1}) ->
159 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
160 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['top'],
161 [amount * distance * count * 20])
162
163 helper_scrollByPagesY = (amount, type, {vim, uiEvent, count = 1}) ->
164 adjustment = prefs.get("scroll.#{type}_page_adjustment")
165 helper_scroll(vim, uiEvent, 'scrollBy', 'pages', ['top'],
166 [amount * count], ['clientHeight'], adjustment)
167
168 helper_scrollToX = (amount, {vim, uiEvent}) ->
169 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['left'],
170 [amount], ['scrollLeftMax'])
171 helper_mark_last_scroll_position(vim)
172
173 helper_scrollToY = (amount, {vim, uiEvent}) ->
174 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['top'],
175 [amount], ['scrollTopMax'])
176 helper_mark_last_scroll_position(vim)
177
178 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
179 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
180 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
181 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
182 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
183 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
184 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
185 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
186 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
187 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
188 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
189 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
190
191 helper_mark_last_scroll_position = (vim) ->
192 keyStr = vim.options['scroll.last_position_mark']
193 vim._run('mark_scroll_position', {keyStr, notify: false})
194
195 commands.mark_scroll_position = ({vim}) ->
196 vim.enterMode('marks', (keyStr) -> vim._run('mark_scroll_position', {keyStr}))
197
198 commands.scroll_to_mark = ({vim}) ->
199 vim.enterMode('marks', (keyStr) ->
200 unless keyStr == vim.options['scroll.last_position_mark']
201 helper_mark_last_scroll_position(vim)
202 helper_scroll(vim, null, 'scrollTo', 'other', ['top', 'left'], keyStr,
203 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark')
204 )
205
206
207
208 commands.tab_new = ({vim}) ->
209 utils.nextTick(vim.window, ->
210 vim.window.BrowserOpenTab()
211 )
212
213 commands.tab_duplicate = ({vim}) ->
214 {gBrowser} = vim.window
215 utils.nextTick(vim.window, ->
216 gBrowser.duplicateTab(gBrowser.selectedTab)
217 )
218
219 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
220 tabs = gBrowser.visibleTabs
221 {selectedTab} = gBrowser
222
223 currentIndex = tabs.indexOf(selectedTab)
224 absoluteIndex = currentIndex + relativeIndex
225 numTabsTotal = tabs.length
226 numPinnedTabs = gBrowser._numPinnedTabs
227
228 [numTabs, min] = switch
229 when not pinnedSeparate then [numTabsTotal, 0]
230 when selectedTab.pinned then [numPinnedTabs, 0]
231 else [numTabsTotal - numPinnedTabs, numPinnedTabs]
232
233 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
234 # current direction.
235 if (relativeIndex < 0 and currentIndex == min) or
236 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
237 if absoluteIndex < min
238 absoluteIndex += numTabs
239 else if absoluteIndex >= min + numTabs
240 absoluteIndex -= numTabs
241
242 absoluteIndex = Math.max(min, absoluteIndex)
243 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
244
245 return absoluteIndex
246
247 helper_switch_tab = (direction, {vim, count = 1}) ->
248 {gBrowser} = vim.window
249 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
250 utils.nextTick(vim.window, ->
251 gBrowser.selectTabAtIndex(index)
252 )
253
254 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
255
256 commands.tab_select_next = helper_switch_tab.bind(null, +1)
257
258 commands.tab_select_most_recent = ({vim}) ->
259 {gBrowser} = vim.window
260 mostRecentTab = null
261 for tab in gBrowser.tabs when not tab.closing and tab != gBrowser.selectedTab
262 if not mostRecentTab or tab.lastAccessed > mostRecentTab.lastAccessed
263 mostRecentTab = tab
264 gBrowser.selectedTab = mostRecentTab if mostRecentTab
265
266 helper_move_tab = (direction, {vim, count = 1}) ->
267 {gBrowser} = vim.window
268 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
269 utils.nextTick(vim.window, ->
270 gBrowser.moveTabTo(gBrowser.selectedTab, index)
271 )
272
273 commands.tab_move_backward = helper_move_tab.bind(null, -1)
274
275 commands.tab_move_forward = helper_move_tab.bind(null, +1)
276
277 commands.tab_move_to_window = ({vim}) ->
278 {gBrowser} = vim.window
279 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
280
281 commands.tab_select_first = ({vim, count = 1}) ->
282 utils.nextTick(vim.window, ->
283 vim.window.gBrowser.selectTabAtIndex(count - 1)
284 )
285
286 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
287 firstNonPinned = vim.window.gBrowser._numPinnedTabs
288 utils.nextTick(vim.window, ->
289 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
290 )
291
292 commands.tab_select_last = ({vim, count = 1}) ->
293 utils.nextTick(vim.window, ->
294 vim.window.gBrowser.selectTabAtIndex(-count)
295 )
296
297 commands.tab_toggle_pinned = ({vim}) ->
298 currentTab = vim.window.gBrowser.selectedTab
299 if currentTab.pinned
300 vim.window.gBrowser.unpinTab(currentTab)
301 else
302 vim.window.gBrowser.pinTab(currentTab)
303
304 commands.tab_close = ({vim, count = 1}) ->
305 {gBrowser} = vim.window
306 return if gBrowser.selectedTab.pinned
307 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
308 utils.nextTick(vim.window, ->
309 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
310 gBrowser.removeTab(tab)
311 return
312 )
313
314 commands.tab_restore = ({vim, count = 1}) ->
315 utils.nextTick(vim.window, ->
316 for index in [0...count] by 1
317 restoredTab = vim.window.undoCloseTab()
318 if not restoredTab and index == 0
319 vim.notify(translate('notification.tab_restore.none'))
320 break
321 return
322 )
323
324 commands.tab_restore_list = ({vim}) ->
325 {window} = vim
326 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
327 window, 'menuitem'
328 )
329 if fragment.childElementCount == 0
330 vim.notify(translate('notification.tab_restore.none'))
331 else
332 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
333
334 commands.tab_close_to_end = ({vim}) ->
335 {gBrowser} = vim.window
336 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
337
338 commands.tab_close_other = ({vim}) ->
339 {gBrowser} = vim.window
340 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
341
342
343
344 helper_follow = (name, vim, callback, count = null) ->
345 vim.markPageInteraction()
346
347 # Enter hints mode immediately, with an empty set of markers. The user might
348 # press keys before the `vim._run` callback is invoked. Those key presses
349 # should be handled in hints mode, not normal mode.
350 initialMarkers = []
351 storage = vim.enterMode('hints', initialMarkers, callback, count,
352 vim.options.hints_sleep)
353
354 vim._run(name, null, ({wrappers, viewport}) ->
355 # The user might have exited hints mode (and perhaps even entered it again)
356 # before this callback is invoked. If so, `storage.markers` has been
357 # cleared, or set to a new value. Only proceed if it is unchanged.
358 return unless storage.markers == initialMarkers
359
360 if wrappers.length > 0
361 {markers, markerMap} = hints.injectHints(vim.window, wrappers, viewport,
362 vim.options)
363 storage.markers = markers
364 storage.markerMap = markerMap
365 else
366 vim.notify(translate('notification.follow.none'))
367 vim.enterMode('normal')
368 )
369
370 helper_follow_clickable = ({inTab, inBackground}, {vim, count = 1}) ->
371 callback = (marker, timesLeft, keyStr) ->
372 {type, elementIndex} = marker.wrapper
373 isLast = (timesLeft == 1)
374 isLink = (type == 'link')
375
376 switch
377 when keyStr.startsWith(vim.options.hints_toggle_in_tab)
378 inTab = not inTab
379 when keyStr.startsWith(vim.options.hints_toggle_in_background)
380 inTab = true
381 inBackground = not inBackground
382 else
383 unless isLast
384 inTab = true
385 inBackground = true
386
387 inTab = false unless isLink
388
389 if type == 'text' or (isLink and not (inTab and inBackground))
390 isLast = true
391
392 vim._focusMarkerElement(elementIndex)
393
394 if inTab
395 utils.nextTick(vim.window, ->
396 utils.openTab(vim.window, marker.wrapper.href, {
397 inBackground
398 relatedToCurrent: true
399 })
400 )
401 else
402 vim._run('click_marker_element', {
403 elementIndex, type
404 preventTargetBlank: vim.options.prevent_target_blank
405 })
406
407 return not isLast
408
409 name = if inTab then 'follow_in_tab' else 'follow'
410 helper_follow(name, vim, callback, count)
411
412 commands.follow =
413 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
414
415 commands.follow_in_tab =
416 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
417
418 commands.follow_in_focused_tab =
419 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
420
421 commands.follow_in_window = ({vim}) ->
422 callback = (marker) ->
423 vim._focusMarkerElement(marker.wrapper.elementIndex)
424 vim.window.openLinkIn(marker.wrapper.href, 'window', {})
425 helper_follow('follow_in_tab', vim, callback)
426
427 commands.follow_multiple = (args) ->
428 args.count = Infinity
429 commands.follow(args)
430
431 commands.follow_copy = ({vim}) ->
432 callback = (marker) ->
433 {elementIndex} = marker.wrapper
434 property = switch marker.wrapper.type
435 when 'link' then 'href'
436 when 'text' then 'value'
437 when 'contenteditable' then 'textContent'
438 vim._run('copy_marker_element', {elementIndex, property})
439 helper_follow('follow_copy', vim, callback)
440
441 commands.follow_focus = ({vim}) ->
442 callback = (marker) ->
443 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
444 return helper_follow('follow_focus', vim, callback)
445
446 commands.click_browser_element = ({vim}) ->
447 markerElements = []
448
449 filter = (element, getElementShape) ->
450 document = element.ownerDocument
451 type = switch
452 when vim._state.scrollableElements.has(element)
453 'scrollable'
454 when element.tabIndex > -1 and
455 # `.localName` is `.nodeName` without `xul:` (if it exists).
456 not (element.localName.endsWith('box') and
457 element.localName != 'checkbox') and
458 element.localName not in ['tabs', 'menuitem', 'menuseparator']
459 'clickable'
460 return unless type
461 return unless shape = getElementShape(element)
462 length = markerElements.push(element)
463 return {type, semantic: true, shape, elementIndex: length - 1}
464
465 callback = (marker) ->
466 element = markerElements[marker.wrapper.elementIndex]
467 switch marker.wrapper.type
468 when 'scrollable'
469 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
470 when 'clickable'
471 utils.focusElement(element)
472 utils.simulateMouseEvents(element, 'click')
473
474 {wrappers, viewport} =
475 hints.getMarkableElementsAndViewport(vim.window, filter)
476
477 if wrappers.length > 0
478 {markers} = hints.injectHints(vim.window, wrappers, viewport, {
479 hint_chars: vim.options.hint_chars
480 ui: true
481 })
482 vim.enterMode('hints', markers, callback)
483 else
484 vim.notify(translate('notification.follow.none'))
485
486 helper_follow_pattern = (type, {vim}) ->
487 options =
488 pattern_selector: vim.options.pattern_selector
489 pattern_attrs: vim.options.pattern_attrs
490 patterns: vim.options["#{type}_patterns"]
491 vim._run('follow_pattern', {type, options})
492
493 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
494
495 commands.follow_next = helper_follow_pattern.bind(null, 'next')
496
497 commands.focus_text_input = ({vim, count}) ->
498 vim.markPageInteraction()
499 vim._run('focus_text_input', {count})
500
501
502
503 findStorage = {lastSearchString: ''}
504
505 helper_find = ({highlight, linksOnly = false}, {vim}) ->
506 helpSearchInput = help.getSearchInput(vim.window)
507 if helpSearchInput
508 helpSearchInput.select()
509 return
510
511 helper_mark_last_scroll_position(vim)
512 findBar = vim.window.gBrowser.getFindBar()
513
514 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
515 findBar.startFind(mode)
516 utils.focusElement(findBar._findField, {select: true})
517
518 return if linksOnly
519 return unless highlightButton = findBar.getElement('highlight')
520 if highlightButton.checked != highlight
521 highlightButton.click()
522
523 commands.find = helper_find.bind(null, {highlight: false})
524
525 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
526
527 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
528
529 helper_find_again = (direction, {vim}) ->
530 findBar = vim.window.gBrowser.getFindBar()
531 if findStorage.lastSearchString.length == 0
532 vim.notify(translate('notification.find_again.none'))
533 return
534 helper_mark_last_scroll_position(vim)
535 findBar._findField.value = findStorage.lastSearchString
536 findBar.onFindAgainCommand(direction)
537 message = findBar._findStatusDesc.textContent
538 vim.notify(message) if message
539
540 commands.find_next = helper_find_again.bind(null, false)
541
542 commands.find_previous = helper_find_again.bind(null, true)
543
544
545
546 commands.window_new = ({vim}) ->
547 vim.window.OpenBrowserWindow()
548
549 commands.window_new_private = ({vim}) ->
550 vim.window.OpenBrowserWindow({private: true})
551
552 commands.enter_mode_ignore = ({vim}) ->
553 vim.enterMode('ignore')
554
555 # Quote next keypress (pass it through to the page).
556 commands.quote = ({vim, count = 1}) ->
557 vim.enterMode('ignore', count)
558
559 commands.enter_reader_view = ({vim}) ->
560 button = vim.window.document.getElementById('reader-mode-button')
561 if not button?.hidden
562 button.click()
563 else
564 vim.notify(translate('notification.enter_reader_view.none'))
565
566 commands.help = ({vim}) ->
567 help.injectHelp(vim.window, vim._parent)
568
569 commands.dev = ({vim}) ->
570 vim.window.DeveloperToolbar.show(true) # `true` to focus.
571
572 commands.esc = ({vim}) ->
573 vim._run('esc')
574 utils.blurActiveBrowserElement(vim)
575 vim.window.DeveloperToolbar.hide()
576 vim.window.gBrowser.getFindBar().close()
577 # TODO: Remove when Tab Groups have been removed.
578 vim.window.TabView?.hide()
579 hints.removeHints(vim.window) # Better safe than sorry.
580
581 unless help.getSearchInput(vim.window)?.getAttribute('focused')
582 help.removeHelp(vim.window)
583
584
585
586 module.exports = {
587 commands
588 findStorage
589 }
Imprint / Impressum