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():
|
|
|
|
def is_cmd(obj):
|
|
|
|
return (inspect.isclass(obj) and obj.__module__ == __name__ and
|
|
|
|
obj.__name__.endswith('Cmd'))
|
|
|
|
|
|
|
|
for (name, cls) in inspect.getmembers(sys.modules[__name__], is_cmd):
|
|
|
|
cls.bind()
|
2013-12-16 22:07:22 +01:00
|
|
|
|
|
|
|
class CommandParser(QObject):
|
2014-01-16 17:12:55 +01:00
|
|
|
def parse(self, test):
|
|
|
|
parts = text.lstrip(':').strip().split()
|
|
|
|
cmd = parts[0]
|
|
|
|
args = parts[1:]
|
2014-01-16 17:26:07 +01:00
|
|
|
obj = cmd_dict[cmd]()
|
|
|
|
try:
|
|
|
|
obj.check(args)
|
|
|
|
except TypeError:
|
|
|
|
# TODO
|
|
|
|
raise
|
|
|
|
obj.run(args)
|
2014-01-16 17:12:55 +01:00
|
|
|
|
|
|
|
class Command(QObject):
|
|
|
|
nargs = 0
|
|
|
|
name = ''
|
|
|
|
signal = None
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def bind(cls):
|
|
|
|
if cls.name:
|
|
|
|
cmd_dict[cls.name] = cls
|
|
|
|
|
2014-01-16 17:26:07 +01:00
|
|
|
def check(self, *args):
|
|
|
|
if ((isinstance(self.nargs, int) and len(args) != self.nargs) or
|
|
|
|
(self.nargs == '?' and len(args) > 1) or
|
|
|
|
(self.nargs == '+' and len(args) < 1)):
|
|
|
|
raise TypeError("Invalid argument count!")
|
|
|
|
|
2014-01-16 17:12:55 +01:00
|
|
|
def run(self, *args):
|
2014-01-16 17:26:07 +01:00
|
|
|
if not self.signal:
|
|
|
|
raise NotImplementedError
|
2014-01-16 17:12:55 +01:00
|
|
|
self.signal.emit(*args)
|
|
|
|
|
|
|
|
class OpenCmd(Command):
|
|
|
|
nargs = 1
|
|
|
|
name = 'open'
|
|
|
|
signal = pyqtSignal(str)
|
|
|
|
|
|
|
|
class TabOpenCmd(Command):
|
|
|
|
nargs = 1
|
|
|
|
name = 'tabopen'
|
|
|
|
signal = pyqtSignal(str)
|
|
|
|
|
2014-01-16 17:45:12 +01:00
|
|
|
class QuitCmd(Command):
|
|
|
|
nargs = 0
|
|
|
|
name = 'quit'
|
|
|
|
signal = pyqtSignal()
|
|
|
|
|
2014-01-16 17:12:55 +01:00
|
|
|
register_all()
|