Move keyboard macro system to MacroRecorder object

This commit is contained in:
Jan Verbeek 2016-10-20 02:50:00 +02:00
parent 2a304d7a6b
commit f2b05a0395
5 changed files with 123 additions and 74 deletions

View File

@ -49,6 +49,7 @@ from qutebrowser.browser import urlmarks, adblock, history, browsertab
from qutebrowser.browser.webkit import cookies, cache, downloads
from qutebrowser.browser.webkit.network import (webkitqutescheme, proxy,
networkmanager)
from qutebrowser.keyinput import macros
from qutebrowser.mainwindow import mainwindow
from qutebrowser.misc import (readline, ipc, savemanager, sessions,
crashsignal, earlyinit)
@ -157,6 +158,8 @@ def init(args, crash_handler):
QDesktopServices.setUrlHandler('https', open_desktopservices_url)
QDesktopServices.setUrlHandler('qute', open_desktopservices_url)
macros.init()
log.init.debug("Init done!")
crash_handler.raise_crashdlg()

View File

@ -34,10 +34,6 @@ from qutebrowser.misc import split
ParseResult = collections.namedtuple('ParseResult', ['cmd', 'args', 'cmdline'])
last_command = {}
macro = {}
recording_macro = None
macro_count = {}
def _current_url(tabbed_browser):
"""Convenience method to get the current url."""
@ -263,27 +259,33 @@ class CommandRunner(QObject):
text: The text to parse.
count: The count to pass to the command.
"""
for result in self.parse_all(text):
mode_manager = objreg.get('mode-manager', scope='window',
window=self._win_id)
cur_mode = mode_manager.mode
record_last_command = True
record_macro = True
mode_manager = objreg.get('mode-manager', scope='window',
window=self._win_id)
cur_mode = mode_manager.mode
for result in self.parse_all(text):
if result.cmd.no_replace_variables:
args = result.args
else:
args = replace_variables(self._win_id, result.args)
result.cmd.run(self._win_id, args, count=count)
parsed_command = (text, count)
if result.cmdline[0] == 'repeat-command':
record_last_command = False
if result.cmdline[0] != 'repeat-command':
last_command[cur_mode] = parsed_command
if result.cmdline[0] in ['record-macro', 'run-macro',
'set-cmd-text']:
record_macro = False
if (recording_macro is not None and
cur_mode == usertypes.KeyMode.normal and
result.cmdline[0] not in ['record-macro', 'run-macro',
'set-cmd-text']):
macro[recording_macro].append(parsed_command)
if record_last_command:
last_command[cur_mode] = (text, count)
if record_macro and cur_mode == usertypes.KeyMode.normal:
macro_recorder = objreg.get('macro-recorder')
macro_recorder.record(text, count)
@pyqtSlot(str, int)
@pyqtSlot(str)

View File

@ -0,0 +1,99 @@
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2016 Jan Verbeek (blyxxyz) <ring@openmailbox.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Keyboard macro system."""
from qutebrowser.commands import cmdexc, cmdutils, runners
from qutebrowser.utils import message, objreg, usertypes
class MacroRecorder:
"""An object for recording and running keyboard macros."""
def __init__(self):
self.macro = {}
self.recording_macro = None
self.macro_count = {}
@cmdutils.register(instance='macro-recorder', name='record-macro')
@cmdutils.argument('win_id', win_id=True)
@cmdutils.argument('register')
def record_macro_command(self, win_id, register=None):
"""Start or stop recording a macro.
Args:
register: Which register to store the macro in.
"""
if self.recording_macro is None:
if register is None:
mode_manager = objreg.get('mode-manager', scope='window',
window=win_id)
mode_manager.enter(usertypes.KeyMode.record_macro,
'record_macro')
else:
self.record_macro(register)
else:
message.info("Macro recorded.")
self.recording_macro = None
def record_macro(self, register):
"""Start recording a macro."""
message.info("Recording macro...")
self.macro[register] = []
self.recording_macro = register
@cmdutils.register(instance='macro-recorder', name='run-macro')
@cmdutils.argument('win_id', win_id=True)
@cmdutils.argument('count', count=True)
@cmdutils.argument('register')
def run_macro_command(self, win_id, count=1, register=None):
"""Run a recorded macro.
Args:
count: How many times to run the macro.
register: Which macro to run.
"""
self.macro_count[win_id] = count
if register is None:
mode_manager = objreg.get('mode-manager', scope='window',
window=win_id)
mode_manager.enter(usertypes.KeyMode.run_macro, 'run_macro')
else:
self.run_macro(win_id, register)
def run_macro(self, win_id, register):
"""Run a recorded macro."""
if register not in self.macro:
raise cmdexc.CommandError(
"No macro recorded in '{}'!".format(register))
commandrunner = runners.CommandRunner(win_id)
for _ in range(self.macro_count[win_id]):
for cmd in self.macro[register]:
commandrunner.run_safely(*cmd)
def record(self, text, count):
"""Record a command if a macro is being recorded."""
if self.recording_macro is not None:
self.macro[self.recording_macro].append((text, count))
def init():
"""Initialize the MacroRecorder."""
macro_recorder = MacroRecorder()
objreg.register('macro-recorder', macro_recorder)

View File

@ -27,7 +27,6 @@ from PyQt5.QtCore import pyqtSlot, Qt
from qutebrowser.config import config
from qutebrowser.keyinput import keyparser
from qutebrowser.misc import utilcmds
from qutebrowser.utils import usertypes, log, objreg, utils
@ -296,15 +295,16 @@ class RegisterKeyParser(keyparser.BaseKeyParser):
tabbed_browser = objreg.get('tabbed-browser', scope='window',
window=self._win_id)
macro_recorder = objreg.get('macro-recorder')
if self._mode == usertypes.KeyMode.set_mark:
tabbed_browser.set_mark(key)
elif self._mode == usertypes.KeyMode.jump_mark:
tabbed_browser.jump_mark(key)
elif self._mode == usertypes.KeyMode.record_macro:
utilcmds.record_macro(key)
macro_recorder.record_macro(key)
elif self._mode == usertypes.KeyMode.run_macro:
utilcmds.run_macro(self._win_id, key)
macro_recorder.run_macro(self._win_id, key)
else:
raise ValueError(
"{} is not a valid register key".format(self._mode))

View File

@ -251,61 +251,6 @@ def repeat_command(win_id, count=None):
commandrunner.run(cmd[0], count if count is not None else cmd[1])
@cmdutils.register(instance='mode-manager', name='record-macro',
scope='window')
@cmdutils.argument('register')
def record_macro_command(self, register=None):
"""Start or stop recording a macro.
Args:
register: Which register to store the macro in.
"""
if runners.recording_macro is None:
if register is None:
self.enter(usertypes.KeyMode.record_macro, 'record_macro')
else:
record_macro(register)
else:
message.info("Macro recorded.")
runners.recording_macro = None
def record_macro(register):
"""Start recording a macro."""
message.info("Recording macro...")
runners.macro[register] = []
runners.recording_macro = register
@cmdutils.register(instance='mode-manager', name='run-macro', scope='window')
@cmdutils.argument('win_id', win_id=True)
@cmdutils.argument('count', count=True)
@cmdutils.argument('register')
def run_macro_command(self, win_id, count=1, register=None):
"""Run a recorded macro.
Args:
count: How many times to run the macro.
register: Which macro to run.
"""
runners.macro_count[win_id] = count
if register is None:
self.enter(usertypes.KeyMode.run_macro, 'run_macro')
else:
run_macro(win_id, register)
def run_macro(win_id, register):
"""Run a recorded macro."""
if register not in runners.macro:
raise cmdexc.CommandError(
"No macro recorded in '{}'!".format(register))
commandrunner = runners.CommandRunner(win_id)
for _ in range(runners.macro_count[win_id]):
for cmd in runners.macro[register]:
commandrunner.run(*cmd)
@cmdutils.register(debug=True, name='debug-log-capacity')
def log_capacity(capacity: int):
"""Change the number of log lines to be stored in RAM.