code style reformatting using black

This commit is contained in:
Goffi 2018-06-27 20:14:46 +02:00
commit 744cb0c503
10 changed files with 21394 additions and 10488 deletions

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
@ -30,62 +30,73 @@ class DbusXmlConstructor(base_constructor.Constructor):
self.template = "dbus_xml_template.xml"
self.core_dest = "org.goffi.sat.xml"
self.default_annotation = {'a{ss}': 'StringDict',
'a(sa{ss}as)': 'QList<Contact>',
'a{i(ss)}': 'HistoryT',
'a(sss)': 'QList<MenuT>',
'a{sa{s(sia{ss})}}': 'PresenceStatusT',
}
self.default_annotation = {
"a{ss}": "StringDict",
"a(sa{ss}as)": "QList<Contact>",
"a{i(ss)}": "HistoryT",
"a(sss)": "QList<MenuT>",
"a{sa{s(sia{ss})}}": "PresenceStatusT",
}
def generateCoreSide(self):
try:
doc = minidom.parse(self.getTemplatePath(self.template))
interface_elt = doc.getElementsByTagName('interface')[0]
interface_elt = doc.getElementsByTagName("interface")[0]
except IOError:
print ("Can't access template")
print("Can't access template")
sys.exit(1)
except IndexError:
print ("Template error")
print("Template error")
sys.exit(1)
sections = self.bridge_template.sections()
sections.sort()
for section in sections:
function = self.getValues(section)
print ("Adding %s %s" % (section, function["type"]))
new_elt = doc.createElement('method' if function["type"] == 'method' else 'signal')
new_elt.setAttribute('name', section)
print("Adding %s %s" % (section, function["type"]))
new_elt = doc.createElement(
"method" if function["type"] == "method" else "signal"
)
new_elt.setAttribute("name", section)
idx = 0
args_doc = self.getArgumentsDoc(section)
for arg in self.argumentsParser(function['sig_in'] or ''):
arg_elt = doc.createElement('arg')
arg_elt.setAttribute('name', args_doc[idx][0] if idx in args_doc else "arg_%i" % idx)
arg_elt.setAttribute('type', arg)
_direction = 'in' if function["type"] == 'method' else 'out'
arg_elt.setAttribute('direction', _direction)
for arg in self.argumentsParser(function["sig_in"] or ""):
arg_elt = doc.createElement("arg")
arg_elt.setAttribute(
"name", args_doc[idx][0] if idx in args_doc else "arg_%i" % idx
)
arg_elt.setAttribute("type", arg)
_direction = "in" if function["type"] == "method" else "out"
arg_elt.setAttribute("direction", _direction)
new_elt.appendChild(arg_elt)
if "annotation" in self.args.flags:
if arg in self.default_annotation:
annot_elt = doc.createElement("annotation")
annot_elt.setAttribute('name', "com.trolltech.QtDBus.QtTypeName.In%d" % idx)
annot_elt.setAttribute('value', self.default_annotation[arg])
annot_elt.setAttribute(
"name", "com.trolltech.QtDBus.QtTypeName.In%d" % idx
)
annot_elt.setAttribute("value", self.default_annotation[arg])
new_elt.appendChild(annot_elt)
idx += 1
if function['sig_out']:
arg_elt = doc.createElement('arg')
arg_elt.setAttribute('type', function['sig_out'])
arg_elt.setAttribute('direction', 'out')
if function["sig_out"]:
arg_elt = doc.createElement("arg")
arg_elt.setAttribute("type", function["sig_out"])
arg_elt.setAttribute("direction", "out")
new_elt.appendChild(arg_elt)
if "annotation" in self.args.flags:
if function['sig_out'] in self.default_annotation:
if function["sig_out"] in self.default_annotation:
annot_elt = doc.createElement("annotation")
annot_elt.setAttribute('name', "com.trolltech.QtDBus.QtTypeName.Out0")
annot_elt.setAttribute('value', self.default_annotation[function['sig_out']])
annot_elt.setAttribute(
"name", "com.trolltech.QtDBus.QtTypeName.Out0"
)
annot_elt.setAttribute(
"value", self.default_annotation[function["sig_out"]]
)
new_elt.appendChild(annot_elt)
interface_elt.appendChild(new_elt)
#now we write to final file
# now we write to final file
self.finalWrite(self.core_dest, [doc.toprettyxml()])

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
@ -25,73 +25,94 @@ class DbusConstructor(base_constructor.Constructor):
CORE_TEMPLATE = "dbus_core_template.py"
CORE_DEST = "dbus_bridge.py"
CORE_FORMATS = {
'signals': """\
"signals": """\
@dbus.service.signal(const_INT_PREFIX+const_{category}_SUFFIX,
signature='{sig_in}')
def {name}(self, {args}):
{body}\n""",
'methods': """\
"methods": """\
@dbus.service.method(const_INT_PREFIX+const_{category}_SUFFIX,
in_signature='{sig_in}', out_signature='{sig_out}',
async_callbacks={async_callbacks})
def {name}(self, {args}{async_comma}{async_args_def}):
{debug}return self._callback("{name}", {args_result}{async_comma}{async_args_call})\n""",
'signal_direct_calls': """\
"signal_direct_calls": """\
def {name}(self, {args}):
self.dbus_bridge.{name}({args})\n""",
}
}
FRONTEND_TEMPLATE = "dbus_frontend_template.py"
FRONTEND_DEST = CORE_DEST
FRONTEND_FORMATS = {
'methods': """\
"methods": """\
def {name}(self, {args}{async_comma}{async_args}):
{error_handler}{blocking_call}{debug}return {result}\n""",
}
{error_handler}{blocking_call}{debug}return {result}\n"""
}
def core_completion_signal(self, completion, function, default, arg_doc, async_):
completion['category'] = completion['category'].upper()
completion['body'] = "pass" if not self.args.debug else 'log.debug ("{}")'.format(completion['name'])
completion["category"] = completion["category"].upper()
completion["body"] = (
"pass"
if not self.args.debug
else 'log.debug ("{}")'.format(completion["name"])
)
def core_completion_method(self, completion, function, default, arg_doc, async_):
completion.update({
'debug': "" if not self.args.debug else 'log.debug ("%s")\n%s' % (completion['name'], 8 * ' '),
'args_result': self.getArguments(function['sig_in'], name=arg_doc, unicode_protect=self.args.unicode),
'async_comma': ', ' if async_ and function['sig_in'] else '',
'async_args_def': 'callback=None, errback=None' if async_ else '',
'async_args_call': 'callback=callback, errback=errback' if async_ else '',
'async_callbacks': "('callback', 'errback')" if async_ else "None",
'category': completion['category'].upper(),
})
completion.update(
{
"debug": ""
if not self.args.debug
else 'log.debug ("%s")\n%s' % (completion["name"], 8 * " "),
"args_result": self.getArguments(
function["sig_in"], name=arg_doc, unicode_protect=self.args.unicode
),
"async_comma": ", " if async_ and function["sig_in"] else "",
"async_args_def": "callback=None, errback=None" if async_ else "",
"async_args_call": "callback=callback, errback=errback" if async_ else "",
"async_callbacks": "('callback', 'errback')" if async_ else "None",
"category": completion["category"].upper(),
}
)
def frontend_completion_method(self, completion, function, default, arg_doc, async_):
completion.update({
# XXX: we can manage blocking call in the same way as async one: if callback is None the call will be blocking
'debug': "" if not self.args.debug else 'log.debug ("%s")\n%s' % (completion['name'], 8 * ' '),
'args_result': self.getArguments(function['sig_in'], name=arg_doc),
'async_args': 'callback=None, errback=None',
'async_comma': ', ' if function['sig_in'] else '',
'error_handler': """if callback is None:
completion.update(
{
# XXX: we can manage blocking call in the same way as async one: if callback is None the call will be blocking
"debug": ""
if not self.args.debug
else 'log.debug ("%s")\n%s' % (completion["name"], 8 * " "),
"args_result": self.getArguments(function["sig_in"], name=arg_doc),
"async_args": "callback=None, errback=None",
"async_comma": ", " if function["sig_in"] else "",
"error_handler": """if callback is None:
error_handler = None
else:
if errback is None:
errback = log.error
error_handler = lambda err:errback(dbus_to_bridge_exception(err))
""",
})
}
)
if async_:
completion['blocking_call'] = ''
completion['async_args_result'] = 'timeout=const_TIMEOUT, reply_handler=callback, error_handler=error_handler'
completion["blocking_call"] = ""
completion[
"async_args_result"
] = "timeout=const_TIMEOUT, reply_handler=callback, error_handler=error_handler"
else:
# XXX: To have a blocking call, we must have not reply_handler, so we test if callback exists, and add reply_handler only in this case
completion['blocking_call'] = """kwargs={}
completion[
"blocking_call"
] = """kwargs={}
if callback is not None:
kwargs['timeout'] = const_TIMEOUT
kwargs['reply_handler'] = callback
kwargs['error_handler'] = error_handler
"""
completion['async_args_result'] = '**kwargs'
result = "self.db_%(category)s_iface.%(name)s(%(args_result)s%(async_comma)s%(async_args_result)s)" % completion
completion['result'] = ("unicode(%s)" if self.args.unicode and function['sig_out'] == 's' else "%s") % result
completion["async_args_result"] = "**kwargs"
result = (
"self.db_%(category)s_iface.%(name)s(%(args_result)s%(async_comma)s%(async_args_result)s)"
% completion
)
completion["result"] = (
"unicode(%s)" if self.args.unicode and function["sig_out"] == "s" else "%s"
) % result

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# SAT: a jabber client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
@ -23,13 +23,14 @@ import dbus.service
import dbus.mainloop.glib
import inspect
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.internet.defer import Deferred
from sat.core.exceptions import BridgeInitError
const_INT_PREFIX = "org.goffi.SAT" # Interface prefix
const_ERROR_PREFIX = const_INT_PREFIX + ".error"
const_OBJ_PATH = '/org/goffi/SAT/bridge'
const_OBJ_PATH = "/org/goffi/SAT/bridge"
const_CORE_SUFFIX = ".core"
const_PLUGIN_SUFFIX = ".plugin"
@ -73,11 +74,12 @@ class GenericException(dbus.DBusException):
self.args = (message, twisted_error.value.condition)
except AttributeError:
self.args = (message,)
self._dbus_error_name = '.'.join([const_ERROR_PREFIX, class_.__module__, class_.__name__])
self._dbus_error_name = ".".join(
[const_ERROR_PREFIX, class_.__module__, class_.__name__]
)
class DbusObject(dbus.service.Object):
def __init__(self, bus, path):
dbus.service.Object.__init__(self, bus, path)
log.debug("Init DbusObject...")
@ -93,7 +95,7 @@ class DbusObject(dbus.service.Object):
raise MethodNotRegistered
if "callback" in kwargs:
#we must have errback too
# we must have errback too
if not "errback" in kwargs:
log.error("errback is missing in method call [%s]" % name)
raise InternalError
@ -107,27 +109,29 @@ class DbusObject(dbus.service.Object):
if not isinstance(result, Deferred):
log.error("Asynchronous method [%s] does not return a Deferred." % name)
raise AsyncNotDeferred
result.addCallback(lambda result: callback() if result is None else callback(result))
result.addCallback(
lambda result: callback() if result is None else callback(result)
)
result.addErrback(lambda err: errback(GenericException(err)))
else:
if isinstance(result, Deferred):
log.error("Synchronous method [%s] return a Deferred." % name)
raise DeferredNotAsync
return result
### signals ###
@dbus.service.signal(const_INT_PREFIX + const_PLUGIN_SUFFIX,
signature='')
@dbus.service.signal(const_INT_PREFIX + const_PLUGIN_SUFFIX, signature="")
def dummySignal(self):
#FIXME: workaround for addSignal (doesn't work if one method doensn't
# FIXME: workaround for addSignal (doesn't work if one method doensn't
# already exist for plugins), probably missing some initialisation, need
# further investigations
pass
##SIGNALS_PART##
##SIGNALS_PART##
### methods ###
##METHODS_PART##
##METHODS_PART##
def __attributes(self, in_sign):
"""Return arguments to user given a in_sign
@param in_sign: in_sign in the short form (using s,a,i,b etc)
@ -136,22 +140,24 @@ class DbusObject(dbus.service.Object):
idx = 0
attr = []
while i < len(in_sign):
if in_sign[i] not in ['b', 'y', 'n', 'i', 'x', 'q', 'u', 't', 'd', 's', 'a']:
if in_sign[i] not in ["b", "y", "n", "i", "x", "q", "u", "t", "d", "s", "a"]:
raise ParseError("Unmanaged attribute type [%c]" % in_sign[i])
attr.append("arg_%i" % idx)
idx += 1
if in_sign[i] == 'a':
if in_sign[i] == "a":
i += 1
if in_sign[i] != '{' and in_sign[i] != '(': # FIXME: must manage tuples out of arrays
if (
in_sign[i] != "{" and in_sign[i] != "("
): # FIXME: must manage tuples out of arrays
i += 1
continue # we have a simple type for the array
opening_car = in_sign[i]
assert(opening_car in ['{', '('])
closing_car = '}' if opening_car == '{' else ')'
assert opening_car in ["{", "("]
closing_car = "}" if opening_car == "{" else ")"
opening_count = 1
while (True): # we have a dict or a list of tuples
while True: # we have a dict or a list of tuples
i += 1
if i >= len(in_sign):
raise ParseError("missing }")
@ -172,47 +178,80 @@ class DbusObject(dbus.service.Object):
_defaults = list(inspect_args.defaults or [])
if inspect.ismethod(method):
#if we have a method, we don't want the first argument (usually 'self')
del(_arguments[0])
# if we have a method, we don't want the first argument (usually 'self')
del (_arguments[0])
#first arguments are for the _callback method
arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback', 'errback=errback']) if async else _arguments))
# first arguments are for the _callback method
arguments_callback = ", ".join(
[repr(name)]
+ (
(_arguments + ["callback=callback", "errback=errback"])
if async
else _arguments
)
)
if async:
_arguments.extend(['callback', 'errback'])
_arguments.extend(["callback", "errback"])
_defaults.extend([None, None])
#now we create a second list with default values
# now we create a second list with default values
for i in range(1, len(_defaults) + 1):
_arguments[-i] = "%s = %s" % (_arguments[-i], repr(_defaults[-i]))
arguments_defaults = ', '.join(_arguments)
arguments_defaults = ", ".join(_arguments)
code = compile('def %(name)s (self,%(arguments_defaults)s): return self._callback(%(arguments_callback)s)' %
{'name': name, 'arguments_defaults': arguments_defaults, 'arguments_callback': arguments_callback}, '<DBus bridge>', 'exec')
exec (code) # FIXME: to the same thing in a cleaner way, without compile/exec
code = compile(
"def %(name)s (self,%(arguments_defaults)s): return self._callback(%(arguments_callback)s)"
% {
"name": name,
"arguments_defaults": arguments_defaults,
"arguments_callback": arguments_callback,
},
"<DBus bridge>",
"exec",
)
exec(code) # FIXME: to the same thing in a cleaner way, without compile/exec
method = locals()[name]
async_callbacks = ('callback', 'errback') if async else None
setattr(DbusObject, name, dbus.service.method(
const_INT_PREFIX + int_suffix, in_signature=in_sign, out_signature=out_sign,
async_callbacks=async_callbacks)(method))
async_callbacks = ("callback", "errback") if async else None
setattr(
DbusObject,
name,
dbus.service.method(
const_INT_PREFIX + int_suffix,
in_signature=in_sign,
out_signature=out_sign,
async_callbacks=async_callbacks,
)(method),
)
function = getattr(self, name)
func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface]
func_table = self._dbus_class_table[
self.__class__.__module__ + "." + self.__class__.__name__
][function._dbus_interface]
func_table[function.__name__] = function # Needed for introspection
def addSignal(self, name, int_suffix, signature, doc={}):
"""Dynamically add a signal to Dbus Bridge"""
attributes = ', '.join(self.__attributes(signature))
#TODO: use doc parameter to name attributes
attributes = ", ".join(self.__attributes(signature))
# TODO: use doc parameter to name attributes
#code = compile ('def '+name+' (self,'+attributes+'): log.debug ("'+name+' signal")', '<DBus bridge>','exec') #XXX: the log.debug is too annoying with xmllog
code = compile('def ' + name + ' (self,' + attributes + '): pass', '<DBus bridge>', 'exec')
exec (code)
# code = compile ('def '+name+' (self,'+attributes+'): log.debug ("'+name+' signal")', '<DBus bridge>','exec') #XXX: the log.debug is too annoying with xmllog
code = compile(
"def " + name + " (self," + attributes + "): pass", "<DBus bridge>", "exec"
)
exec(code)
signal = locals()[name]
setattr(DbusObject, name, dbus.service.signal(
const_INT_PREFIX + int_suffix, signature=signature)(signal))
setattr(
DbusObject,
name,
dbus.service.signal(const_INT_PREFIX + int_suffix, signature=signature)(
signal
),
)
function = getattr(self, name)
func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface]
func_table = self._dbus_class_table[
self.__class__.__module__ + "." + self.__class__.__name__
][function._dbus_interface]
func_table[function.__name__] = function # Needed for introspection
@ -223,20 +262,24 @@ class Bridge(object):
try:
self.session_bus = dbus.SessionBus()
except dbus.DBusException as e:
if e._dbus_error_name == 'org.freedesktop.DBus.Error.NotSupported':
log.error(_(u"D-Bus is not launched, please see README to see instructions on how to launch it"))
if e._dbus_error_name == "org.freedesktop.DBus.Error.NotSupported":
log.error(
_(
u"D-Bus is not launched, please see README to see instructions on how to launch it"
)
)
raise BridgeInitError
self.dbus_name = dbus.service.BusName(const_INT_PREFIX, self.session_bus)
self.dbus_bridge = DbusObject(self.session_bus, const_OBJ_PATH)
##SIGNAL_DIRECT_CALLS_PART##
##SIGNAL_DIRECT_CALLS_PART##
def register_method(self, name, callback):
log.debug("registering DBus bridge method [%s]" % name)
self.dbus_bridge.register_method(name, callback)
def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False, doc={}):
"""Dynamically add a method to Dbus Bridge"""
#FIXME: doc parameter is kept only temporary, the time to remove it from calls
# FIXME: doc parameter is kept only temporary, the time to remove it from calls
log.debug("Adding method [%s] to DBus bridge" % name)
self.dbus_bridge.addMethod(name, int_suffix, in_sign, out_sign, method, async)
self.register_method(name, method)

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
@ -18,7 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.bridge.bridge_constructor import base_constructor
# from textwraps import dedent
#  from textwraps import dedent
class EmbeddedConstructor(base_constructor.Constructor):
@ -26,11 +27,11 @@ class EmbeddedConstructor(base_constructor.Constructor):
CORE_TEMPLATE = "embedded_template.py"
CORE_DEST = "embedded.py"
CORE_FORMATS = {
'methods': """\
"methods": """\
def {name}(self, {args}{args_comma}callback=None, errback=None):
{ret_routine}
""",
'signals': """\
"signals": """\
def {name}(self, {args}):
try:
cb = self._signals_cbs["{category}"]["{name}"]
@ -38,22 +39,30 @@ class EmbeddedConstructor(base_constructor.Constructor):
log.warning(u"ignoring signal {name}: no callback registered")
else:
cb({args_result})
"""
}
""",
}
FRONTEND_TEMPLATE = "embedded_frontend_template.py"
FRONTEND_DEST = CORE_DEST
FRONTEND_FORMATS = {}
def core_completion_method(self, completion, function, default, arg_doc, async_):
completion.update({
'debug': "" if not self.args.debug else 'log.debug ("%s")\n%s' % (completion['name'], 8 * ' '),
'args_result': self.getArguments(function['sig_in'], name=arg_doc),
'args_comma': ', ' if function['sig_in'] else '',
})
completion.update(
{
"debug": ""
if not self.args.debug
else 'log.debug ("%s")\n%s' % (completion["name"], 8 * " "),
"args_result": self.getArguments(function["sig_in"], name=arg_doc),
"args_comma": ", " if function["sig_in"] else "",
}
)
if async_:
completion["cb_or_lambda"] = "callback" if function['sig_out'] else "lambda dummy: callback()"
completion["ret_routine"] = """\
completion["cb_or_lambda"] = (
"callback" if function["sig_out"] else "lambda dummy: callback()"
)
completion[
"ret_routine"
] = """\
d = self._methods_cbs["{name}"]({args_result})
if callback is not None:
d.addCallback({cb_or_lambda})
@ -62,10 +71,14 @@ class EmbeddedConstructor(base_constructor.Constructor):
else:
d.addErrback(errback)
return d
""".format(**completion)
""".format(
**completion
)
else:
completion['ret_or_nothing'] = 'ret' if function['sig_out'] else ''
completion["ret_routine"] = """\
completion["ret_or_nothing"] = "ret" if function["sig_out"] else ""
completion[
"ret_routine"
] = """\
try:
ret = self._methods_cbs["{name}"]({args_result})
except Exception as e:
@ -77,9 +90,11 @@ class EmbeddedConstructor(base_constructor.Constructor):
if callback is None:
return ret
else:
callback({ret_or_nothing})""".format(**completion)
callback({ret_or_nothing})""".format(
**completion
)
def core_completion_signal(self, completion, function, default, arg_doc, async_):
completion.update({
'args_result': self.getArguments(function['sig_in'], name=arg_doc),
})
completion.update(
{"args_result": self.getArguments(function["sig_in"], name=arg_doc)}
)

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
@ -18,6 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.core import exceptions
@ -26,10 +27,7 @@ class _Bridge(object):
def __init__(self):
log.debug(u"Init embedded bridge...")
self._methods_cbs = {}
self._signals_cbs = {
"core": {},
"plugin": {}
}
self._signals_cbs = {"core": {}, "plugin": {}}
def bridgeConnect(self, callback, errback):
callback()
@ -43,7 +41,11 @@ class _Bridge(object):
def register_signal(self, functionName, handler, iface="core"):
iface_dict = self._signals_cbs[iface]
if functionName in iface_dict:
raise exceptions.ConflictError(u"signal {name} is already regitered for interface {iface}".format(name=functionName, iface=iface))
raise exceptions.ConflictError(
u"signal {name} is already regitered for interface {iface}".format(
name=functionName, iface=iface
)
)
iface_dict[functionName] = handler
def call_method(self, name, out_sign, async_, args, kwargs):
@ -84,23 +86,36 @@ class _Bridge(object):
cb(*args, **kwargs)
def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False, doc={}):
#FIXME: doc parameter is kept only temporary, the time to remove it from calls
# FIXME: doc parameter is kept only temporary, the time to remove it from calls
log.debug("Adding method [{}] to embedded bridge".format(name))
self.register_method(name, method)
setattr(self.__class__, name, lambda self_, *args, **kwargs: self.call_method(name, out_sign, async, args, kwargs))
setattr(
self.__class__,
name,
lambda self_, *args, **kwargs: self.call_method(
name, out_sign, async, args, kwargs
),
)
def addSignal(self, name, int_suffix, signature, doc={}):
setattr(self.__class__, name, lambda self_, *args, **kwargs: self.send_signal(name, args, kwargs))
setattr(
self.__class__,
name,
lambda self_, *args, **kwargs: self.send_signal(name, args, kwargs),
)
## signals ##
##SIGNALS_PART##
## methods ##
## methods ##
##METHODS_PART##
# we want the same instance for both core and frontend
bridge = None
def Bridge():
global bridge
if bridge is None:

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
@ -24,7 +24,6 @@ import re
class MediawikiConstructor(base_constructor.Constructor):
def __init__(self, bridge_template, options):
base_constructor.Constructor.__init__(self, bridge_template, options)
self.core_template = "mediawiki_template.tpl"
@ -35,10 +34,10 @@ class MediawikiConstructor(base_constructor.Constructor):
def anchor_link(match):
link = match.group(1)
#we add anchor_link for [method_name] syntax:
# we add anchor_link for [method_name] syntax:
if link in self.bridge_template.sections():
return "[[#%s|%s]]" % (link, link)
print ("WARNING: found an anchor link to an unknown method")
print("WARNING: found an anchor link to an unknown method")
return link
return re.sub(r"\[(\w+)\]", anchor_link, text)
@ -51,12 +50,12 @@ class MediawikiConstructor(base_constructor.Constructor):
arg_doc = self.getArgumentsDoc(name)
arg_default = self.getDefault(name)
args_str = self.getArguments(sig_in)
args = args_str.split(', ') if args_str else [] # ugly but it works :)
args = args_str.split(", ") if args_str else [] # ugly but it works :)
wiki = []
for i in range(len(args)):
if i in arg_doc:
name, doc = arg_doc[i]
doc = '\n:'.join(doc.rstrip('\n').split('\n'))
doc = "\n:".join(doc.rstrip("\n").split("\n"))
wiki.append("; %s: %s" % (name, self._addTextDecorations(doc)))
else:
wiki.append("; arg_%d: " % i)
@ -70,9 +69,13 @@ class MediawikiConstructor(base_constructor.Constructor):
"""
arg_doc = self.getArgumentsDoc(name)
wiki = []
if 'return' in arg_doc:
wiki.append('\n|-\n! scope=row | return value\n|')
wiki.append('<br />\n'.join(self._addTextDecorations(arg_doc['return']).rstrip('\n').split('\n')))
if "return" in arg_doc:
wiki.append("\n|-\n! scope=row | return value\n|")
wiki.append(
"<br />\n".join(
self._addTextDecorations(arg_doc["return"]).rstrip("\n").split("\n")
)
)
return "\n".join(wiki)
def generateCoreSide(self):
@ -82,37 +85,49 @@ class MediawikiConstructor(base_constructor.Constructor):
sections.sort()
for section in sections:
function = self.getValues(section)
print ("Adding %s %s" % (section, function["type"]))
print("Adding %s %s" % (section, function["type"]))
async_msg = """<br />'''This method is asynchronous'''"""
deprecated_msg = """<br />'''<font color="#FF0000">/!\ WARNING /!\ : This method is deprecated, please don't use it !</font>'''"""
signature_signal = \
"""\
signature_signal = (
"""\
! scope=row | signature
| %s
|-\
""" % function['sig_in']
signature_method = \
"""\
"""
% function["sig_in"]
)
signature_method = """\
! scope=row | signature in
| %s
|-
! scope=row | signature out
| %s
|-\
""" % (function['sig_in'], function['sig_out'])
""" % (
function["sig_in"],
function["sig_out"],
)
completion = {
'signature': signature_signal if function['type'] == "signal" else signature_method,
'sig_out': function['sig_out'] or '',
'category': function['category'],
'name': section,
'doc': self.getDoc(section) or "FIXME: No description available",
'async': async_msg if "async" in self.getFlags(section) else "",
'deprecated': deprecated_msg if "deprecated" in self.getFlags(section) else "",
'parameters': self._wikiParameter(section, function['sig_in']),
'return': self._wikiReturn(section) if function['type'] == 'method' else ''}
"signature": signature_signal
if function["type"] == "signal"
else signature_method,
"sig_out": function["sig_out"] or "",
"category": function["category"],
"name": section,
"doc": self.getDoc(section) or "FIXME: No description available",
"async": async_msg if "async" in self.getFlags(section) else "",
"deprecated": deprecated_msg
if "deprecated" in self.getFlags(section)
else "",
"parameters": self._wikiParameter(section, function["sig_in"]),
"return": self._wikiReturn(section)
if function["type"] == "method"
else "",
}
dest = signals_part if function['type'] == "signal" else methods_part
dest.append("""\
dest = signals_part if function["type"] == "signal" else methods_part
dest.append(
"""\
== %(name)s ==
''%(doc)s''
%(deprecated)s
@ -126,28 +141,28 @@ class MediawikiConstructor(base_constructor.Constructor):
|
%(parameters)s%(return)s
|}
""" % completion)
"""
% completion
)
#at this point, signals_part, and methods_part should be filled,
#we just have to place them in the right part of the template
# at this point, signals_part, and methods_part should be filled,
# we just have to place them in the right part of the template
core_bridge = []
template_path = self.getTemplatePath(self.core_template)
try:
with open(template_path) as core_template:
for line in core_template:
if line.startswith('##SIGNALS_PART##'):
if line.startswith("##SIGNALS_PART##"):
core_bridge.extend(signals_part)
elif line.startswith('##METHODS_PART##'):
elif line.startswith("##METHODS_PART##"):
core_bridge.extend(methods_part)
elif line.startswith('##TIMESTAMP##'):
core_bridge.append('Generated on %s' % datetime.now())
elif line.startswith("##TIMESTAMP##"):
core_bridge.append("Generated on %s" % datetime.now())
else:
core_bridge.append(line.replace('\n', ''))
core_bridge.append(line.replace("\n", ""))
except IOError:
print ("Can't open template file [%s]" % template_path)
print("Can't open template file [%s]" % template_path)
sys.exit(1)
#now we write to final file
# now we write to final file
self.finalWrite(self.core_dest, core_bridge)

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
@ -25,32 +25,42 @@ class pbConstructor(base_constructor.Constructor):
CORE_TEMPLATE = "pb_core_template.py"
CORE_DEST = "pb.py"
CORE_FORMATS = {
'signals': """\
"signals": """\
def {name}(self, {args}):
{debug}self.sendSignal("{name}", {args_no_def})\n""",
}
{debug}self.sendSignal("{name}", {args_no_def})\n"""
}
FRONTEND_TEMPLATE = "pb_frontend_template.py"
FRONTEND_DEST = CORE_DEST
FRONTEND_FORMATS = {
'methods': """\
"methods": """\
def {name}(self{args_comma}{args}, callback=None, errback=None):
{debug}d = self.root.callRemote("{name}"{args_comma}{args_no_def})
if callback is not None:
d.addCallback({callback})
if errback is None:
errback = self._generic_errback
d.addErrback(errback)\n""",
}
d.addErrback(errback)\n"""
}
def core_completion_signal(self, completion, function, default, arg_doc, async_):
completion['args_no_def'] = self.getArguments(function['sig_in'], name=arg_doc)
completion['debug'] = "" if not self.args.debug else 'log.debug ("%s")\n%s' % (completion['name'], 8 * ' ')
completion["args_no_def"] = self.getArguments(function["sig_in"], name=arg_doc)
completion["debug"] = (
""
if not self.args.debug
else 'log.debug ("%s")\n%s' % (completion["name"], 8 * " ")
)
def frontend_completion_method(self, completion, function, default, arg_doc, async_):
completion.update({
'args_comma': ', ' if function['sig_in'] else '',
'args_no_def': self.getArguments(function['sig_in'], name=arg_doc),
'callback': 'callback' if function['sig_out'] else 'lambda dummy: callback()',
'debug': "" if not self.args.debug else 'log.debug ("%s")\n%s' % (completion['name'], 8 * ' '),
})
completion.update(
{
"args_comma": ", " if function["sig_in"] else "",
"args_no_def": self.getArguments(function["sig_in"], name=arg_doc),
"callback": "callback"
if function["sig_out"]
else "lambda dummy: callback()",
"debug": ""
if not self.args.debug
else 'log.debug ("%s")\n%s' % (completion["name"], 8 * " "),
}
)

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# SAT: a jabber client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
@ -19,6 +19,7 @@
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.spread import jelly, pb
from twisted.internet import reactor
@ -28,17 +29,18 @@ from twisted.internet import reactor
# we monkey patch jelly to handle namedtuple
ori_jelly = jelly._Jellier.jelly
def fixed_jelly(self, obj):
"""this method fix handling of namedtuple"""
if isinstance(obj, tuple) and not obj is tuple:
obj = tuple(obj)
return ori_jelly(self, obj)
jelly._Jellier.jelly = fixed_jelly
class PBRoot(pb.Root):
def __init__(self):
self.signals_handlers = []
@ -47,10 +49,11 @@ class PBRoot(pb.Root):
log.info(u"registered signal handler")
def sendSignalEb(self, failure, signal_name):
log.error(u"Error while sending signal {name}: {msg}".format(
name = signal_name,
msg = failure,
))
log.error(
u"Error while sending signal {name}: {msg}".format(
name=signal_name, msg=failure
)
)
def sendSignal(self, name, args, kwargs):
to_remove = []
@ -66,11 +69,11 @@ class PBRoot(pb.Root):
log.debug(u"Removing signal handler for dead frontend")
self.signals_handlers.remove(handler)
##METHODS_PART##
class Bridge(object):
def __init__(self):
log.info("Init Perspective Broker...")
self.root = PBRoot()
@ -85,17 +88,20 @@ class Bridge(object):
def register_method(self, name, callback):
log.debug("registering PB bridge method [%s]" % name)
setattr(self.root, "remote_"+name, callback)
# self.root.register_method(name, callback)
setattr(self.root, "remote_" + name, callback)
#  self.root.register_method(name, callback)
def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False, doc={}):
"""Dynamically add a method to PB Bridge"""
#FIXME: doc parameter is kept only temporary, the time to remove it from calls
# FIXME: doc parameter is kept only temporary, the time to remove it from calls
log.debug("Adding method {name} to PB bridge".format(name=name))
self.register_method(name, method)
def addSignal(self, name, int_suffix, signature, doc={}):
log.debug("Adding signal {name} to PB bridge".format(name=name))
setattr(self, name, lambda *args, **kwargs: self.sendSignal(name, *args, **kwargs))
setattr(
self, name, lambda *args, **kwargs: self.sendSignal(name, *args, **kwargs)
)
##SIGNALS_PART##

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# SAT communication bridge
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
@ -18,6 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.core import exceptions
from twisted.spread import pb
@ -25,11 +26,9 @@ from twisted.internet import reactor
class SignalsHandler(pb.Referenceable):
def __getattr__(self, name):
if name.startswith("remote_"):
log.debug(u"calling an unregistered signal: {name}".format(
name = name[7:]))
log.debug(u"calling an unregistered signal: {name}".format(name=name[7:]))
return lambda *args, **kwargs: None
else:
@ -43,13 +42,15 @@ class SignalsHandler(pb.Referenceable):
except AttributeError:
pass
else:
raise exceptions.InternalError(u"{name} signal handler has been registered twice".format(
name = method_name))
raise exceptions.InternalError(
u"{name} signal handler has been registered twice".format(
name=method_name
)
)
setattr(self, method_name, handler)
class Bridge(object):
def __init__(self):
self.signals_handler = SignalsHandler()
@ -81,11 +82,11 @@ class Bridge(object):
callback = errback = None
if kwargs:
try:
callback = kwargs.pop('callback')
callback = kwargs.pop("callback")
except KeyError:
pass
try:
errback = kwargs.pop('errback')
errback = kwargs.pop("errback")
except KeyError:
pass
elif len(args) >= 2 and callable(args[-1]) and callable(args[-2]):
@ -124,4 +125,5 @@ class Bridge(object):
def register_signal(self, functionName, handler, iface="core"):
self.signals_handler.register_signal(functionName, handler, iface)
##METHODS_PART##