qutebrowser/qutebrowser/commands/utils.py

76 lines
2.1 KiB
Python
Raw Normal View History

import inspect
import sys
import logging
2013-12-16 22:07:22 +01:00
from PyQt5.QtCore import QObject, pyqtSignal
2014-01-16 17:12:55 +01:00
cmd_dict = {}
def register_all():
2014-01-17 11:28:35 +01:00
import qutebrowser.commands.commands
2014-01-16 17:12:55 +01:00
def is_cmd(obj):
2014-01-17 10:57:27 +01:00
return (inspect.isclass(obj) and
obj.__module__ == 'qutebrowser.commands.commands')
2014-01-16 17:12:55 +01:00
2014-01-17 11:28:46 +01:00
for (name, cls) in inspect.getmembers(qutebrowser.commands.commands,
is_cmd):
2014-01-17 11:14:19 +01:00
if cls.bind:
2014-01-17 11:55:16 +01:00
obj = cls()
cmd_dict[obj.name] = obj
2013-12-16 22:07:22 +01:00
class CommandParser(QObject):
2014-01-17 07:04:24 +01:00
error = pyqtSignal(str)
2014-01-16 16:00:25 +01:00
def parse(self, text):
2014-01-16 17:49:57 +01:00
parts = text.strip().split()
2014-01-16 17:12:55 +01:00
cmd = parts[0]
2014-01-16 16:05:31 +01:00
argv = parts[1:]
2014-01-17 07:04:24 +01:00
try:
obj = cmd_dict[cmd]
except KeyError:
self.error.emit("{}: no such command".format(cmd))
return
2014-01-16 17:26:07 +01:00
try:
2014-01-16 16:05:31 +01:00
obj.check(argv)
2014-01-16 17:26:07 +01:00
except TypeError:
2014-01-17 07:06:49 +01:00
self.error.emit("{}: invalid argument count".format(cmd))
return
2014-01-16 16:05:31 +01:00
obj.run(argv)
2014-01-16 17:12:55 +01:00
class Command(QObject):
nargs = 0
2014-01-17 06:56:18 +01:00
name = None
2014-01-17 06:51:21 +01:00
key = None
2014-01-16 17:12:55 +01:00
signal = None
count = False
2014-01-17 11:14:19 +01:00
bind = True
2014-01-16 17:12:55 +01:00
2014-01-17 11:55:16 +01:00
def __init__(self):
super().__init__()
if self.name is None:
self.name = self.__class__.__name__.lower()
2014-01-16 16:05:31 +01:00
def check(self, argv):
if ((isinstance(self.nargs, int) and len(argv) != self.nargs) or
(self.nargs == '?' and len(argv) > 1) or
(self.nargs == '+' and len(argv) < 1)):
2014-01-16 17:26:07 +01:00
raise TypeError("Invalid argument count!")
def run(self, argv=None, count=None):
logging.debug("Cmd called: {}({})".format(self.__class__.__name__,
", ".join(argv) if argv else ''))
2014-01-16 17:26:07 +01:00
if not self.signal:
raise NotImplementedError
2014-01-17 08:11:49 +01:00
# some sane defaults
if self.nargs == 0:
if count is not None:
self.signal.emit(count)
else:
self.signal.emit()
2014-01-17 08:11:49 +01:00
elif self.nargs == 1:
if count is not None:
self.signal.emit(count, argv[0])
else:
self.signal.emit(argv[0])
2014-01-17 08:11:49 +01:00
else:
raise NotImplementedError