Exemplo n.º 1
0
    def __init__(self, el, externals, custom_lists):
        self.el = el
        name = get_by_path(el, '@name')
        array_name = get_by_path(el, '@array-name')
        array_depth = get_by_path(el, '@array-depth')
        if array_depth:
            array_depth = int(array_depth)
        else:
            array_depth = None
        self.binding = binding_from_decl(name, array_name, array_depth)
        self.deps = []

        for member in get_by_path(el, 'member'):
            sig = member.getAttribute('type')
            tptype = member.getAttributeNS(NS_TP, 'type')

            if (sig, tptype) in externals:
                continue

            if tptype.endswith('[]'):
                tptype = tptype[:-2]

            binding = binding_from_usage(sig, tptype, custom_lists)

            if binding.custom_type:
                self.deps.append(binding.val)

        self.revdeps = []
Exemplo n.º 2
0
    def __init__(self, el, externals, custom_lists):
        self.el = el
        name = get_by_path(el, '@name')
        array_name = get_by_path(el, '@array-name')
        array_depth = get_by_path(el, '@array-depth')
        if array_depth:
            array_depth = int(array_depth)
        else:
            array_depth = None
        self.binding = binding_from_decl(name, array_name, array_depth)
        self.deps = []

        for member in get_by_path(el, 'member'):
            sig = member.getAttribute('type')
            tptype = member.getAttributeNS(NS_TP, 'type')

            if (sig, tptype) in externals:
                continue

            if tptype.endswith('[]'):
                tptype = tptype[:-2]

            binding = binding_from_usage(sig, tptype, custom_lists)

            if binding.custom_type:
                self.deps.append(binding.val)

        self.revdeps = []
Exemplo n.º 3
0
    def do_signal(self, signal):
        name = signal.getAttribute('name')
        argnames, argdocstrings, argbindings = extract_arg_or_member_info(
            get_by_path(signal, 'arg'), self.custom_lists, self.externals,
            self.typesnamespace, '     *     ')

        self.h("""
    /**
     * Represents the signal "%s" on the remote object.
%s\
""" % (name, format_docstring(signal, '     * ')))

        for i in xrange(len(argnames)):
            assert argnames[
                i] != None, 'Name missing from argument at index %d for signal %s' % (
                    i, name)
            if argdocstrings[i]:
                self.h("""\
     *
     * \\param %s
%s\
""" % (argnames[i], argdocstrings[i]))

        self.h("""\
     */
    void %s(%s);
""" % (name, ', '.join([
            '%s %s' % (binding.inarg, name)
            for binding, name in zip(argbindings, argnames)
        ])))
Exemplo n.º 4
0
class Generator(object):
    def __init__(self, opts):
        try:
            self.namespace = opts['--namespace']
            self.declfile = opts['--declfile']
            self.implfile = opts['--implfile']
            self.realinclude = opts['--realinclude']
            self.prettyinclude = opts.get('--prettyinclude', self.realinclude)
            self.extraincludes = opts.get('--extraincludes', None)
            self.must_define = opts.get('--must-define', None)
            self.visibility = opts.get('--visibility', '')
            dom = xml.dom.minidom.parse(opts['--specxml'])
        except KeyError, k:
            assert False, 'Missing required parameter %s' % k.args[0]

        self.decls = []
        self.impls = []
        self.spec = get_by_path(dom, "spec")[0]
        self.externals = gather_externals(self.spec)
        self.custom_lists = gather_custom_lists(self.spec, self.namespace)
        self.required_custom = []
        self.required_arrays = []
        self.to_declare = []
        self.depinfos = {}
        self.refs = RefRegistry(self.spec)
Exemplo n.º 5
0
    def do_signal(self, signal):
        name = signal.getAttribute("name")
        argnames, argdocstrings, argbindings = extract_arg_or_member_info(
            get_by_path(signal, "arg"), self.custom_lists, self.externals, self.typesnamespace, "     *     "
        )

        self.h(
            """
    /**
     * Represents the signal "%s" on the remote object.
%s\
"""
            % (name, format_docstring(signal, "     * "))
        )

        for i in xrange(len(argnames)):
            assert argnames[i] != None, "Name missing from argument at index %d for signal %s" % (i, name)
            if argdocstrings[i]:
                self.h(
                    """\
     *
     * \\param %s
%s\
"""
                    % (argnames[i], argdocstrings[i])
                )

        self.h(
            """\
     */
    void %s(%s);
"""
            % (name, ", ".join(["%s %s" % (binding.inarg, name) for binding, name in zip(argbindings, argnames)]))
        )
Exemplo n.º 6
0
class Generator(object):
    def __init__(self, opts):
        try:
            self.group = opts.get('--group', '')
            self.headerfile = opts['--headerfile']
            self.implfile = opts['--implfile']
            self.namespace = opts['--namespace']
            self.typesnamespace = opts['--typesnamespace']
            self.realinclude = opts.get('--realinclude', None)
            self.mocinclude = opts.get('--mocinclude', None)
            self.prettyinclude = opts.get('--prettyinclude')
            self.extraincludes = opts.get('--extraincludes', None)
            self.must_define = opts.get('--must-define', None)
            self.visibility = opts.get('--visibility', '')
            ifacedom = xml.dom.minidom.parse(opts['--ifacexml'])
            specdom = xml.dom.minidom.parse(opts['--specxml'])
        except KeyError, k:
            assert False, 'Missing required parameter %s' % k.args[0]

        if not self.realinclude:
            self.realinclude = self.headerfile

        self.hs = []
        self.bs = []
        self.ifacenodes = ifacedom.getElementsByTagName('node')
        self.spec, = get_by_path(specdom, "spec")
        self.custom_lists = gather_custom_lists(self.spec, self.typesnamespace)
        self.externals = gather_externals(self.spec)
        self.refs = RefRegistry(self.spec)
Exemplo n.º 7
0
    def do_signal_disconnect(self, signal):
        name = signal.getAttribute('name')
        _, _, argbindings = extract_arg_or_member_info(get_by_path(signal, 'arg'), self.custom_lists, self.externals, self.typesnamespace, '     *     ')

        self.b("""\
    disconnect(this, SIGNAL(%s(%s)), NULL, NULL);
""" % (name, ', '.join([binding.inarg for binding in argbindings])))
Exemplo n.º 8
0
    def do_signal_disconnect(self, signal):
        name = signal.getAttribute('name')
        _, _, argbindings = extract_arg_or_member_info(
            get_by_path(signal, 'arg'), self.custom_lists, self.externals,
            self.typesnamespace, '     *     ')

        self.b("""\
    disconnect(this, SIGNAL(%s(%s)), NULL, NULL);
""" % (name, ', '.join([binding.inarg for binding in argbindings])))
Exemplo n.º 9
0
    def do_method_introspection(self, methods):
        for method in methods:
            name = method.getAttribute('name')
            args = get_by_path(method, 'arg')
            argnames, argdocstrings, argbindings = extract_arg_or_member_info(args,
                self.custom_lists, self.externals, self.typesnamespace, self.refs, '     *     ')

            if not argnames:
                self.h("""\
"    <method name=\\"%(name)s\\"/>\\n"
""" % {'name': name})
            else:
                self.h("""\
"    <method name=\\"%(name)s\\">\\n"
""" % {'name': name})

                outindex = 0
                inindex = 0
                for i in xrange(len(argnames)):
                    assert argnames[i] != None, 'Name missing from argument at index %d for signal %s' % (i, name)

                    argbinding = argbindings[i]
                    argname = argnames[i]
                    argsig = args[i].getAttribute('type')
                    argdirection = args[i].getAttribute('direction')

                    # QtDBus requires annotating a{sv}
                    if argsig == 'a{sv}':
                        argbinding.custom_type = True

                    if not argbinding.custom_type:
                        self.h("""\
"      <arg direction=\\"%(direction)s\\" type=\\"%(sig)s\\" name=\\"%(name)s\\"/>\\n"
""" % {'direction': argdirection,
       'sig': argsig,
       'name': argname})
                    else:
                        self.h("""\
"      <arg direction=\\"%(direction)s\\" type=\\"%(sig)s\\" name=\\"%(name)s\\">\\n"
"        <annotation value=\\"%(type)s\\" name=\\"com.trolltech.QtDBus.QtTypeName.%(index)s\\"/>\\n"
"      </arg>\\n"
""" % {'direction': argdirection,
       'sig': argsig,
       'name': argname,
       'type': argbinding.val,
       'index': 'In' + str(inindex) if argdirection == 'in' else 'Out' + str(outindex),
       })

                    if argdirection == 'out':
                        outindex += 1
                    else:
                        inindex += 1

                self.h("""\
"    </method>\\n"
""")
    def do_flags(self, flags):
        singular = flags.getAttribute('singular') or \
                   flags.getAttribute('value-prefix')

        using_name = False
        if not singular:
            using_name = True
            singular = flags.getAttribute('name')

        if singular.endswith('lags'):
            singular = singular[:-1]

        if using_name and singular.endswith('s'):
            singular = singular[:-1]

        singular = singular.replace('_', '')
        plural = (flags.getAttribute('plural') or flags.getAttribute('name')
                  or singular + 's').replace('_', '')
        self.h("""\
/**
 * \\ingroup flagtypeconsts
 *
 * Flag type generated from the specification.
 */
enum %(singular)s
{
""" % {'singular': singular})

        flagvalues = get_by_path(flags, 'flag')

        for flag in flagvalues:
            self.do_val(flag, singular, flag == flagvalues[-1])

        self.h("""\
    %s = 0xffffffffU
""" % ("_" + singular + "Padding"))

        self.h(
            """\
};

/**
 * \\typedef QFlags<%(singular)s> %(plural)s
 * \\ingroup flagtypeconsts
 *
 * Type representing combinations of #%(singular)s values.
%(docstring)s\
 */
typedef QFlags<%(singular)s> %(plural)s;
Q_DECLARE_OPERATORS_FOR_FLAGS(%(plural)s)

""" % {
                'singular': singular,
                'plural': plural,
                'docstring': format_docstring(flags)
            })
Exemplo n.º 11
0
    def do_method_introspection(self, methods):
        for method in methods:
            name = method.getAttribute('name')
            args = get_by_path(method, 'arg')
            argnames, argdocstrings, argbindings = extract_arg_or_member_info(args,
                self.custom_lists, self.externals, self.typesnamespace, self.refs, '     *     ')

            if not argnames:
                self.h("""\
"    <method name=\\"%(name)s\\"/>\\n"
""" % {'name': name})
            else:
                self.h("""\
"    <method name=\\"%(name)s\\">\\n"
""" % {'name': name})

                outindex = 0
                inindex = 0
                for i in range(len(argnames)):
                    assert argnames[i] != None, 'Name missing from argument at index %d for signal %s' % (i, name)

                    argbinding = argbindings[i]
                    argname = argnames[i]
                    argsig = args[i].getAttribute('type')
                    argdirection = args[i].getAttribute('direction')

                    # QtDBus requires annotating a{sv}
                    if argsig == 'a{sv}':
                        argbinding.custom_type = True

                    if not argbinding.custom_type:
                        self.h("""\
"      <arg direction=\\"%(direction)s\\" type=\\"%(sig)s\\" name=\\"%(name)s\\"/>\\n"
""" % {'direction': argdirection,
       'sig': argsig,
       'name': argname})
                    else:
                        self.h("""\
"      <arg direction=\\"%(direction)s\\" type=\\"%(sig)s\\" name=\\"%(name)s\\">\\n"
"        <annotation value=\\"%(type)s\\" name=\\"com.trolltech.QtDBus.QtTypeName.%(index)s\\"/>\\n"
"      </arg>\\n"
""" % {'direction': argdirection,
       'sig': argsig,
       'name': argname,
       'type': argbinding.val,
       'index': 'In' + str(inindex) if argdirection == 'in' else 'Out' + str(outindex),
       })

                    if argdirection == 'out':
                        outindex += 1
                    else:
                        inindex += 1

                self.h("""\
"    </method>\\n"
""")
    def do_enum(self, enum):
        singular = enum.getAttribute('singular') or \
                   enum.getAttribute('name')
        value_prefix = enum.getAttribute('singular') or \
                       enum.getAttribute('value-prefix') or \
                       enum.getAttribute('name')

        if singular.endswith('lags'):
            singular = singular[:-1]

        plural = enum.getAttribute('plural') or singular + 's'
        singular = singular.replace('_', '')
        value_prefix = value_prefix.replace('_', '')
        vals = get_by_path(enum, 'enumvalue')

        self.h("""\
/**
 * \\enum %(singular)s
 * \\ingroup enumtypeconsts
 *
 * Enumerated type generated from the specification.
%(docstring)s\
 */
enum %(singular)s
{
""" % {
            'singular': singular,
            'docstring': format_docstring(enum)
        })

        for val in vals:
            self.do_val(val, value_prefix, val == vals[-1])

        self.h("""\
    %s = 0xffffffffU
};

""" % ("_" + singular + "Padding"))

        self.h(
            """\
/**
 * \\ingroup enumtypeconsts
 *
 * 1 higher than the highest valid value of %(singular)s.
 */
const int NUM_%(upper-plural)s = (%(last-val)s+1);

""" % {
                'singular': singular,
                'upper-plural': plural.upper(),
                'last-val': vals[-1].getAttribute('value')
            })
Exemplo n.º 13
0
    def do_signals_connect(self, signals):
        for signal in signals:
            name = signal.getAttribute('name')
            adaptee_name = to_lower_camel_case(signal.getAttribute('tp:name-for-bindings'))
            _, _, argbindings = extract_arg_or_member_info(get_by_path(signal, 'arg'),
                    self.custom_lists, self.externals, self.typesnamespace, self.refs, '     *     ')

            self.b("""\
    connect(adaptee, SIGNAL(%(adaptee_name)s(%(params)s)), SIGNAL(%(name)s(%(params)s)));
""" % {'name': name,
       'adaptee_name': adaptee_name,
       'params': ', '.join([binding.inarg for binding in argbindings])
       })
Exemplo n.º 14
0
    def do_signals_connect(self, signals):
        for signal in signals:
            name = signal.getAttribute('name')
            adaptee_name = to_lower_camel_case(signal.getAttribute('tp:name-for-bindings'))
            _, _, argbindings = extract_arg_or_member_info(get_by_path(signal, 'arg'),
                    self.custom_lists, self.externals, self.typesnamespace, self.refs, '     *     ')

            self.b("""\
    connect(adaptee, SIGNAL(%(adaptee_name)s(%(params)s)), SIGNAL(%(name)s(%(params)s)));
""" % {'name': name,
       'adaptee_name': adaptee_name,
       'params': ', '.join([binding.inarg for binding in argbindings])
       })
    def do_flags(self, flags):
        singular = flags.getAttribute('singular') or \
                   flags.getAttribute('value-prefix')

        using_name = False
        if not singular:
            using_name = True
            singular = flags.getAttribute('name')

        if singular.endswith('lags'):
            singular = singular[:-1]

        if using_name and singular.endswith('s'):
            singular = singular[:-1]

        singular = singular.replace('_', '')
        plural = (flags.getAttribute('plural') or flags.getAttribute('name') or singular + 's').replace('_', '')
        self.h("""\
/**
 * \\ingroup flagtypeconsts
 *
 * Flag type generated from the specification.
 */
enum %(singular)s
{
""" % {'singular' : singular})

        flagvalues = get_by_path(flags, 'flag')

        for flag in flagvalues:
            self.do_val(flag, singular, flag == flagvalues[-1])

        self.h("""\
    %s = 0xffffffffU
""" % ("_" + singular + "Padding"))

        self.h("""\
};

/**
 * \\typedef QFlags<%(singular)s> %(plural)s
 * \\ingroup flagtypeconsts
 *
 * Type representing combinations of #%(singular)s values.
%(docstring)s\
 */
typedef QFlags<%(singular)s> %(plural)s;
Q_DECLARE_OPERATORS_FOR_FLAGS(%(plural)s)

""" % {'singular' : singular, 'plural' : plural, 'docstring' : format_docstring(flags, self.refs)})
Exemplo n.º 16
0
    def do_signal_introspection(self, signals):
        for signal in signals:
            name = signal.getAttribute('name')
            args = get_by_path(signal, 'arg')
            argnames, argdocstrings, argbindings = extract_arg_or_member_info(
                args, self.custom_lists, self.externals, self.typesnamespace,
                self.refs, '     *     ')

            if not argnames:
                self.h("""\
"    <signal name=\\"%(name)s\\"/>\\n"
""" % {'name': name})
            else:
                self.h("""\
"    <signal name=\\"%(name)s\\">\\n"
""" % {'name': name})

                for i in xrange(len(argnames)):
                    assert argnames[
                        i] != None, 'Name missing from argument at index %d for signal %s' % (
                            i, name)

                    argbinding = argbindings[i]
                    argname = argnames[i]
                    argsig = args[i].getAttribute('type')

                    if not argbinding.custom_type:
                        self.h("""\
"      <arg type=\\"%(sig)s\\" name=\\"%(name)s\\"/>\\n"
""" % {
                            'sig': argsig,
                            'name': argname
                        })
                    else:
                        self.h(
                            """\
"      <arg type=\\"%(sig)s\\" name=\\"%(name)s\\">\\n"
"        <annotation value=\\"%(type)s\\" name=\\"com.trolltech.QtDBus.QtTypeName.In%(index)d\\"/>\\n"
"      </arg>\\n"
""" % {
                                'sig': argsig,
                                'name': argname,
                                'type': argbinding.val,
                                'index': i,
                            })

                self.h("""\
"    </signal>\\n"
""")
Exemplo n.º 17
0
    def do_signal(self, signal):
        name = signal.getAttribute('name')
        adaptee_name = to_lower_camel_case(
            signal.getAttribute('tp:name-for-bindings'))
        argnames, argdocstrings, argbindings = extract_arg_or_member_info(
            get_by_path(signal, 'arg'), self.custom_lists, self.externals,
            self.typesnamespace, self.refs, '     *     ')
        params = ', '.join([
            '%s %s' % (binding.inarg, param_name)
            for binding, param_name in zip(argbindings, argnames)
        ])

        for i in xrange(len(argnames)):
            assert argnames[
                i] != None, 'Name missing from argument at index %d for signal %s' % (
                    i, name)

        self.h("""\
    /**
     * Represents the exported D-Bus signal \\c %(name)s on this object.
     *
     * Adaptees should export this signal as a Qt signal with the following signature:
     * void %(adaptee_name)s(%(params)s);
     *
     * The adaptee signal will be automatically relayed as a D-Bus signal once emitted.
     *
""" % {
            'name': name,
            'adaptee_name': adaptee_name,
            'params': params
        })

        for i in xrange(len(argnames)):
            assert argnames[
                i] != None, 'Name missing from argument at index %d for signal %s' % (
                    i, name)
            if argdocstrings[i]:
                self.h("""\
     * \\param %s
%s\
""" % (argnames[i], argdocstrings[i]))

        self.h("""\
     */
    void %(name)s(%(params)s);
""" % {
            'name': name,
            'params': params
        })
Exemplo n.º 18
0
    def __init__(self, spec):
        self.targets = {}
        for node in spec.getElementsByTagName('node'):
            iface, = get_by_path(node, 'interface')
            iface_name = iface.getAttribute('name')

            self.targets[iface_name] = RefTarget(node)

            for method in iface.getElementsByTagName(RefTarget.KIND_METHOD):
                self.targets[iface_name + '.' + method.getAttribute('name')] = RefTarget(method)

            for signal in iface.getElementsByTagName(RefTarget.KIND_SIGNAL):
                self.targets[iface_name + '.' + signal.getAttribute('name')] = RefTarget(signal)

            for prop in iface.getElementsByTagName(RefTarget.KIND_PROPERTY):
                self.targets[iface_name + '.' + prop.getAttribute('name')] = RefTarget(prop)
    def do_enum(self, enum):
        singular = enum.getAttribute('singular') or \
                   enum.getAttribute('name')
        value_prefix = enum.getAttribute('singular') or \
                       enum.getAttribute('value-prefix') or \
                       enum.getAttribute('name')

        if singular.endswith('lags'):
            singular = singular[:-1]

        plural = enum.getAttribute('plural') or singular + 's'
        singular = singular.replace('_', '')
        value_prefix = value_prefix.replace('_', '')
        vals = get_by_path(enum, 'enumvalue')

        self.h("""\
/**
 * \\enum %(singular)s
 * \\ingroup enumtypeconsts
 *
 * Enumerated type generated from the specification.
%(docstring)s\
 */
enum %(singular)s
{
""" % {'singular' : singular, 'docstring' : format_docstring(enum, self.refs)})

        for val in vals:
            self.do_val(val, value_prefix, val == vals[-1])

        self.h("""\
    %s = 0xffffffffU
};

""" % ("_" + singular + "Padding"))

        self.h("""\
/**
 * \\ingroup enumtypeconsts
 *
 * 1 higher than the highest valid value of %(singular)s.
 */
const int NUM_%(upper-plural)s = (%(last-val)s+1);

""" % {'singular' : singular,
       'upper-plural' : plural.upper(),
       'last-val' : vals[-1].getAttribute('value')})
    def __init__(self, opts):
        try:
            self.namespace = opts['--namespace']
            self.must_define = opts.get('--must-define', None)
            dom = xml.dom.minidom.parse(opts['--specxml'])
        except KeyError as k:
            assert False, 'Missing required parameter %s' % k.args[0]

        self.define_prefix = None
        if '--define-prefix' in opts:
            self.define_prefix = opts['--define-prefix']

        self.old_prefix = None
        if '--str-constant-prefix' in opts:
            self.old_prefix = opts['--str-constant-prefix']

        self.spec = get_by_path(dom, "spec")[0]
        self.out = codecs.getwriter('utf-8')(stdout)
Exemplo n.º 21
0
    def do_signal_introspection(self, signals):
        for signal in signals:
            name = signal.getAttribute('name')
            args = get_by_path(signal, 'arg')
            argnames, argdocstrings, argbindings = extract_arg_or_member_info(args,
                self.custom_lists, self.externals, self.typesnamespace, self.refs, '     *     ')

            if not argnames:
                self.h("""\
"    <signal name=\\"%(name)s\\"/>\\n"
""" % {'name': name})
            else:
                self.h("""\
"    <signal name=\\"%(name)s\\">\\n"
""" % {'name': name})

                for i in xrange(len(argnames)):
                    assert argnames[i] != None, 'Name missing from argument at index %d for signal %s' % (i, name)

                    argbinding = argbindings[i]
                    argname = argnames[i]
                    argsig = args[i].getAttribute('type')

                    if not argbinding.custom_type:
                        self.h("""\
"      <arg type=\\"%(sig)s\\" name=\\"%(name)s\\"/>\\n"
""" % {'sig': argsig,
       'name': argname})
                    else:
                        self.h("""\
"      <arg type=\\"%(sig)s\\" name=\\"%(name)s\\">\\n"
"        <annotation value=\\"%(type)s\\" name=\\"com.trolltech.QtDBus.QtTypeName.In%(index)d\\"/>\\n"
"      </arg>\\n"
""" % {'sig': argsig,
       'name': argname,
       'type': argbinding.val,
       'index': i,
       })

                self.h("""\
"    </signal>\\n"
""")
Exemplo n.º 22
0
    def do_mic_typedefs(self, methods):
        for method in methods:
            name = method.getAttribute('name')
            args = get_by_path(method, 'arg')
            argnames, argdocstrings, argbindings = extract_arg_or_member_info(args, self.custom_lists,
                    self.externals, self.typesnamespace, self.refs, '     *     ')

            outargs = []
            for i in range(len(args)):
                if args[i].getAttribute('direction') == 'out':
                    outargs.append(i)

            if outargs:
                outargtypes = ', '.join([argbindings[i].val for i in outargs])
            else:
                outargtypes = ''

            self.h("""\
    typedef Tp::MethodInvocationContextPtr< %(outargtypes)s > %(name)sContextPtr;
""" % {'name': name,
       'outargtypes': outargtypes,
       })
Exemplo n.º 23
0
    def do_mic_typedefs(self, methods):
        for method in methods:
            name = method.getAttribute('name')
            args = get_by_path(method, 'arg')
            argnames, argdocstrings, argbindings = extract_arg_or_member_info(args, self.custom_lists,
                    self.externals, self.typesnamespace, self.refs, '     *     ')

            outargs = []
            for i in xrange(len(args)):
                if args[i].getAttribute('direction') == 'out':
                    outargs.append(i)

            if outargs:
                outargtypes = ', '.join([argbindings[i].val for i in outargs])
            else:
                outargtypes = ''

            self.h("""\
    typedef Tp::MethodInvocationContextPtr< %(outargtypes)s > %(name)sContextPtr;
""" % {'name': name,
       'outargtypes': outargtypes,
       })
Exemplo n.º 24
0
    def do_signal(self, signal):
        name = signal.getAttribute('name')
        adaptee_name = to_lower_camel_case(signal.getAttribute('tp:name-for-bindings'))
        argnames, argdocstrings, argbindings = extract_arg_or_member_info(get_by_path(signal,
            'arg'), self.custom_lists, self.externals, self.typesnamespace, self.refs, '     *     ')
        params = ', '.join(['%s %s' % (binding.inarg, param_name) for binding, param_name in zip(argbindings, argnames)])

        for i in xrange(len(argnames)):
            assert argnames[i] != None, 'Name missing from argument at index %d for signal %s' % (i, name)

        self.h("""\
    /**
     * Represents the exported D-Bus signal \\c %(name)s on this object.
     *
     * Adaptees should export this signal as a Qt signal with the following signature:
     * void %(adaptee_name)s(%(params)s);
     *
     * The adaptee signal will be automatically relayed as a D-Bus signal once emitted.
     *
""" % {'name': name,
       'adaptee_name': adaptee_name,
       'params': params
       })

        for i in xrange(len(argnames)):
            assert argnames[i] != None, 'Name missing from argument at index %d for signal %s' % (i, name)
            if argdocstrings[i]:
                self.h("""\
     * \\param %s
%s\
""" % (argnames[i], argdocstrings[i]))

        self.h("""\
     */
    void %(name)s(%(params)s);
""" % {'name': name,
       'params': params
       })
Exemplo n.º 25
0
    def do_ifacenode(self, ifacenode):
        # Extract info
        name = ifacenode.getAttribute('name').replace('/', '').replace('_', '') + 'Adaptor'
        iface, = get_by_path(ifacenode, 'interface')
        dbusname = iface.getAttribute('name')
        props = get_by_path(iface, 'property')
        methods = get_by_path(iface, 'method')
        signals = get_by_path(iface, 'signal')

        # Begin class, constructors
        self.h("""
/**
 * \\class %(name)s
%(headercmd)s\
%(groupcmd)s\
 *
 * Adaptor class providing a 1:1 mapping of the D-Bus interface "%(dbusname)s".
 */
class %(visibility)s %(name)s : public Tp::AbstractAdaptor
{
    Q_OBJECT
    Q_CLASSINFO("D-Bus Interface", "%(dbusname)s")
    Q_CLASSINFO("D-Bus Introspection", ""
"  <interface name=\\"%(dbusname)s\\">\\n"
""" % {'name': name,
       'headercmd': get_headerfile_cmd(self.realinclude, self.prettyinclude),
       'groupcmd': self.group and (' * \\ingroup %s\n' % self.group),
       'dbusname': dbusname,
       'visibility': self.visibility,
       })

        self.do_introspection(props, methods, signals)

        self.h("""\
"  </interface>\\n"
"")
""")

        self.do_qprops(props)

        self.h("""
public:
    %(name)s(const QDBusConnection& dbusConnection, QObject* adaptee, QObject* parent);
    virtual ~%(name)s();

""" % {'name': name})

        self.do_mic_typedefs(methods)

        self.b("""
%(name)s::%(name)s(const QDBusConnection& bus, QObject* adaptee, QObject* parent)
    : Tp::AbstractAdaptor(bus, adaptee, parent)
{
""" % {'name': name})

        self.do_signals_connect(signals)

        self.b("""\
}

%(name)s::~%(name)s()
{
}
""" % {'name': name})

        # Properties
        has_props = False
        if props:
            self.h("""
public: // PROPERTIES
""")

            for prop in props:
                # Skip tp:properties
                if not prop.namespaceURI:
                    self.do_prop(name, prop)
                    has_props = True

        # Methods
        if methods:
            self.h("""
public Q_SLOTS: // METHODS
""")

            for method in methods:
                self.do_method(name, method)

        # Signals
        if signals:
            self.h("""
Q_SIGNALS: // SIGNALS
""")

            for signal in signals:
                self.do_signal(signal)

        # Close class
        self.h("""\
};
""")
Exemplo n.º 26
0
    def do_ifacenode(self, ifacenode):
        # Extract info
        name = ifacenode.getAttribute('name').replace('/', '').replace(
            '_', '') + 'Adaptor'
        iface, = get_by_path(ifacenode, 'interface')
        dbusname = iface.getAttribute('name')
        props = get_by_path(iface, 'property')
        methods = get_by_path(iface, 'method')
        signals = get_by_path(iface, 'signal')

        # Begin class, constructors
        self.h(
            """
/**
 * \\class %(name)s
%(headercmd)s\
%(groupcmd)s\
 *
 * Adaptor class providing a 1:1 mapping of the D-Bus interface "%(dbusname)s".
 */
class %(visibility)s %(name)s : public Tp::AbstractAdaptor
{
    Q_OBJECT
    Q_CLASSINFO("D-Bus Interface", "%(dbusname)s")
    Q_CLASSINFO("D-Bus Introspection", ""
"  <interface name=\\"%(dbusname)s\\">\\n"
""" % {
                'name':
                name,
                'headercmd':
                get_headerfile_cmd(self.realinclude, self.prettyinclude),
                'groupcmd':
                self.group and (' * \\ingroup %s\n' % self.group),
                'dbusname':
                dbusname,
                'visibility':
                self.visibility,
            })

        self.do_introspection(props, methods, signals)

        self.h("""\
"  </interface>\\n"
"")
""")

        self.do_qprops(props)

        self.h("""
public:
    %(name)s(const QDBusConnection& dbusConnection, QObject* adaptee, QObject* parent);
    virtual ~%(name)s();

""" % {'name': name})

        self.do_mic_typedefs(methods)

        self.b("""
%(name)s::%(name)s(const QDBusConnection& bus, QObject* adaptee, QObject* parent)
    : Tp::AbstractAdaptor(bus, adaptee, parent)
{
""" % {'name': name})

        self.do_signals_connect(signals)

        self.b("""\
}

%(name)s::~%(name)s()
{
}
""" % {'name': name})

        # Properties
        has_props = False
        if props:
            self.h("""
public: // PROPERTIES
""")

            for prop in props:
                # Skip tp:properties
                if not prop.namespaceURI:
                    self.do_prop(name, prop)
                    has_props = True

        # Methods
        if methods:
            self.h("""
public Q_SLOTS: // METHODS
""")

            for method in methods:
                self.do_method(name, method)

        # Signals
        if signals:
            self.h("""
Q_SIGNALS: // SIGNALS
""")

            for signal in signals:
                self.do_signal(signal)

        # Close class
        self.h("""\
};
""")
Exemplo n.º 27
0
    def provide_all(self):
        self.required_arrays.sort()
        for (val, array_of) in self.required_arrays:
            real = 'QList<%s>' % array_of
            self.decl("""\
/**
 * \\struct %s
 * \\ingroup list
%s\
 *
 * Generic list type with %s elements. Convertible with
 * %s, but needed to have a discrete type in the Qt type system.
 */
""" % (val, get_headerfile_cmd(self.realinclude, self.prettyinclude), array_of, real))
            self.decl(self.faketype(val, real))
            self.to_declare.append(self.namespace + '::' + val)

        structs = self.spec.getElementsByTagNameNS(NS_TP, 'struct')
        mappings = self.spec.getElementsByTagNameNS(NS_TP, 'mapping')
        exts = self.spec.getElementsByTagNameNS(NS_TP, 'external-type')

        for deptype in structs + mappings:
            info = DepInfo(deptype, self.externals, self.custom_lists)
            self.depinfos[info.binding.val] = info

        leaves = []
        next_leaves = []

        for val, depinfo in self.depinfos.iteritems():
            leaf = True

            for dep in depinfo.deps:
                if not self.depinfos.has_key(dep):
                    raise UnresolvedDependency(val, dep)

                leaf = False
                self.depinfos[dep].revdeps.append(val)

            if leaf:
                next_leaves.append(val)

        while leaves or next_leaves:
            if not leaves:
                leaves = next_leaves
                leaves.sort()
                next_leaves = []

            val = leaves.pop(0)
            depinfo = self.depinfos[val]
            self.output_by_depinfo(depinfo)

            for revdep in depinfo.revdeps:
                revdepinfo = self.depinfos[revdep]
                revdepinfo.deps.remove(val)

                if not revdepinfo.deps:
                    next_leaves.append(revdep)

            del self.depinfos[val]

        for provider in structs + mappings + exts:
            name = get_by_path(provider, '@name')
            array_name = get_by_path(provider, '@array-name')
            array_depth = get_by_path(provider, '@array-depth')
            if array_depth:
                array_depth = int(array_depth)
            else:
                array_depth = None
            sig = provider.getAttribute('type')
            tptype = provider.getAttribute('name')
            external = (sig, tptype) in self.externals
            binding = binding_from_decl(name, array_name, array_depth, external)
            self.provide(binding.val)

            if binding.array_val:
                self.provide(binding.array_val)

            d = binding.array_depth
            while d > 1:
                d -= 1
                self.provide(binding.array_val + ('List' * d))

        if self.required_custom:
            raise MissingTypes(self.required_custom)
Exemplo n.º 28
0
    def do_method(self, ifacename, method):
        name = method.getAttribute('name')
        adaptee_name = to_lower_camel_case(method.getAttribute('tp:name-for-bindings'))
        args = get_by_path(method, 'arg')
        argnames, argdocstrings, argbindings = extract_arg_or_member_info(args, self.custom_lists,
                self.externals, self.typesnamespace, self.refs, '     *     ')
        docstring = format_docstring(method, self.refs, '     * ').replace('*/', '&#42;&#47;')

        inargs = []
        outargs = []

        for i in xrange(len(args)):
            if args[i].getAttribute('direction') == 'out':
                outargs.append(i)
            else:
                inargs.append(i)
                assert argnames[i] != None, 'No argument name for input argument at index %d for method %s' % (i, name)

        if outargs:
            rettype = argbindings[outargs[0]].val
        else:
            rettype = 'void'

        params = [argbindings[i].inarg + ' ' + argnames[i] for i in inargs]
        params.append('const QDBusMessage& dbusMessage')
        params += [argbindings[i].outarg + ' ' + argnames[i] for i in outargs[1:]]
        params = ', '.join(params)

        if outargs:
            outargtypes = ', '.join([argbindings[i].val for i in outargs])
        else:
            outargtypes = ''
        invokemethodargs = ', '.join(['Q_ARG(' + argbindings[i].val + ', ' + argnames[i] + ')' for i in inargs])

        inparams = [argbindings[i].val for i in inargs]
        inparams.append("%s::%s::%sContextPtr" % (self.namespace, ifacename, name))
        normalized_adaptee_params = ','.join(inparams)

        adaptee_params = [argbindings[i].inarg + ' ' + argnames[i] for i in inargs]
        adaptee_params.append('const %(namespace)s::%(ifacename)s::%(name)sContextPtr &context' %
            {'namespace': self.namespace,
             'ifacename': ifacename,
             'name': name})
        adaptee_params = ', '.join(adaptee_params)

        self.h("""\
    /**
     * Begins a call to the exported D-Bus method \\c %(name)s on this object.
     *
     * Adaptees should export this method as a Qt slot with the following signature:
     * void %(adaptee_name)s(%(adaptee_params)s);
     *
     * Implementations should call MethodInvocationContext::setFinished (or setFinishedWithError
     * accordingly) on the received \\a context object once the method has finished processing.
     *
%(docstring)s\
     *
""" % {'name': name,
        'adaptee_name': adaptee_name,
        'adaptee_params': adaptee_params,
        'rettype': rettype,
        'docstring': docstring
        })

        for i in inargs:
            if argdocstrings[i]:
                self.h("""\
     * \\param %s
%s\
""" % (argnames[i], argdocstrings[i]))

        for i in outargs[1:]:
            if argdocstrings[i]:
                self.h("""\
     * \\param %s Output parameter
%s\
""" % (argnames[i], argdocstrings[i]))

        if outargs:
                self.h("""\
     * \\return
%s\
""" % argdocstrings[outargs[0]])

        self.h("""\
     */
    %(rettype)s %(name)s(%(params)s);
""" % {'rettype': rettype,
       'name': name,
       'params': params
       })

        self.b("""
%(rettype)s %(ifacename)s::%(name)s(%(params)s)
{
    if (!adaptee()->metaObject()->indexOfMethod("%(adaptee_name)s(%(normalized_adaptee_params)s)") == -1) {
        dbusConnection().send(dbusMessage.createErrorReply(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented")));
""" % {'rettype': rettype,
       'ifacename': ifacename,
       'name': name,
       'adaptee_name': adaptee_name,
       'normalized_adaptee_params': normalized_adaptee_params,
       'params': params,
       })

        if rettype != 'void':
            self.b("""\
        return %(rettype)s();
""" % {'rettype': rettype})
        else:
            self.b("""\
        return;
""")

        self.b("""\
    }

    %(name)sContextPtr ctx = %(name)sContextPtr(
            new Tp::MethodInvocationContext< %(outargtypes)s >(dbusConnection(), dbusMessage));
""" % {'name': name,
       'outargtypes': outargtypes,
       })

        if invokemethodargs:
            self.b("""\
    QMetaObject::invokeMethod(adaptee(), "%(adaptee_name)s",
        %(invokemethodargs)s,
        Q_ARG(%(namespace)s::%(ifacename)s::%(name)sContextPtr, ctx));
""" % {'namespace': self.namespace,
       'ifacename': ifacename,
       'name': name,
       'adaptee_name': adaptee_name,
       'invokemethodargs': invokemethodargs,
       })
        else:
            self.b("""\
    QMetaObject::invokeMethod(adaptee(), "%(lname)s",
        Q_ARG(%(namespace)s::%(ifacename)s::%(name)sContextPtr, ctx));
""" % {'namespace': self.namespace,
       'ifacename': ifacename,
       'name': name,
       'lname': (name[0].lower() + name[1:]),
       })

        if rettype != 'void':
            self.b("""\
    return %(rettype)s();
""" % {'rettype': rettype})

        self.b("}\n")
Exemplo n.º 29
0
    def do_method(self, method):
        name = method.getAttribute('name')
        args = get_by_path(method, 'arg')
        argnames, argdocstrings, argbindings = extract_arg_or_member_info(
            args, self.custom_lists, self.externals, self.typesnamespace,
            '     *     ')

        inargs = []
        outargs = []

        for i in xrange(len(args)):
            if args[i].getAttribute('direction') == 'out':
                outargs.append(i)
            else:
                inargs.append(i)
                assert argnames[
                    i] != None, 'No argument name for input argument at index %d for method %s' % (
                        i, name)

        rettypes = ', '.join([argbindings[i].val for i in outargs])
        params = ', '.join(
            [argbindings[i].inarg + ' ' + argnames[i] for i in inargs])
        if params:
            params += ', int timeout = -1'
        else:
            params = 'int timeout = -1'

        self.h("""
    /**
     * Begins a call to the D-Bus method "%s" on the remote object.
%s\
     *
     * Note that \\a timeout is ignored as of now. It will be used once
     * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed.
     *
""" % (name, format_docstring(method, '     * ')))

        for i in inargs:
            if argdocstrings[i]:
                self.h("""\
     *
     * \\param %s
%s\
""" % (argnames[i], argdocstrings[i]))

        self.h("""\
     * \\param timeout The timeout in milliseconds.
""")

        for i in outargs:
            if argdocstrings[i]:
                self.h("""\
     *
     * \\return
%s\
""" % argdocstrings[i])

        self.h("""\
     */
    inline QDBusPendingReply<%(rettypes)s> %(name)s(%(params)s)
    {
        if (!invalidationReason().isEmpty()) {
            return QDBusPendingReply<%(rettypes)s>(QDBusMessage::createError(
                invalidationReason(),
                invalidationMessage()
            ));
        }
""" % {
            'rettypes': rettypes,
            'name': name,
            'params': params
        })

        if inargs:
            self.h("""
        QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(),
                this->staticInterfaceName(), QLatin1String("%s"));
        callMessage << %s;
        return this->connection().asyncCall(callMessage, timeout);
    }
""" % (name, ' << '.join(
                ['QVariant::fromValue(%s)' % argnames[i] for i in inargs])))
        else:
            self.h("""
        QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(),
                this->staticInterfaceName(), QLatin1String("%s"));
        return this->connection().asyncCall(callMessage, timeout);
    }
""" % name)
Exemplo n.º 30
0
    def do_ifacenode(self, ifacenode):
        # Extract info
        name = ifacenode.getAttribute('name').replace('/', '').replace(
            '_', '') + 'Interface'
        iface, = get_by_path(ifacenode, 'interface')
        dbusname = iface.getAttribute('name')

        # Begin class, constructors
        self.h(
            """
/**
 * \\class %(name)s
%(headercmd)s\
%(groupcmd)s\
 *
 * Proxy class providing a 1:1 mapping of the D-Bus interface "%(dbusname)s."
 */
class %(visibility)s %(name)s : public Tp::AbstractInterface
{
    Q_OBJECT

public:
    /**
     * Returns the name of the interface "%(dbusname)s", which this class
     * represents.
     *
     * \\return The D-Bus interface name.
     */
    static inline QLatin1String staticInterfaceName()
    {
        return QLatin1String("%(dbusname)s");
    }

    /**
     * Creates a %(name)s associated with the given object on the session bus.
     *
     * \\param busName Name of the service the object is on.
     * \\param objectPath Path to the object on the service.
     * \\param parent Passed to the parent class constructor.
     */
    %(name)s(
        const QString& busName,
        const QString& objectPath,
        QObject* parent = 0
    );

    /**
     * Creates a %(name)s associated with the given object on the given bus.
     *
     * \\param connection The bus via which the object can be reached.
     * \\param busName Name of the service the object is on.
     * \\param objectPath Path to the object on the service.
     * \\param parent Passed to the parent class constructor.
     */
    %(name)s(
        const QDBusConnection& connection,
        const QString& busName,
        const QString& objectPath,
        QObject* parent = 0
    );
""" % {
                'name':
                name,
                'headercmd':
                get_headerfile_cmd(self.realinclude, self.prettyinclude),
                'groupcmd':
                self.group and (' * \\ingroup %s\n' % self.group),
                'dbusname':
                dbusname,
                'visibility':
                self.visibility,
            })

        self.b("""
%(name)s::%(name)s(const QString& busName, const QString& objectPath, QObject *parent)
    : Tp::AbstractInterface(busName, objectPath, staticInterfaceName(), QDBusConnection::sessionBus(), parent)
{
}

%(name)s::%(name)s(const QDBusConnection& connection, const QString& busName, const QString& objectPath, QObject *parent)
    : Tp::AbstractInterface(busName, objectPath, staticInterfaceName(), connection, parent)
{
}
""" % {'name': name})

        # Construct from DBusProxy subclass
        self.h("""
    /**
     * Creates a %(name)s associated with the same object as the given proxy.
     *
     * \\param proxy The proxy to use. It will also be the QObject::parent()
     *               for this object.
     */
    %(name)s(%(dbus_proxy)s *proxy);
""" % {
            'name': name,
            'dbus_proxy': self.dbus_proxy
        })

        self.b("""
%(name)s::%(name)s(%(dbus_proxy)s *proxy)
    : Tp::AbstractInterface(proxy, staticInterfaceName())
{
}
""" % {
            'name': name,
            'dbus_proxy': self.dbus_proxy
        })

        # Main interface
        mainiface = self.mainiface or 'Tp::AbstractInterface'

        if mainiface != self.namespace + '::' + name:
            self.h("""
    /**
     * Creates a %(name)s associated with the same object as the given proxy.
     * Additionally, the created proxy will have the same parent as the given
     * proxy.
     *
     * \\param mainInterface The proxy to use.
     */
    explicit %(name)s(const %(mainiface)s& mainInterface);

    /**
     * Creates a %(name)s associated with the same object as the given proxy.
     * However, a different parent object can be specified.
     *
     * \\param mainInterface The proxy to use.
     * \\param parent Passed to the parent class constructor.
     */
    %(name)s(const %(mainiface)s& mainInterface, QObject* parent);
""" % {
                'name': name,
                'mainiface': mainiface
            })

            self.b("""
%(name)s::%(name)s(const %(mainiface)s& mainInterface)
    : Tp::AbstractInterface(mainInterface.service(), mainInterface.path(), staticInterfaceName(), mainInterface.connection(), mainInterface.parent())
{
}

%(name)s::%(name)s(const %(mainiface)s& mainInterface, QObject *parent)
    : Tp::AbstractInterface(mainInterface.service(), mainInterface.path(), staticInterfaceName(), mainInterface.connection(), parent)
{
}
""" % {
                'name': name,
                'mainiface': mainiface
            })

        # Properties
        has_props = False
        for prop in get_by_path(iface, 'property'):
            # Skip tp:properties
            if not prop.namespaceURI:
                self.do_prop(prop)
                has_props = True

        self.h("""
    /**
     * Request all of the DBus properties on the interface.
     *
     * \\return A pending variant map which will emit finished when the properties have
     *          been retrieved.
     */
    Tp::PendingVariantMap *requestAllProperties() const
    {
        return internalRequestAllProperties();
    }
""")

        # Methods
        methods = get_by_path(iface, 'method')

        if methods:
            self.h("""
public Q_SLOTS:\
""")

            for method in methods:
                self.do_method(method)

        # Signals
        signals = get_by_path(iface, 'signal')

        if signals:
            self.h("""
Q_SIGNALS:\
""")

            for signal in signals:
                self.do_signal(signal)

        # invalidated handler (already a slot in the superclass)
        # we can't just use disconnect(this, NULL, NULL, NULL) because
        # (a) that would disconnect QObject::destroyed() and other non-D-Bus
        # signals, and (b) QtDBus doesn't support that usage anyway (it needs
        # specific signals in order to remove its signal match rules)
        self.h("""
protected:
    virtual void invalidate(Tp::DBusProxy *, const QString &, const QString &);
""")

        self.b("""
void %(name)s::invalidate(Tp::DBusProxy *proxy,
        const QString &error, const QString &message)
{
""" % {'name': name})

        for signal in signals:
            self.do_signal_disconnect(signal)

        self.b("""
    Tp::AbstractInterface::invalidate(proxy, error, message);
}
""")

        # Close class
        self.h("""\
};
""")
Exemplo n.º 31
0
    def provide_all(self):
        self.required_arrays.sort()
        for (val, array_of) in self.required_arrays:
            real = 'QList<%s>' % array_of
            self.decl("""\
/**
 * \\struct %s
 * \\ingroup list
%s\
 *
 * Generic list type with %s elements. Convertible with
 * %s, but needed to have a discrete type in the Qt type system.
 */
""" % (val, get_headerfile_cmd(self.realinclude, self.prettyinclude), array_of, real))
            self.decl(self.faketype(val, real))
            self.to_declare.append(self.namespace + '::' + val)

            self.both('%s QDBusArgument& operator<<(QDBusArgument& arg, const %s &list)' %
                    (self.visibility, val))
            self.decl(';\n')
            self.impl("""
{
    int id = qMetaTypeId<%s>();
    arg.beginArray(id);
    for (int i = 0; i < list.count(); ++i) {
        arg << list.at(i);
    }
    arg.endArray();
    return arg;
}

""" % (array_of))

            self.both('%s const QDBusArgument& operator>>(const QDBusArgument& arg, %s &list)' %
                    (self.visibility, val))
            self.decl(';\n\n')
            self.impl("""
{
    arg.beginArray();
    list.clear();
    while (!arg.atEnd()) {
        %s item;
        arg >> item;
        list.append(item);
    }
    arg.endArray();
    return arg;
}

""" % (array_of))

        structs = self.spec.getElementsByTagNameNS(NS_TP, 'struct')
        mappings = self.spec.getElementsByTagNameNS(NS_TP, 'mapping')
        exts = self.spec.getElementsByTagNameNS(NS_TP, 'external-type')

        for deptype in structs + mappings:
            info = DepInfo(deptype, self.externals, self.custom_lists)
            self.depinfos[info.binding.val] = info

        leaves = []
        next_leaves = []

        for val, depinfo in self.depinfos.iteritems():
            leaf = True

            for dep in depinfo.deps:
                if not self.depinfos.has_key(dep):
                    raise UnresolvedDependency(val, dep)

                leaf = False
                self.depinfos[dep].revdeps.append(val)

            if leaf:
                next_leaves.append(val)

        while leaves or next_leaves:
            if not leaves:
                leaves = next_leaves
                leaves.sort()
                next_leaves = []

            val = leaves.pop(0)
            depinfo = self.depinfos[val]
            self.output_by_depinfo(depinfo)

            for revdep in depinfo.revdeps:
                revdepinfo = self.depinfos[revdep]
                revdepinfo.deps.remove(val)

                if not revdepinfo.deps:
                    next_leaves.append(revdep)

            del self.depinfos[val]

        for provider in structs + mappings + exts:
            name = get_by_path(provider, '@name')
            array_name = get_by_path(provider, '@array-name')
            array_depth = get_by_path(provider, '@array-depth')
            if array_depth:
                array_depth = int(array_depth)
            else:
                array_depth = None
            sig = provider.getAttribute('type')
            tptype = provider.getAttribute('name')
            external = (sig, tptype) in self.externals
            binding = binding_from_decl(name, array_name, array_depth, external)
            self.provide(binding.val)

            if binding.array_val:
                self.provide(binding.array_val)

            d = binding.array_depth
            while d > 1:
                d -= 1
                self.provide(binding.array_val + ('List' * d))

        if self.required_custom:
            raise MissingTypes(self.required_custom)
Exemplo n.º 32
0
    def do_method(self, method):
        name = method.getAttribute('name')
        args = get_by_path(method, 'arg')
        argnames, argdocstrings, argbindings = extract_arg_or_member_info(args, self.custom_lists, self.externals, self.typesnamespace, '     *     ')

        inargs = []
        outargs = []

        for i in xrange(len(args)):
            if args[i].getAttribute('direction') == 'out':
                outargs.append(i)
            else:
                inargs.append(i)
                assert argnames[i] != None, 'No argument name for input argument at index %d for method %s' % (i, name)

        rettypes = ', '.join([argbindings[i].val for i in outargs])
        params = ', '.join([argbindings[i].inarg + ' ' + argnames[i] for i in inargs])
        if params:
            params += ', int timeout = -1'
        else:
            params = 'int timeout = -1'

        self.h("""
    /**
     * Begins a call to the D-Bus method "%s" on the remote object.
%s\
     *
     * Note that \\a timeout is ignored as of now. It will be used once
     * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed.
     *
""" % (name, format_docstring(method, '     * ')))

        for i in inargs:
            if argdocstrings[i]:
                self.h("""\
     *
     * \\param %s
%s\
""" % (argnames[i], argdocstrings[i]))

        self.h("""\
     * \\param timeout The timeout in milliseconds.
""")

        for i in outargs:
            if argdocstrings[i]:
                self.h("""\
     *
     * \\return
%s\
""" % argdocstrings[i])

        self.h("""\
     */
    inline QDBusPendingReply<%(rettypes)s> %(name)s(%(params)s)
    {
        if (!invalidationReason().isEmpty()) {
            return QDBusPendingReply<%(rettypes)s>(QDBusMessage::createError(
                invalidationReason(),
                invalidationMessage()
            ));
        }
""" % {'rettypes' : rettypes,
       'name' : name,
       'params' : params})

        if inargs:
            self.h("""
        QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(),
                this->staticInterfaceName(), QLatin1String("%s"));
        callMessage << %s;
        return this->connection().asyncCall(callMessage, timeout);
    }
""" % (name, ' << '.join(['QVariant::fromValue(%s)' % argnames[i] for i in inargs])))
        else:
            self.h("""
        QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(),
                this->staticInterfaceName(), QLatin1String("%s"));
        return this->connection().asyncCall(callMessage, timeout);
    }
""" % name)
Exemplo n.º 33
0
    def provide_all(self):
        self.required_arrays.sort()
        for (val, array_of) in self.required_arrays:
            init_list_type = array_of
            real = 'QList<%s>' % init_list_type
            self.decl("""\
/**
 * \\struct %s
 * \\ingroup list
%s\
 *
 * Generic list type with %s elements. Convertible with
 * %s, but needed to have a discrete type in the Qt type system.
 */
""" % (val, get_headerfile_cmd(self.realinclude, self.prettyinclude), array_of, real))
            self.decl(self.faketype(val, real, init_list_type))
            self.to_declare.append(self.namespace + '::' + val)

            self.both('%s QDBusArgument& operator<<(QDBusArgument& arg, const %s &list)' %
                    (self.visibility, val))
            self.decl(';\n')
            self.impl("""
{
    int id = qMetaTypeId<%s>();
    arg.beginArray(id);
    for (int i = 0; i < list.count(); ++i) {
        arg << list.at(i);
    }
    arg.endArray();
    return arg;
}

""" % (array_of))

            self.both('%s const QDBusArgument& operator>>(const QDBusArgument& arg, %s &list)' %
                    (self.visibility, val))
            self.decl(';\n\n')
            self.impl("""
{
    arg.beginArray();
    list.clear();
    while (!arg.atEnd()) {
        %s item;
        arg >> item;
        list.append(item);
    }
    arg.endArray();
    return arg;
}

""" % (array_of))

        structs = self.spec.getElementsByTagNameNS(NS_TP, 'struct')
        mappings = self.spec.getElementsByTagNameNS(NS_TP, 'mapping')
        exts = self.spec.getElementsByTagNameNS(NS_TP, 'external-type')

        for deptype in structs + mappings:
            info = DepInfo(deptype, self.externals, self.custom_lists)
            self.depinfos[info.binding.val] = info

        leaves = []
        next_leaves = []

        for val, depinfo in self.depinfos.iteritems():
            leaf = True

            for dep in depinfo.deps:
                if not self.depinfos.has_key(dep):
                    raise UnresolvedDependency(val, dep)

                leaf = False
                self.depinfos[dep].revdeps.append(val)

            if leaf:
                next_leaves.append(val)

        while leaves or next_leaves:
            if not leaves:
                leaves = next_leaves
                leaves.sort()
                next_leaves = []

            val = leaves.pop(0)
            depinfo = self.depinfos[val]
            self.output_by_depinfo(depinfo)

            for revdep in depinfo.revdeps:
                revdepinfo = self.depinfos[revdep]
                revdepinfo.deps.remove(val)

                if not revdepinfo.deps:
                    next_leaves.append(revdep)

            del self.depinfos[val]

        for provider in structs + mappings + exts:
            name = get_by_path(provider, '@name')
            array_name = get_by_path(provider, '@array-name')
            array_depth = get_by_path(provider, '@array-depth')
            if array_depth:
                array_depth = int(array_depth)
            else:
                array_depth = None
            sig = provider.getAttribute('type')
            tptype = provider.getAttribute('name')
            external = (sig, tptype) in self.externals
            binding = binding_from_decl(name, array_name, array_depth, external)
            self.provide(binding.val)

            if binding.array_val:
                self.provide(binding.array_val)

            d = binding.array_depth
            while d > 1:
                d -= 1
                self.provide(binding.array_val + ('List' * d))

        if self.required_custom:
            raise MissingTypes(self.required_custom)
    def __call__(self):
        # Header
        self.h('/* Generated from ')
        self.h(get_descendant_text(get_by_path(self.spec, 'title')))
        version = get_by_path(self.spec, "version")

        if version:
            self.h(', version ' + get_descendant_text(version))

        self.h("""
 */
 """)

        if self.must_define:
            self.h("""
#ifndef %s
#error %s
#endif
""" % (self.must_define, self.must_define))

        self.h("""
#include <QFlags>

/**
 * \\addtogroup typesconstants Types and constants
 *
 * Enumerated, flag, structure, list and mapping types and utility constants.
 */

/**
 * \\defgroup flagtypeconsts Flag type constants
 * \\ingroup typesconstants
 *
 * Types generated from the specification representing bit flag constants and
 * combinations of them (bitfields).
 */

/**
 * \\defgroup enumtypeconsts Enumerated type constants
 * \\ingroup typesconstants
 *
 * Types generated from the specification representing enumerated types ie.
 * types the values of which are mutually exclusive integral constants.
 */

/**
 * \\defgroup ifacestrconsts Interface string constants
 * \\ingroup typesconstants
 *
 * D-Bus interface names of the interfaces in the specification.
 */

/**
 * \\defgroup errorstrconsts Error string constants
 * \\ingroup typesconstants
 *
 * Names of the D-Bus errors in the specification.
 */
""")

        # Begin namespace
        self.h("""
namespace %s
{
""" % self.namespace)

        # Flags
        for flags in self.spec.getElementsByTagNameNS(NS_TP, 'flags'):
            self.do_flags(flags)

        # Enums
        for enum in self.spec.getElementsByTagNameNS(NS_TP, 'enum'):
            self.do_enum(enum)

        # End namespace
        self.h("""\
}

""")

        # Interface names
        for iface in self.spec.getElementsByTagName('interface'):
            if self.old_prefix:
                self.h(
                    """\
/**
 * \\ingroup ifacestrconsts
 *
 * The interface name "%(name)s".
 */
#define %(DEFINE)s "%(name)s"

""" % {
                        'name':
                        iface.getAttribute('name'),
                        'DEFINE':
                        self.old_prefix + 'INTERFACE_' + get_by_path(
                            iface, '../@name').upper().replace('/', '')
                    })

            if self.define_prefix:
                self.h(
                    """\
/**
 * \\ingroup ifacestrconsts
 *
 * The interface name "%(name)s" as a QLatin1String, usable in QString requiring contexts even when
 * building with Q_NO_CAST_FROM_ASCII defined.
 */
#define %(DEFINE)s QLatin1String("%(name)s")

""" % {
                        'name':
                        iface.getAttribute('name'),
                        'DEFINE':
                        self.define_prefix + 'IFACE_' + get_by_path(
                            iface, '../@name').upper().replace('/', '')
                    })

        # Error names
        for error in get_by_path(self.spec, 'errors/error'):
            name = error.getAttribute('name')
            fullname = get_by_path(
                error, '../@namespace') + '.' + name.replace(' ', '')

            if self.old_prefix:
                define = self.old_prefix + 'ERROR_' + name.replace(
                    ' ', '_').replace('.', '_').upper()
                self.h(
                    """\
/**
 * \\ingroup errorstrconsts
 *
 * The error name "%(fullname)s".
%(docstring)s\
 */
#define %(DEFINE)s "%(fullname)s"

""" % {
                        'fullname': fullname,
                        'docstring': format_docstring(error),
                        'DEFINE': define
                    })

            if self.define_prefix:
                define = self.define_prefix + 'ERROR_' + name.replace(
                    ' ', '_').replace('.', '_').upper()
                self.h(
                    """\
/**
 * \\ingroup errorstrconsts
 *
 * The error name "%(fullname)s" as a QLatin1String, usable in QString requiring contexts even when
 * building with Q_NO_CAST_FROM_ASCII defined.
%(docstring)s\
 */
#define %(DEFINE)s QLatin1String("%(fullname)s")

""" % {
                        'fullname': fullname,
                        'docstring': format_docstring(error),
                        'DEFINE': define
                    })
Exemplo n.º 35
0
    def do_method(self, ifacename, method):
        name = method.getAttribute('name')
        adaptee_name = to_lower_camel_case(
            method.getAttribute('tp:name-for-bindings'))
        args = get_by_path(method, 'arg')
        argnames, argdocstrings, argbindings = extract_arg_or_member_info(
            args, self.custom_lists, self.externals, self.typesnamespace,
            self.refs, '     *     ')
        docstring = format_docstring(method, self.refs,
                                     '     * ').replace('*/', '&#42;&#47;')

        inargs = []
        outargs = []

        for i in xrange(len(args)):
            if args[i].getAttribute('direction') == 'out':
                outargs.append(i)
            else:
                inargs.append(i)
                assert argnames[
                    i] != None, 'No argument name for input argument at index %d for method %s' % (
                        i, name)

        if outargs:
            rettype = argbindings[outargs[0]].val
        else:
            rettype = 'void'

        params = [argbindings[i].inarg + ' ' + argnames[i] for i in inargs]
        params.append('const QDBusMessage& dbusMessage')
        params += [
            argbindings[i].outarg + ' ' + argnames[i] for i in outargs[1:]
        ]
        params = ', '.join(params)

        if outargs:
            outargtypes = ', '.join([argbindings[i].val for i in outargs])
        else:
            outargtypes = ''
        invokemethodargs = ', '.join([
            'Q_ARG(' + argbindings[i].val + ', ' + argnames[i] + ')'
            for i in inargs
        ])

        inparams = [argbindings[i].val for i in inargs]
        inparams.append("%s::%s::%sContextPtr" %
                        (self.namespace, ifacename, name))
        normalized_adaptee_params = ','.join(inparams)

        adaptee_params = [
            argbindings[i].inarg + ' ' + argnames[i] for i in inargs
        ]
        adaptee_params.append(
            'const %(namespace)s::%(ifacename)s::%(name)sContextPtr &context' %
            {
                'namespace': self.namespace,
                'ifacename': ifacename,
                'name': name
            })
        adaptee_params = ', '.join(adaptee_params)

        self.h(
            """\
    /**
     * Begins a call to the exported D-Bus method \\c %(name)s on this object.
     *
     * Adaptees should export this method as a Qt slot with the following signature:
     * void %(adaptee_name)s(%(adaptee_params)s);
     *
     * Implementations should call MethodInvocationContext::setFinished (or setFinishedWithError
     * accordingly) on the received \\a context object once the method has finished processing.
     *
%(docstring)s\
     *
""" % {
                'name': name,
                'adaptee_name': adaptee_name,
                'adaptee_params': adaptee_params,
                'rettype': rettype,
                'docstring': docstring
            })

        for i in inargs:
            if argdocstrings[i]:
                self.h("""\
     * \\param %s
%s\
""" % (argnames[i], argdocstrings[i]))

        for i in outargs[1:]:
            if argdocstrings[i]:
                self.h("""\
     * \\param %s Output parameter
%s\
""" % (argnames[i], argdocstrings[i]))

        if outargs:
            self.h("""\
     * \\return
%s\
""" % argdocstrings[outargs[0]])

        self.h("""\
     */
    %(rettype)s %(name)s(%(params)s);
""" % {
            'rettype': rettype,
            'name': name,
            'params': params
        })

        self.b(
            """
%(rettype)s %(ifacename)s::%(name)s(%(params)s)
{
    if (!adaptee()->metaObject()->indexOfMethod("%(adaptee_name)s(%(normalized_adaptee_params)s)") == -1) {
        dbusConnection().send(dbusMessage.createErrorReply(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented")));
""" % {
                'rettype': rettype,
                'ifacename': ifacename,
                'name': name,
                'adaptee_name': adaptee_name,
                'normalized_adaptee_params': normalized_adaptee_params,
                'params': params,
            })

        if rettype != 'void':
            self.b("""\
        return %(rettype)s();
""" % {'rettype': rettype})
        else:
            self.b("""\
        return;
""")

        self.b("""\
    }

    %(name)sContextPtr ctx = %(name)sContextPtr(
            new Tp::MethodInvocationContext< %(outargtypes)s >(dbusConnection(), dbusMessage));
""" % {
            'name': name,
            'outargtypes': outargtypes,
        })

        if invokemethodargs:
            self.b(
                """\
    QMetaObject::invokeMethod(adaptee(), "%(adaptee_name)s",
        %(invokemethodargs)s,
        Q_ARG(%(namespace)s::%(ifacename)s::%(name)sContextPtr, ctx));
""" % {
                    'namespace': self.namespace,
                    'ifacename': ifacename,
                    'name': name,
                    'adaptee_name': adaptee_name,
                    'invokemethodargs': invokemethodargs,
                })
        else:
            self.b(
                """\
    QMetaObject::invokeMethod(adaptee(), "%(lname)s",
        Q_ARG(%(namespace)s::%(ifacename)s::%(name)sContextPtr, ctx));
""" % {
                    'namespace': self.namespace,
                    'ifacename': ifacename,
                    'name': name,
                    'lname': (name[0].lower() + name[1:]),
                })

        if rettype != 'void':
            self.b("""\
    return %(rettype)s();
""" % {'rettype': rettype})

        self.b("}\n")
Exemplo n.º 36
0
    def __call__(self):
        # Emit comment header

        self.both('/* Generated from ')
        self.both(get_descendant_text(get_by_path(self.spec, 'title')))
        version = get_by_path(self.spec, "version")

        if version:
            self.both(', version ' + get_descendant_text(version))

        self.both(' */\n')

        # Gather info on available and required types

        self.gather_required()

        if self.must_define:
            self.decl('\n')
            self.decl('#ifndef %s\n' % self.must_define)
            self.decl('#error %s\n' % self.must_define)
            self.decl('#endif')

        self.decl('\n')

        if self.extraincludes:
            for include in self.extraincludes.split(','):
                self.decl('#include %s\n' % include)

        self.decl("""
#include <QtGlobal>

#include <QByteArray>
#include <QString>
#include <QStringList>
#include <QVariantList>
#include <QVariantMap>

#include <QDBusArgument>
#include <QDBusMetaType>
#include <QDBusObjectPath>
#include <QDBusSignature>
#include <QDBusVariant>

#include <TelepathyQt/Global>

/**
 * \\addtogroup typesconstants Types and constants
 *
 * Enumerated, flag, structure, list and mapping types and utility constants.
 */

/**
 * \\defgroup struct Structure types
 * \\ingroup typesconstants
 *
 * Structure types generated from the specification.
 */

/**
 * \\defgroup list List types
 * \\ingroup typesconstants
 *
 * List types generated from the specification.
 */

/**
 * \\defgroup mapping Mapping types
 * \\ingroup typesconstants
 *
 * Mapping types generated from the specification.
 */

""")

        if self.must_define:
            self.impl("""
#define %s""" % self.must_define)

        self.impl("""
#include "%s"
""" % self.realinclude)

        self.both("""
namespace %s
{
""" % self.namespace)

        # Emit type definitions for types provided in the spec

        self.provide_all()

        # Emit type registration function

        self.decl("""
} // namespace %s

""" % self.namespace)

        self.impl("""\
TP_QT_NO_EXPORT void _registerTypes()
{
    static bool registered = false;
    if (registered)
        return;
    registered = true;

""")

        # Emit Qt metatype declarations

        self.to_declare.sort()

        for metatype in self.to_declare:
            self.decl('Q_DECLARE_METATYPE(%s)\n' % metatype)
            self.impl(
                '    qDBusRegisterMetaType<%s>();\n' %
                ((metatype.endswith('>') and metatype + ' ') or metatype))

        self.impl("""\
}

} // namespace %s
""" % self.namespace)

        # Write output to files

        open(self.declfile, 'w').write(''.join(self.decls).encode("utf-8"))
        open(self.implfile, 'w').write(''.join(self.impls).encode("utf-8"))
Exemplo n.º 37
0
    def __call__(self):
        # Emit comment header

        self.both('/* Generated from ')
        self.both(get_descendant_text(get_by_path(self.spec, 'title')))
        version = get_by_path(self.spec, "version")

        if version:
            self.both(', version ' + get_descendant_text(version))

        self.both(' */\n')

        # Gather info on available and required types

        self.gather_required()

        if self.must_define:
            self.decl('\n')
            self.decl('#ifndef %s\n' % self.must_define)
            self.decl('#error %s\n' % self.must_define)
            self.decl('#endif')

        self.decl('\n')

        if self.extraincludes:
            for include in self.extraincludes.split(','):
                self.decl('#include %s\n' % include)

        self.decl("""
#include <QtGlobal>

#include <QByteArray>
#include <QString>
#include <QStringList>
#include <QVariantList>
#include <QVariantMap>

#include <QDBusArgument>
#include <QDBusMetaType>
#include <QDBusObjectPath>
#include <QDBusSignature>
#include <QDBusVariant>

#include <TelepathyQt/Global>

/**
 * \\addtogroup typesconstants Types and constants
 *
 * Enumerated, flag, structure, list and mapping types and utility constants.
 */

/**
 * \\defgroup struct Structure types
 * \\ingroup typesconstants
 *
 * Structure types generated from the specification.
 */

/**
 * \\defgroup list List types
 * \\ingroup typesconstants
 *
 * List types generated from the specification.
 */

/**
 * \\defgroup mapping Mapping types
 * \\ingroup typesconstants
 *
 * Mapping types generated from the specification.
 */

""")

        if self.must_define:
            self.impl("""
#define %s""" % self.must_define)

        self.impl("""
#include "%s"
""" % self.realinclude)

        self.both("""
namespace %s
{
""" % self.namespace)

        # Emit type definitions for types provided in the spec

        self.provide_all()

        # Emit type registration function

        self.decl("""
} // namespace %s

""" % self.namespace)

        self.impl("""\
TP_QT_NO_EXPORT void _registerTypes()
{
    static bool registered = false;
    if (registered)
        return;
    registered = true;

""")

        # Emit Qt metatype declarations

        self.to_declare.sort()

        for metatype in self.to_declare:
            self.decl('Q_DECLARE_METATYPE(%s)\n' % metatype)
            self.impl('    qDBusRegisterMetaType<%s>();\n' % ((metatype.endswith('>') and metatype + ' ') or metatype))

        self.impl("""\
}

} // namespace %s
""" % self.namespace)

        # Write output to files

        open(self.declfile, 'w').write(''.join(self.decls).encode("utf-8"))
        open(self.implfile, 'w').write(''.join(self.impls).encode("utf-8"))
Exemplo n.º 38
0
    def provide_all(self):
        self.required_arrays.sort()
        for (val, array_of) in self.required_arrays:
            real = 'QList<%s>' % array_of
            self.decl("""\
/**
 * \\struct %s
 * \\ingroup list
%s\
 *
 * Generic list type with %s elements. Convertible with
 * %s, but needed to have a discrete type in the Qt type system.
 */
""" % (val, get_headerfile_cmd(self.realinclude,
                               self.prettyinclude), array_of, real))
            self.decl(self.faketype(val, real))
            self.to_declare.append(self.namespace + '::' + val)

        structs = self.spec.getElementsByTagNameNS(NS_TP, 'struct')
        mappings = self.spec.getElementsByTagNameNS(NS_TP, 'mapping')
        exts = self.spec.getElementsByTagNameNS(NS_TP, 'external-type')

        for deptype in structs + mappings:
            info = DepInfo(deptype, self.externals, self.custom_lists)
            self.depinfos[info.binding.val] = info

        leaves = []
        next_leaves = []

        for val, depinfo in self.depinfos.iteritems():
            leaf = True

            for dep in depinfo.deps:
                if not self.depinfos.has_key(dep):
                    raise UnresolvedDependency(val, dep)

                leaf = False
                self.depinfos[dep].revdeps.append(val)

            if leaf:
                next_leaves.append(val)

        while leaves or next_leaves:
            if not leaves:
                leaves = next_leaves
                leaves.sort()
                next_leaves = []

            val = leaves.pop(0)
            depinfo = self.depinfos[val]
            self.output_by_depinfo(depinfo)

            for revdep in depinfo.revdeps:
                revdepinfo = self.depinfos[revdep]
                revdepinfo.deps.remove(val)

                if not revdepinfo.deps:
                    next_leaves.append(revdep)

            del self.depinfos[val]

        for provider in structs + mappings + exts:
            name = get_by_path(provider, '@name')
            array_name = get_by_path(provider, '@array-name')
            array_depth = get_by_path(provider, '@array-depth')
            if array_depth:
                array_depth = int(array_depth)
            else:
                array_depth = None
            sig = provider.getAttribute('type')
            tptype = provider.getAttribute('name')
            external = (sig, tptype) in self.externals
            binding = binding_from_decl(name, array_name, array_depth,
                                        external)
            self.provide(binding.val)

            if binding.array_val:
                self.provide(binding.array_val)

            d = binding.array_depth
            while d > 1:
                d -= 1
                self.provide(binding.array_val + ('List' * d))

        if self.required_custom:
            raise MissingTypes(self.required_custom)
Exemplo n.º 39
0
    def output_by_depinfo(self, depinfo):
        names, docstrings, bindings = extract_arg_or_member_info(get_by_path(depinfo.el, 'member'), self.custom_lists, self.externals, None, self.refs, '     * ', ('    /**', '     */'))
        members = len(names)

        if depinfo.el.localName == 'struct':
            if members == 0:
                raise EmptyStruct(depinfo.binding.val)

            self.decl("""\
/**
 * \\struct %(name)s
 * \\ingroup struct
%(headercmd)s\
 *
 * Structure type generated from the specification.
%(docstring)s\
 */
struct %(visibility)s %(name)s
{
""" % {
        'name' : depinfo.binding.val,
        'headercmd': get_headerfile_cmd(self.realinclude, self.prettyinclude),
        'docstring' : format_docstring(depinfo.el, self.refs),
        'visibility': self.visibility,
        })

            for i in xrange(members):
                self.decl("""\
%s\
    %s %s;
""" % (docstrings[i], bindings[i].val, names[i]))

            self.decl("""\
};

""")

            self.both('%s bool operator==(%s v1, %s v2)' %
                    (self.visibility,
                     depinfo.binding.inarg,
                     depinfo.binding.inarg))
            self.decl(';\n')
            self.impl("""
{""")
            if (bindings[0].val != 'QDBusVariant'):
                self.impl("""
    return ((v1.%s == v2.%s)""" % (names[0], names[0]))
            else:
                self.impl("""
    return ((v1.%s.variant() == v2.%s.variant())""" % (names[0], names[0]))
            for i in xrange(1, members):
                if (bindings[i].val != 'QDBusVariant'):
                    self.impl("""
            && (v1.%s == v2.%s)""" % (names[i], names[i]))
                else:
                    self.impl("""
            && (v1.%s.variant() == v2.%s.variant())""" % (names[i], names[i]))
            self.impl("""
            );
}

""")

            self.decl('inline bool operator!=(%s v1, %s v2)' %
                      (depinfo.binding.inarg, depinfo.binding.inarg))
            self.decl("""
{
    return !operator==(v1, v2);
}
""")

            self.both('%s QDBusArgument& operator<<(QDBusArgument& arg, %s val)' %
                    (self.visibility, depinfo.binding.inarg))
            self.decl(';\n')
            self.impl("""
{
    arg.beginStructure();
    arg << %s;
    arg.endStructure();
    return arg;
}

""" % ' << '.join(['val.' + name for name in names]))

            self.both('%s const QDBusArgument& operator>>(const QDBusArgument& arg, %s val)' %
                    (self.visibility, depinfo.binding.outarg))
            self.decl(';\n\n')
            self.impl("""
{
    arg.beginStructure();
    arg >> %s;
    arg.endStructure();
    return arg;
}

""" % ' >> '.join(['val.' + name for name in names]))
        elif depinfo.el.localName == 'mapping':
            if members != 2:
                raise MalformedMapping(depinfo.binding.val, members)

            realtype = 'QMap<%s, %s>' % (bindings[0].val, (bindings[1].val.endswith('>') and bindings[1].val + ' ') or bindings[1].val)
            self.decl("""\
/**
 * \\struct %s
 * \\ingroup mapping
%s\
 *
 * Mapping type generated from the specification. Convertible with
 * %s, but needed to have a discrete type in the Qt type system.
%s\
 */
""" % (depinfo.binding.val, get_headerfile_cmd(self.realinclude, self.prettyinclude), realtype, format_docstring(depinfo.el, self.refs)))
            self.decl(self.faketype(depinfo.binding.val, realtype))
        else:
            raise WTF(depinfo.el.localName)

        self.to_declare.append(self.namespace + '::' + depinfo.binding.val)

        if depinfo.binding.array_val:
            self.to_declare.append('%s::%s' % (self.namespace, depinfo.binding.array_val))
            self.decl("""\
/**
 * \\ingroup list
%s\
 *
 * Array of %s values.
 */
typedef %s %s;

""" % (get_headerfile_cmd(self.realinclude, self.prettyinclude), depinfo.binding.val, 'QList<%s>' % depinfo.binding.val, depinfo.binding.array_val))

        i = depinfo.binding.array_depth
        while i > 1:
            i -= 1
            self.to_declare.append('%s::%s%s' % (self.namespace, depinfo.binding.array_val, ('List' * i)))
            list_of = depinfo.binding.array_val + ('List' * (i-1))
            self.decl("""\
/**
 * \\ingroup list
%s\
 *
 * Array of %s values.
 */
typedef QList<%s> %sList;

""" % (get_headerfile_cmd(self.realinclude, self.prettyinclude), list_of, list_of, list_of))
Exemplo n.º 40
0
    def output_by_depinfo(self, depinfo):
        names, docstrings, bindings = extract_arg_or_member_info(
            get_by_path(depinfo.el, 'member'), self.custom_lists,
            self.externals, None, self.refs, '     * ', ('    /**', '     */'))
        members = len(names)

        if depinfo.el.localName == 'struct':
            if members == 0:
                raise EmptyStruct(depinfo.binding.val)

            self.decl(
                """\
/**
 * \\struct %(name)s
 * \\ingroup struct
%(headercmd)s\
 *
 * Structure type generated from the specification.
%(docstring)s\
 */
struct %(visibility)s %(name)s
{
""" % {
                    'name':
                    depinfo.binding.val,
                    'headercmd':
                    get_headerfile_cmd(self.realinclude, self.prettyinclude),
                    'docstring':
                    format_docstring(depinfo.el, self.refs),
                    'visibility':
                    self.visibility,
                })

            for i in xrange(members):
                self.decl("""\
%s\
    %s %s;
""" % (docstrings[i], bindings[i].val, names[i]))

            self.decl("""\
};

""")

            self.both('%s bool operator==(%s v1, %s v2)' %
                      (self.visibility, depinfo.binding.inarg,
                       depinfo.binding.inarg))
            self.decl(';\n')
            self.impl("""
{""")
            if (bindings[0].val != 'QDBusVariant'):
                self.impl("""
    return ((v1.%s == v2.%s)""" % (names[0], names[0]))
            else:
                self.impl("""
    return ((v1.%s.variant() == v2.%s.variant())""" % (names[0], names[0]))
            for i in xrange(1, members):
                if (bindings[i].val != 'QDBusVariant'):
                    self.impl("""
            && (v1.%s == v2.%s)""" % (names[i], names[i]))
                else:
                    self.impl("""
            && (v1.%s.variant() == v2.%s.variant())""" % (names[i], names[i]))
            self.impl("""
            );
}

""")

            self.decl('inline bool operator!=(%s v1, %s v2)' %
                      (depinfo.binding.inarg, depinfo.binding.inarg))
            self.decl("""
{
    return !operator==(v1, v2);
}
""")

            self.both(
                '%s QDBusArgument& operator<<(QDBusArgument& arg, %s val)' %
                (self.visibility, depinfo.binding.inarg))
            self.decl(';\n')
            self.impl("""
{
    arg.beginStructure();
    arg << %s;
    arg.endStructure();
    return arg;
}

""" % ' << '.join(['val.' + name for name in names]))

            self.both(
                '%s const QDBusArgument& operator>>(const QDBusArgument& arg, %s val)'
                % (self.visibility, depinfo.binding.outarg))
            self.decl(';\n\n')
            self.impl("""
{
    arg.beginStructure();
    arg >> %s;
    arg.endStructure();
    return arg;
}

""" % ' >> '.join(['val.' + name for name in names]))
        elif depinfo.el.localName == 'mapping':
            if members != 2:
                raise MalformedMapping(depinfo.binding.val, members)

            realtype = 'QMap<%s, %s>' % (bindings[0].val,
                                         (bindings[1].val.endswith('>')
                                          and bindings[1].val + ' ')
                                         or bindings[1].val)
            self.decl("""\
/**
 * \\struct %s
 * \\ingroup mapping
%s\
 *
 * Mapping type generated from the specification. Convertible with
 * %s, but needed to have a discrete type in the Qt type system.
%s\
 */
""" % (depinfo.binding.val,
            get_headerfile_cmd(self.realinclude, self.prettyinclude), realtype,
            format_docstring(depinfo.el, self.refs)))
            self.decl(self.faketype(depinfo.binding.val, realtype))
        else:
            raise WTF(depinfo.el.localName)

        self.to_declare.append(self.namespace + '::' + depinfo.binding.val)

        if depinfo.binding.array_val:
            self.to_declare.append('%s::%s' %
                                   (self.namespace, depinfo.binding.array_val))
            self.decl("""\
/**
 * \\ingroup list
%s\
 *
 * Array of %s values.
 */
typedef %s %s;

""" % (get_headerfile_cmd(self.realinclude,
                          self.prettyinclude), depinfo.binding.val,
            'QList<%s>' % depinfo.binding.val, depinfo.binding.array_val))

        i = depinfo.binding.array_depth
        while i > 1:
            i -= 1
            self.to_declare.append('%s::%s%s' %
                                   (self.namespace, depinfo.binding.array_val,
                                    ('List' * i)))
            list_of = depinfo.binding.array_val + ('List' * (i - 1))
            self.decl("""\
/**
 * \\ingroup list
%s\
 *
 * Array of %s values.
 */
typedef QList<%s> %sList;

""" % (get_headerfile_cmd(self.realinclude,
                          self.prettyinclude), list_of, list_of, list_of))
Exemplo n.º 41
0
    def do_ifacenode(self, ifacenode):
        # Extract info
        name = ifacenode.getAttribute('name').replace('/', '').replace('_', '') + 'Interface'
        iface, = get_by_path(ifacenode, 'interface')
        dbusname = iface.getAttribute('name')

        # Begin class, constructors
        self.h("""
/**
 * \\class %(name)s
%(headercmd)s\
%(groupcmd)s\
 *
 * Proxy class providing a 1:1 mapping of the D-Bus interface "%(dbusname)s."
 */
class %(visibility)s %(name)s : public Tp::AbstractInterface
{
    Q_OBJECT

public:
    /**
     * Returns the name of the interface "%(dbusname)s", which this class
     * represents.
     *
     * \\return The D-Bus interface name.
     */
    static inline QLatin1String staticInterfaceName()
    {
        return QLatin1String("%(dbusname)s");
    }

    /**
     * Creates a %(name)s associated with the given object on the session bus.
     *
     * \\param busName Name of the service the object is on.
     * \\param objectPath Path to the object on the service.
     * \\param parent Passed to the parent class constructor.
     */
    %(name)s(
        const QString& busName,
        const QString& objectPath,
        QObject* parent = 0
    );

    /**
     * Creates a %(name)s associated with the given object on the given bus.
     *
     * \\param connection The bus via which the object can be reached.
     * \\param busName Name of the service the object is on.
     * \\param objectPath Path to the object on the service.
     * \\param parent Passed to the parent class constructor.
     */
    %(name)s(
        const QDBusConnection& connection,
        const QString& busName,
        const QString& objectPath,
        QObject* parent = 0
    );
""" % {'name' : name,
       'headercmd' : get_headerfile_cmd(self.realinclude, self.prettyinclude),
       'groupcmd' : self.group and (' * \\ingroup %s\n' % self.group),
       'dbusname' : dbusname,
       'visibility': self.visibility,
       })

        self.b("""
%(name)s::%(name)s(const QString& busName, const QString& objectPath, QObject *parent)
    : Tp::AbstractInterface(busName, objectPath, staticInterfaceName(), QDBusConnection::sessionBus(), parent)
{
}

%(name)s::%(name)s(const QDBusConnection& connection, const QString& busName, const QString& objectPath, QObject *parent)
    : Tp::AbstractInterface(busName, objectPath, staticInterfaceName(), connection, parent)
{
}
""" % {'name' : name})

        # Construct from DBusProxy subclass
        self.h("""
    /**
     * Creates a %(name)s associated with the same object as the given proxy.
     *
     * \\param proxy The proxy to use. It will also be the QObject::parent()
     *               for this object.
     */
    %(name)s(%(dbus_proxy)s *proxy);
""" % {'name' : name,
       'dbus_proxy' : self.dbus_proxy})

        self.b("""
%(name)s::%(name)s(%(dbus_proxy)s *proxy)
    : Tp::AbstractInterface(proxy, staticInterfaceName())
{
}
""" % {'name' : name,
       'dbus_proxy' : self.dbus_proxy})

        # Main interface
        mainiface = self.mainiface or 'Tp::AbstractInterface'

        if mainiface != self.namespace + '::' + name:
            self.h("""
    /**
     * Creates a %(name)s associated with the same object as the given proxy.
     * Additionally, the created proxy will have the same parent as the given
     * proxy.
     *
     * \\param mainInterface The proxy to use.
     */
    explicit %(name)s(const %(mainiface)s& mainInterface);

    /**
     * Creates a %(name)s associated with the same object as the given proxy.
     * However, a different parent object can be specified.
     *
     * \\param mainInterface The proxy to use.
     * \\param parent Passed to the parent class constructor.
     */
    %(name)s(const %(mainiface)s& mainInterface, QObject* parent);
""" % {'name' : name,
       'mainiface' : mainiface})

            self.b("""
%(name)s::%(name)s(const %(mainiface)s& mainInterface)
    : Tp::AbstractInterface(mainInterface.service(), mainInterface.path(), staticInterfaceName(), mainInterface.connection(), mainInterface.parent())
{
}

%(name)s::%(name)s(const %(mainiface)s& mainInterface, QObject *parent)
    : Tp::AbstractInterface(mainInterface.service(), mainInterface.path(), staticInterfaceName(), mainInterface.connection(), parent)
{
}
""" % {'name' : name,
       'mainiface' : mainiface})

        # Properties
        has_props = False
        for prop in get_by_path(iface, 'property'):
            # Skip tp:properties
            if not prop.namespaceURI:
                self.do_prop(prop)
                has_props = True

        self.h("""
    /**
     * Request all of the DBus properties on the interface.
     *
     * \\return A pending variant map which will emit finished when the properties have
     *          been retrieved.
     */
    Tp::PendingVariantMap *requestAllProperties() const
    {
        return internalRequestAllProperties();
    }
""")

        # Methods
        methods = get_by_path(iface, 'method')

        if methods:
            self.h("""
public Q_SLOTS:\
""")

            for method in methods:
                self.do_method(method)

        # Signals
        signals = get_by_path(iface, 'signal')

        if signals:
            self.h("""
Q_SIGNALS:\
""")

            for signal in signals:
                self.do_signal(signal)

        # invalidated handler (already a slot in the superclass)
        # we can't just use disconnect(this, NULL, NULL, NULL) because
        # (a) that would disconnect QObject::destroyed() and other non-D-Bus
        # signals, and (b) QtDBus doesn't support that usage anyway (it needs
        # specific signals in order to remove its signal match rules)
        self.h("""
protected:
    virtual void invalidate(Tp::DBusProxy *, const QString &, const QString &);
""")

        self.b("""
void %(name)s::invalidate(Tp::DBusProxy *proxy,
        const QString &error, const QString &message)
{
""" % {'name' : name})

        for signal in signals:
            self.do_signal_disconnect(signal)

        self.b("""
    Tp::AbstractInterface::invalidate(proxy, error, message);
}
""")

        # Close class
        self.h("""\
};
""")
Exemplo n.º 42
0
    def do_method(self, method):
        name = method.getAttribute("name")
        args = get_by_path(method, "arg")
        argnames, argdocstrings, argbindings = extract_arg_or_member_info(
            args, self.custom_lists, self.externals, self.typesnamespace, "     *     "
        )

        inargs = []
        outargs = []

        for i in xrange(len(args)):
            if args[i].getAttribute("direction") == "out":
                outargs.append(i)
            else:
                inargs.append(i)
                assert argnames[i] != None, "No argument name for input argument at index %d for method %s" % (i, name)

        rettypes = ", ".join([argbindings[i].val for i in outargs])
        params = ", ".join([argbindings[i].inarg + " " + argnames[i] for i in inargs])

        self.h(
            """
    /**
     * Begins a call to the D-Bus method "%s" on the remote object.
%s\
"""
            % (name, format_docstring(method, "     * "))
        )

        for i in inargs:
            if argdocstrings[i]:
                self.h(
                    """\
     *
     * \\param %s
%s\
"""
                    % (argnames[i], argdocstrings[i])
                )

        for i in outargs:
            if argdocstrings[i]:
                self.h(
                    """\
     *
     * \\return
%s\
"""
                    % argdocstrings[i]
                )

        self.h(
            """\
     */
    inline QDBusPendingReply<%(rettypes)s> %(name)s(%(params)s)
    {
        if (!invalidationReason().isEmpty()) {
            return QDBusPendingReply<%(rettypes)s>(QDBusMessage::createError(
                invalidationReason(),
                invalidationMessage()
            ));
        }

"""
            % {"rettypes": rettypes, "name": name, "params": params}
        )

        if inargs:
            self.h(
                """
        QList<QVariant> argumentList;
        argumentList << %s;
        return asyncCallWithArgumentList(QLatin1String("%s"), argumentList);
    }
"""
                % (" << ".join(["QVariant::fromValue(%s)" % argnames[i] for i in inargs]), name)
            )
        else:
            self.h(
                """
        return asyncCall(QLatin1String("%s"));
    }
"""
                % name
            )
Exemplo n.º 43
0
    def __call__(self):
        # Header
        self.h('/* Generated from ')
        self.h(get_descendant_text(get_by_path(self.spec, 'title')))
        version = get_by_path(self.spec, "version")

        if version:
            self.h(', version ' + get_descendant_text(version))

        self.h("""
 */
 """)

        if self.must_define:
            self.h("""
#ifndef %s
#error %s
#endif
""" % (self.must_define, self.must_define))

        self.h("""
#include <QFlags>

/**
 * \\addtogroup typesconstants Types and constants
 *
 * Enumerated, flag, structure, list and mapping types and utility constants.
 */

/**
 * \\defgroup flagtypeconsts Flag type constants
 * \\ingroup typesconstants
 *
 * Types generated from the specification representing bit flag constants and
 * combinations of them (bitfields).
 */

/**
 * \\defgroup enumtypeconsts Enumerated type constants
 * \\ingroup typesconstants
 *
 * Types generated from the specification representing enumerated types ie.
 * types the values of which are mutually exclusive integral constants.
 */

/**
 * \\defgroup ifacestrconsts Interface string constants
 * \\ingroup typesconstants
 *
 * D-Bus interface names of the interfaces in the specification.
 */

/**
 * \\defgroup errorstrconsts Error string constants
 * \\ingroup typesconstants
 *
 * Names of the D-Bus errors in the specification.
 */
""")

        # Begin namespace
        self.h("""
namespace %s
{
""" % self.namespace)

        # Flags
        for flags in self.spec.getElementsByTagNameNS(NS_TP, 'flags'):
            self.do_flags(flags)

        # Enums
        for enum in self.spec.getElementsByTagNameNS(NS_TP, 'enum'):
            self.do_enum(enum)

        # End namespace
        self.h("""\
}

""")

        # Interface names
        for iface in self.spec.getElementsByTagName('interface'):
            self.h("""\
/**
 * \\ingroup ifacestrconsts
 *
 * The interface name "%(name)s".
 */
#define %(DEFINE)s "%(name)s"

""" % {'name' : iface.getAttribute('name'),
       'DEFINE' : self.prefix + 'INTERFACE_' + get_by_path(iface, '../@name').upper().replace('/', '')})

        # Error names
        for error in get_by_path(self.spec, 'errors/error'):
            name = error.getAttribute('name')
            fullname = get_by_path(error, '../@namespace') + '.' + name.replace(' ', '')
            define = self.prefix + 'ERROR_' + name.replace(' ', '_').replace('.', '_').upper()
            self.h("""\
/**
 * \\ingroup errorstrconsts
 *
 * The error name "%(fullname)s".
%(docstring)s\
 */
#define %(DEFINE)s "%(fullname)s"

""" % {'fullname' : fullname,
       'docstring': format_docstring(error),
       'DEFINE' : define})
Exemplo n.º 44
0
    def do_method(self, method):
        name = method.getAttribute('name')
        args = get_by_path(method, 'arg')
        argnames, argdocstrings, argbindings = extract_arg_or_member_info(
            args, self.custom_lists, self.externals, self.typesnamespace,
            '     *     ')

        inargs = []
        outargs = []

        for i in xrange(len(args)):
            if args[i].getAttribute('direction') == 'out':
                outargs.append(i)
            else:
                inargs.append(i)
                assert argnames[
                    i] != None, 'No argument name for input argument at index %d for method %s' % (
                        i, name)

        rettypes = ', '.join([argbindings[i].val for i in outargs])
        params = ', '.join(
            [argbindings[i].inarg + ' ' + argnames[i] for i in inargs])

        self.h("""
    /**
     * Begins a call to the D-Bus method "%s" on the remote object.
%s\
""" % (name, format_docstring(method, '     * ')))

        for i in inargs:
            if argdocstrings[i]:
                self.h("""\
     *
     * \\param %s
%s\
""" % (argnames[i], argdocstrings[i]))

        for i in outargs:
            if argdocstrings[i]:
                self.h("""\
     *
     * \\return
%s\
""" % argdocstrings[i])

        self.h("""\
     */
    inline QDBusPendingReply<%(rettypes)s> %(name)s(%(params)s)
    {
        if (!invalidationReason().isEmpty()) {
            return QDBusPendingReply<%(rettypes)s>(QDBusMessage::createError(
                invalidationReason(),
                invalidationMessage()
            ));
        }

""" % {
            'rettypes': rettypes,
            'name': name,
            'params': params
        })

        if inargs:
            self.h("""
        QList<QVariant> argumentList;
        argumentList << %s;
        return asyncCallWithArgumentList(QLatin1String("%s"), argumentList);
    }
""" % (' << '.join(['QVariant::fromValue(%s)' % argnames[i]
                    for i in inargs]), name))
        else:
            self.h("""
        return asyncCall(QLatin1String("%s"));
    }
""" % name)