Lua quirks

This commit is contained in:
Kiooeht 2012-11-12 20:52:26 -08:00
parent 5f33da3aeb
commit 4b39e0f3c6
6 changed files with 182 additions and 62 deletions

44
luaquirks.py Normal file
View file

@ -0,0 +1,44 @@
import os, sys, re, ostools
try:
import lua
except ImportError:
lua = None
from quirks import ScriptQuirks
from PyQt4 import QtGui, QtCore
class LuaQuirks(ScriptQuirks):
def loadModule(self, name, filename):
if lua is None:
return None
fullname = os.path.join('quirks', name)
lua.globals().package.loaded[fullname] = None
return lua.require(fullname)
def getExtension(self):
return '.lua'
def modHas(self, module, attr):
return module[attr] is not None
def register(self, module):
class Wrapper(object):
def __init__(self, module, name):
self.module = module
self.name = name
def __call__(self, text):
return self.module.commands[self.name](lua.globals().tostring(text))
for name in module.commands:
try:
if not isinstance(module.commands[name]("test"), basestring):
raise Exception
except:
print "Quirk malformed: %s" % (name)
msgbox = QtGui.QMessageBox()
msgbox.setWindowTitle("Error!")
msgbox.setText("Quirk malformed: %s" % (name))
msgbox.exec_()
else:
self.quirks[name] = Wrapper(module, name)

View file

@ -323,7 +323,7 @@ class PesterQuirkTypes(QtGui.QDialog):
self.funclist2.setStyleSheet("color: #000000; background-color: #FFFFFF;")
from parsetools import quirkloader
funcs = [q+")" for q in quirkloader.quirks.keys()]
funcs = [q+"()" for q in quirkloader.quirks.keys()]
funcs.sort()
self.funclist.addItems(funcs)
self.funclist2.addItems(funcs)
@ -561,7 +561,7 @@ class PesterQuirkTypes(QtGui.QDialog):
def reloadQuirkFuncSlot(self):
from parsetools import reloadQuirkFunctions, quirkloader
reloadQuirkFunctions()
funcs = [q+")" for q in quirkloader.quirks.keys()]
funcs = [q+"()" for q in quirkloader.quirks.keys()]
funcs.sort()
self.funclist.clear()
self.funclist.addItems(funcs)

View file

@ -6,7 +6,9 @@ from datetime import timedelta
from PyQt4 import QtGui
from generic import mysteryTime
from quirks import ScriptQuirks
from pyquirks import PythonQuirks
from luaquirks import LuaQuirks
_ctag_begin = re.compile(r'(?i)<c=(.*?)>')
_gtag_begin = re.compile(r'(?i)<g[a-f]>')
@ -23,12 +25,16 @@ _format_begin = re.compile(r'(?i)<([ibu])>')
_format_end = re.compile(r'(?i)</([ibu])>')
_honk = re.compile(r"(?i)\bhonk\b")
quirkloader = PythonQuirks()
quirkloader = ScriptQuirks()
quirkloader.add(PythonQuirks())
quirkloader.add(LuaQuirks())
quirkloader.loadAll()
print quirkloader.funcre()
_functionre = re.compile(r"%s" % quirkloader.funcre())
_groupre = re.compile(r"\\([0-9]+)")
def reloadQuirkFunctions():
quirkloader.load()
quirkloader.loadAll()
global _functionre
_functionre = re.compile(r"%s" % quirkloader.funcre())
@ -395,8 +401,8 @@ def parseRegexpFunctions(to):
backr = _groupre.search(mo.group())
if backr is not None:
current.append(backreference(backr.group(1)))
elif mo.group() in functiondict.keys():
p = parseLeaf(functiondict[mo.group()], current)
elif mo.group()[:-1] in functiondict.keys():
p = parseLeaf(functiondict[mo.group()[:-1]], current)
current.append(p)
current = p
elif mo.group() == ")":

View file

@ -1,57 +1,26 @@
import os, sys, imp, re, ostools
from quirks import ScriptQuirks
from PyQt4 import QtGui, QtCore
class PythonQuirks(object):
def __init__(self):
self._datadir = ostools.getDataDir()
self.home = os.getcwd()
self.quirks = {}
self.last = {}
self.load()
class PythonQuirks(ScriptQuirks):
def loadModule(self, name, filename):
return imp.load_source(name, filename)
def load(self):
self.last = self.quirks.copy()
self.quirks.clear()
filenames = []
if not os.path.exists(os.path.join(self.home, 'quirks')):
os.mkdir(os.path.join(self.home, 'quirks'))
for fn in os.listdir(os.path.join(self.home, 'quirks')):
if fn.endswith('.py') and not fn.startswith('_'):
filenames.append(os.path.join(self.home, 'quirks', fn))
if self._datadir:
if not os.path.exists(os.path.join(self._datadir, 'quirks')):
os.mkdir(os.path.join(self._datadir, 'quirks'))
for fn in os.listdir(os.path.join(self._datadir, 'quirks')):
if fn.endswith('.py') and not fn.startswith('_'):
filenames.append(os.path.join(self._datadir, 'quirks', fn))
def getExtension(self):
return '.py'
modules = []
for filename in filenames:
name = os.path.basename(filename)[:-3]
try: module = imp.load_source(name, filename)
except Exception, e:
print "Error loading %s: %s (in pyquirks.py)" % (name, e)
msgbox = QtGui.QMessageBox()
msgbox.setWindowTitle("Error!")
msgbox.setText("Error loading %s: %s (in pyquirks.py)" % (name, e))
msgbox.exec_()
else:
if hasattr(module, 'setup'):
module.setup()
self.register(vars(module))
modules.append(name)
for k in self.last:
if k in self.quirks:
if self.last[k] == self.quirks[k]:
del self.quirks[k]
if self.quirks:
print 'Registered quirks:', '), '.join(self.quirks) + ")"
else:print "Warning: Couldn't find any python quirks"
def register(self, variables):
def modHas(self, module, attr):
if attr == 'commands':
variables = vars(module)
for name, obj in variables.iteritems():
if hasattr(obj, 'command'):
if self.modHas(obj, 'command'):
return True
return hasattr(module, attr)
def register(self, module):
variables = vars(module)
for name, obj in variables.iteritems():
if self.modHas(obj, 'command'):
try:
if not isinstance(obj("test"), basestring):
raise Exception
@ -62,13 +31,5 @@ class PythonQuirks(object):
msgbox.setText("Quirk malformed: %s" % (obj.command))
msgbox.exec_()
else:
self.quirks[obj.command+"("] = obj
self.quirks[obj.command] = obj
def funcre(self):
if not self.quirks:
return r"\\[0-9]+"
f = r"("
for q in self.quirks:
f = f + q[:-1]+r"\(|"
f = f + r"\)|\\[0-9]+)"
return f

91
quirks.py Normal file
View file

@ -0,0 +1,91 @@
import os, sys, re, ostools
from PyQt4 import QtGui, QtCore
class ScriptQuirks(object):
def __init__(self):
self._datadir = ostools.getDataDir()
self.home = os.getcwd()
self.quirks = {}
self.last = {}
self.scripts = []
#self.load()
def loadModule(self, name, filename):
raise Exception
def modHas(self, module, attr):
return False
def loadAll(self):
self.last = self.quirks.copy()
self.quirks.clear()
for script in self.scripts:
print script.getExtension()
script.load()
#print script.quirks
for q in script.quirks:
self.quirks.update(script.quirks)
for k in self.last:
if k in self.quirks:
if self.last[k] == self.quirks[k]:
del self.quirks[k]
#print self.quirks
if self.quirks:
print 'Registered quirks:', '(), '.join(self.quirks) + "()"
else:
print "Warning: Couldn't find any script quirks"
def add(self, script):
self.scripts.append(script)
def load(self):
self.last = self.quirks.copy()
self.quirks.clear()
extension = self.getExtension()
filenames = []
if not os.path.exists(os.path.join(self.home, 'quirks')):
os.mkdir(os.path.join(self.home, 'quirks'))
for fn in os.listdir(os.path.join(self.home, 'quirks')):
if fn.endswith(extension) and not fn.startswith('_'):
filenames.append(os.path.join(self.home, 'quirks', fn))
if self._datadir:
if not os.path.exists(os.path.join(self._datadir, 'quirks')):
os.mkdir(os.path.join(self._datadir, 'quirks'))
for fn in os.listdir(os.path.join(self._datadir, 'quirks')):
if fn.endswith(extension) and not fn.startswith('_'):
filenames.append(os.path.join(self._datadir, 'quirks', fn))
modules = []
for filename in filenames:
extension_length = len(self.getExtension())
name = os.path.basename(filename)[:-extension_length]
try:
module = self.loadModule(name, filename)
if module is None:
continue
except Exception, e:
print "Error loading %s: %s (in quirks.py)" % (os.path.basename(name), e)
msgbox = QtGui.QMessageBox()
msgbox.setWindowTitle("Error!")
msgbox.setText("Error loading %s: %s (in quirks.py)" % (os.path.basename(filename), e))
msgbox.exec_()
else:
if self.modHas(module, 'setup'):
module.setup()
if self.modHas(module, 'commands'):
self.register(module)
modules.append(name)
for k in self.last:
if k in self.quirks:
if self.last[k] == self.quirks[k]:
del self.quirks[k]
def funcre(self):
if not self.quirks:
return r"\\[0-9]+"
f = r"("
for q in self.quirks:
f = f + q+r"\(|"
f = f + r"\)|\\[0-9]+)"
return f

18
quirks/example.lua Normal file
View file

@ -0,0 +1,18 @@
module(..., package.seeall)
commands = {}
local function upper(text)
return string.upper(text)
end
commands.luaupper = upper
local function lower(text)
return string.lower(text)
end
commands.lualower = lower
local function utf8reverse(text)
return text:gsub("([\194-\244][\128-\191]+)", string.reverse):reverse()
end
commands.luareverse = utf8reverse