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