qutebrowser/qutebrowser/commands/utils.py

62 lines
1.7 KiB
Python
Raw Normal View History

2013-12-16 22:07:22 +01:00
from PyQt5.QtCore import QObject, pyqtSignal
2014-01-16 17:12:55 +01:00
import inspect, sys
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 10:57:27 +01:00
for (name, cls) in inspect.getmembers(commands, is_cmd):
2014-01-17 11:14:19 +01:00
if cls.bind:
if cls.name is None:
name = cls.__name__.tolower()
else:
name = cls.name
cmd_dict[name] = cls()
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
2014-01-17 11:14:19 +01:00
bind = True
2014-01-16 17:12:55 +01:00
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!")
2014-01-17 08:11:29 +01:00
def run(self, argv=None):
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:
self.signal.emit()
elif self.nargs == 1:
self.signal.emit(argv[0])
else:
raise NotImplementedError