Add gdbus-codegen(1) command

It doesn't work yet without the user manually adding ffi bits. That's
the topic of the next commit.

Signed-off-by: David Zeuthen <davidz@redhat.com>
This commit is contained in:
David Zeuthen 2011-04-08 16:57:31 -04:00
parent ac93a6af88
commit 0b9229beca
15 changed files with 3884 additions and 3 deletions

View File

@ -3770,6 +3770,8 @@ gobject/tests/Makefile
gthread/Makefile
gthread/tests/Makefile
gio/Makefile
gio/gdbus-codegen/Makefile
gio/gdbus-codegen/config.py
gio/xdgmime/Makefile
gio/inotify/Makefile
gio/libasyncns/Makefile

View File

@ -149,6 +149,7 @@ content_files = \
glib-compile-schemas.xml\
gsettings.xml \
gdbus.xml \
gdbus-codegen.xml \
$(NULL)
expand_content_files = \
@ -170,8 +171,9 @@ EXTRA_DIST += \
man_MANS = \
gio-querymodules.1 \
glib-compile-schemas.1 \
gsettings.1 \
gdbus.1
gsettings.1 \
gdbus.1 \
gdbus-codegen.1
if ENABLE_MAN

View File

@ -0,0 +1,674 @@
<refentry id="gdbus-codegen" lang="en">
<refmeta>
<refentrytitle>gdbus-codegen</refentrytitle>
<manvolnum>1</manvolnum>
<refmiscinfo class="manual">User Commands</refmiscinfo>
</refmeta>
<refnamediv>
<refname>gdbus-codegen</refname>
<refpurpose>D-Bus Code Generator</refpurpose>
</refnamediv>
<refsynopsisdiv>
<cmdsynopsis>
<command>gdbus-codegen</command>
<arg><option>--interface-prefix</option> <replaceable>org.project.Prefix</replaceable></arg>
<arg><option>--c-namespace</option> <replaceable>YourProject</replaceable></arg>
<arg><option>--generate-c-code</option> <replaceable>OUTFILES</replaceable></arg>
<arg><option>--generate-docbook</option> <replaceable>OUTFILES</replaceable></arg>
<group choice="plain" rep="repeat">
<arg>
<option>--annotate</option>
<replaceable>element</replaceable>
<option>--key</option>
<replaceable>key</replaceable>
<option>--value</option>
<replaceable>key</replaceable>
</arg>
</group>
<arg choice="plain">FILE</arg>
<arg>
<arg choice="plain" rep="repeat">FILE</arg>
</arg>
</cmdsynopsis>
</refsynopsisdiv>
<refsect1>
<title>Description</title>
<para>
<command>gdbus-codegen</command> is used to generate code and/or
documentation for one or more D-Bus interfaces. The tool reads
D-Bus Introspection XML files and generates output files. The tool
currently supports generating C code (via
<option>--generate-c-code</option>) and Docbook XML (via
<option>--generate-docbook</option>).
</para>
<para>
When generating C code, an abstract
<type>GInterface</type>-derived type is generated for each D-Bus
interface. Additionally, for every generated type,
<type>FooBar</type>, two concrete instantiable types,
<type>FooBarProxy</type> and <type>FooBarStub</type>, implementing
said interface are also generated. The former is derived from
<type>GDBusProxy</type> and intended for use on the client side
while the latter is derived from the
<type>GDBusInterfaceStub</type> type making it easy to export on a
<type>GDBusConnection</type> either directly or via a
<type>GDBusObjectManagerServer</type>.
</para>
</refsect1>
<refsect1>
<title>Options</title>
<para>
The following options are supported:
</para>
<variablelist>
<varlistentry>
<term><option>--interface-prefix</option> <replaceable>org.project.Prefix.</replaceable></term>
<listitem>
<para>
A prefix to strip from all D-Bus interface names when
calculating the typename for the C binding and the Docbook
<ulink
url="http://www.docbook.org/tdg/en/html/primary.html">sortas
attribute</ulink>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>--generate-docbook</option> <replaceable>OUTFILES</replaceable></term>
<listitem>
<para>
Generate Docbook Documentation for each D-Bus interface and
put it in
<filename>OUTFILES-org.Project.IfaceName.xml</filename> (where
<literal>org.Project.IfaceName</literal> is a place-holder for
the interface name).
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>--generate-c-code</option> <replaceable>OUTFILES</replaceable></term>
<listitem>
<para>
Generate C code for all D-Bus interfaces and put it in
<filename>OUTFILES.c</filename> and
<filename>OUTFILES.h</filename>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>--c-namespace</option> <replaceable>YourProject</replaceable></term>
<listitem>
<para>
The namespace to use for generated C code. This must be
provided in CamelCase format.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>--annotate</option></term>
<listitem>
<para>
Used together with <option>--key</option> and
<option>--value</option> to annotate the given XML files. It
can be used with interfaces, methods, signals, properties
and arguments in the following way:
</para>
<informalexample><programlisting><![CDATA[
gdbus-codegen --c-namespace MyApp \
--generate-c-code myapp-generated \
--annotate "org.project.InterfaceName" \
--key org.gtk.GDBus.Name --value MyFrobnicator \
--annotate "org.project.InterfaceName:Property" \
--key bar --value bat \
--annotate "org.project.InterfaceName.Method()" \
--key org.freedesktop.DBus.Deprecated --value true \
--annotate "org.project.InterfaceName.Method()[arg_name]" \
--key snake --value hiss \
--annotate "org.project.InterfaceName::Signal" \
--key cat --value meow \
--annotate "org.project.InterfaceName::Signal[arg_name]" \
--key dog --value wuff \
myapp-dbus-interfaces.xml
]]></programlisting></informalexample>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1>
<title>Supported D-Bus Annotations</title>
<para>
The following D-Bus annotations are supported by
<command>gdbus-codegen</command>:
</para>
<variablelist>
<varlistentry>
<term><literal>org.gtk.GDBus.Name</literal></term>
<listitem>
<para>
Can be used on any <literal>&lt;interface&gt;</literal>,
<literal>&lt;method&gt;</literal>,
<literal>&lt;signal&gt;</literal> and
<literal>&lt;property&gt;</literal> element to specify the
name to use.
</para>
<para>
For interfaces where this annotation is not specified, the
name used is the D-Bus interface name stripped with the
prefix given with <option>--interface-prefix</option> and with
the dots removed and initial characters capitalized. For
example the D-Bus interface
<literal>com.acme.Coyote</literal> the name used is
<type>ComAcmeCoyote</type>. For the D-Bus interface
<literal>org.project.Bar.Frobnicator</literal> with
<option>--interface-prefix</option>
<literal>org.project.</literal>, the name used is
<type>BarFrobnicator</type>.
</para>
<para>
For methods, signals and properties the name used is
calculated by transforming
<literal>NameGivenThisWay</literal> into
<literal>name_given_this_way</literal>, e.g. roughly
converting from camel-case to lower-case with underscores
using certain heuristics.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>org.gtk.GDBus.C.ForceGVariant</literal></term>
<listitem>
<para>
If set to a non-empty string, a <type>GVariant</type> will
be used instead of the natural C type. This annotation can
be used on any <literal>&lt;arg&gt;</literal> and
<literal>&lt;property&gt;</literal> element.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>org.gtk.GDBus.DocString</literal></term>
<listitem>
<para>
A string with Docbook content for documentation. This annotation can
be used on <literal>&lt;interface&gt;</literal>,
<literal>&lt;method&gt;</literal>,
<literal>&lt;signal&gt;</literal>,
<literal>&lt;property&gt;</literal> and
<literal>&lt;arg&gt;</literal> elements.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>org.gtk.GDBus.DocString.Short</literal></term>
<listitem>
<para>
A string with Docbook content for short/brief
documentation. This annotation can only be used on
<literal>&lt;interface&gt;</literal> elements.
</para>
</listitem>
</varlistentry>
</variablelist>
<para>
As an easier alternative to using the
<literal>org.gtk.GDBus.DocString</literal> annotation, note that
XML parser used by <command>gdbus-codegen</command> parses XML
comments in a way similar to <ulink
url="http://www.gtk.org/gtk-doc/">gtk-doc</ulink>:
<informalexample><programlisting><![CDATA[
<!--
net.Corp.Bar:
@short_description: A short description
A <emphasis>longer</emphasis> description.
This is a new paragraph.
-->
<interface name="net.corp.Bar">
<!--
FooMethod:
@greeting: The docs for greeting parameter.
@response: The docs for response parameter.
The docs for the actual method.
-->
<method name="FooMethod">
<arg name="greeting" direction="in" type="s"/>
<arg name="response" direction="out" type="s"/>
</method>
<!--
BarSignal:
@blah: The docs for blah parameter.
@boo: The docs for boo parameter.
The docs for the actual signal.
-->
<signal name="BarSignal">
<arg name="blah" type="s"/>
<arg name="boo" type="s"/>
</signal>
<!-- BazProperty: The docs for the property. -->
<property name="BazProperty" type="s" access="read"/>
</interface>
]]></programlisting></informalexample>
</para>
<para>
For the <literal>org.gtk.GDBus.DocString</literal> annotation (and
inline comments), note that substrings of the form
<literal>#net.Corp.Bar</literal>,
<literal>net.Corp.Bar.FooMethod()</literal>,
<literal>#net.Corp.Bar::BarSignal</literal> and
<literal>#net.Corp.InlineDocs:BazProperty</literal> are all expanded
to links to the respective interface, method, signal and property.
</para>
</refsect1>
<refsect1>
<title>Example</title>
<para>
Consider the following D-Bus Introspection XML.
</para>
<informalexample><programlisting><![CDATA[
<interface name="net.Corp.MyApp.Frobber">
<method name="HelloWorld">
<arg name="greeting" direction="in" type="s"/>
<arg name="response" direction="out" type="s"/>
</method>
<signal name="Notification">
<arg name="icon_blob" type="ay"/>
<arg name="height" type="i"/>
<arg name="messages" type="as"/>
</signal>
<property name="Verbose" type="b" access="readwrite"/>
</interface>
]]></programlisting>
</informalexample>
<para>
If <command>gdbus-codegen</command> is used on this file like this:
</para>
<informalexample><programlisting><![CDATA[
gdbus-codegen --generate-c-code myapp-generated \
--c-namespace MyApp \
--interface-prefix net.corp.MyApp. \
net.Corp.MyApp.Frobber.xml
]]></programlisting></informalexample>
<para>
two files called
<filename>myapp-generated.[ch]</filename> are
generated. The files provide an abstract
<type>GInterface</type>-derived type called
<type>MyAppFrobber</type> as well as two instantiable types with
the same name but suffixed with <type>Proxy</type> and
<type>Stub</type>. The generated file, roughly, contains the
following facilities:
</para>
<informalexample><programlisting><![CDATA[
/* GType macros for the three generated types */
#define MY_APP_TYPE_FROBBER (my_app_frobber_get_type ())
#define MY_APP_TYPE_FROBBER_STUB (my_app_frobber_stub_get_type ())
#define MY_APP_TYPE_FROBBER_PROXY (my_app_frobber_proxy_get_type ())
typedef struct _MyAppFrobber MyAppFrobber; /* Dummy typedef */
typedef struct
{
GTypeInterface parent_iface;
/* Signal handler for the ::notification signal */
void (*notification) (MyAppFrobber *proxy,
GVariant *icon_blob,
gint height,
const gchar* const *messages);
/* Signal handler for the ::handle-hello-world signal */
gboolean (*handle_hello_world) (MyAppFrobber *proxy,
GDBusMethodInvocation *invocation,
const gchar *greeting);
} MyAppFrobberIface;
/* Asynchronously calls HelloWorld() */
void
my_app_frobber_call_hello_world (MyAppFrobber *proxy,
const gchar *greeting,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data);
gboolean
my_app_frobber_call_hello_world_finish (MyAppFrobber *proxy,
gchar **out_response,
GAsyncResult *res,
GError **error);
/* Synchronously calls HelloWorld(). Blocks calling thread. */
gboolean
my_app_frobber_call_hello_world_sync (MyAppFrobber *proxy,
const gchar *greeting,
gchar **out_response,
GCancellable *cancellable,
GError **error);
/* Completes handling the HelloWorld() method call */
void
my_app_frobber_complete_hello_world (MyAppFrobber *object,
GDBusMethodInvocation *invocation,
const gchar *response);
/* Emits the ::notification signal / Notification() D-Bus signal */
void
my_app_frobber_emit_notification (MyAppFrobber *object,
GVariant *icon_blob,
gint height,
const gchar* const *messages);
/* Gets the :verbose GObject property / Verbose D-Bus property.
* Does no blocking I/O.
*/
gboolean my_app_frobber_get_verbose (MyAppFrobber *object);
/* Sets the :verbose GObject property / Verbose D-Bus property.
* Does no blocking I/O.
*/
void my_app_frobber_set_verbose (MyAppFrobber *object,
gboolean value);
/* Gets the interface info */
GDBusInterfaceInfo *my_app_frobber_interface_info (void);
/* Creates a new stub object, ready to be exported */
MyAppFrobber *my_app_frobber_stub_new (void);
/* Client-side proxy constructors.
*
* Additionally, _new_for_bus(), _new_for_bus_finish() and
* _new_for_bus_sync() proxy constructors are also generated.
*/
void
my_app_frobber_proxy_new (GDBusConnection *connection,
GDBusProxyFlags flags,
const gchar *name,
const gchar *object_path,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data);
MyAppFrobber *
my_app_frobber_proxy_new_finish (GAsyncResult *res,
GError **error);
MyAppFrobber *
my_app_frobber_proxy_new_sync (GDBusConnection *connection,
GDBusProxyFlags flags,
const gchar *name,
const gchar *object_path,
GCancellable *cancellable,
GError **error);
]]></programlisting></informalexample>
<para>
Thus, for every D-Bus method, there will be three C functions for
calling the method, one <type>GObject</type> signal for handling
an incoming call and one C function for completing an incoming
call. For every D-Bus signal, there's one <type>GObject</type>
signal and one C function for emitting it. For every D-Bus
property, two C functions are generated (one setter, one getter)
and one <type>GObject</type> property. The following table
summarizes the generated facilities and where they are applicable:
</para>
<informaltable>
<tgroup cols="3">
<thead>
<row>
<entry></entry>
<entry>Client</entry>
<entry>Server</entry>
</row>
</thead>
<tbody>
<row>
<entry>Types</entry>
<entry>Use <type>MyAppFrobberProxy</type></entry>
<entry>Any type implementing the <type>MyAppFrobber</type> interface</entry>
</row>
<row>
<entry>Methods</entry>
<entry>Use <function>m_a_f_hello_world()</function> to call.</entry>
<entry>Receive via the <function>handle_hello_world()</function> signal handler. Complete the call with <function>m_a_f_complete_hello_world()</function></entry>
</row>
<row>
<entry>Signals</entry>
<entry>Connect to the <function>::notification</function> GObject signal.</entry>
<entry>Use <function>m_a_f_emit_notification()</function> to emit signal.</entry>
</row>
<row>
<entry>Properties (Reading)</entry>
<entry>Use <function>m_a_f_get_verbose()</function> or <parameter>:verbose</parameter>.</entry>
<entry>Implement <type>GObject</type>'s <function>get_property()</function> vfunc.</entry>
</row>
<row>
<entry>Properties (writing)</entry>
<entry>Use <function>m_a_f_set_verbose()</function> or <parameter>:verbose</parameter>.</entry>
<entry>Implement <type>GObject</type>'s <function>set_property()</function> vfunc.</entry>
</row>
</tbody>
</tgroup>
</informaltable>
<refsect2>
<title>Client-side usage</title>
<para>
You can use the generated proxy type with the generated
constructors:
</para>
<informalexample><programlisting><![CDATA[
MyAppFrobber *proxy;
GError *error;
error = NULL;
proxy = my_app_frobber_proxy_new_for_bus_sync (
G_BUS_TYPE_SESSION,
G_DBUS_PROXY_FLAGS_NONE,
"net.Corp.MyApp", /* bus name */
"/net/Corp/MyApp/SomeFrobber", /* object */
NULL, /* GCancellable* */
&error);
/* do stuff with proxy */
g_object_unref (proxy);
]]></programlisting></informalexample>
<para>
Instead of using the generic <type>GDBusProxy</type> facilities,
one can use the generated methods such as
<function>my_app_frobber_call_hello_world()</function> to invoke
the <function>net.Corp.MyApp.Frobber.HelloWorld()</function>
D-Bus method, connect to the the
<function>::notification</function> GObject signal to receive
the <function>net.Corp.MyApp.Frobber::Notication</function> D-Bus
signal and get/set the
<parameter>net.Corp.MyApp.Frobber:Verbose</parameter> D-Bus
Property using either the GObject property
<parameter>:verbose</parameter> or the
<function>my_app_get_verbose()</function> and
<function>my_app_set_verbose()</function> methods. Use the
standard <function>GObject::notify</function> signal to listen
to property changes.
</para>
<para>
Note that all property access is via <type>GDBusProxy</type>'s
property cache so no IO is ever done when reading properties.
Also note that setting a property will cause
<function>org.freedesktop.DBus.Properties.Set()</function> to be
called on the remote object. This call, however, is asynchronous
so setting a property won't block. Further, the change is
delayed and no error checking is possible.
</para>
</refsect2>
<refsect2>
<title>Server-side usage</title>
<para>
The generated <type>MyAppFrobber</type> interface is designed so
it is easy to implement it in a <type>GObject</type>
subclass. For example, to handle
<function>HelloWorld()</function> method invocations, set the
vfunc for <function>handle_hello_hello_world()</function> in the
<type>MyAppFrobberIface</type> structure. Similary, to handle
the <parameter>net.Corp.MyApp.Frobber:Verbose</parameter>
property override the <parameter>:verbose</parameter> GObject
property from the subclass. To emit a signal, use
e.g. <function>my_app_emit_signal()</function> or
<function>g_signal_emit_by_name()</function>.
</para>
<para>
Instead of subclassing, it is often easier to use the generated
<type>MyAppFrobberStub</type> subclass. To handle incoming
method calls, use <function>g_signal_connect()</function> with
the <function>::handle-*</function> signals and instead of
overriding <type>GObject</type>'s
<function>get_property()</function> and
<function>set_property()</function> vfuncs, use
<function>g_object_get()</function> and
<function>g_object_set()</function> or the generated property
getters and setters (the generated class has an internal
property bag implementation).
</para>
<informalexample><programlisting><![CDATA[
static gboolean
on_handle_hello_world (MyAppFrobber *object,
GDBusMethodInvocation *invocation,
const gchar *greeting,
gpointer user_data)
{
if (g_strcmp0 (greeting, "Boo") != 0)
{
gchar *response;
response = g_strdup_printf ("Word! You said `%s'.", greeting);
my_app_complete_hello_world (object, invocation, response);
g_free (response);
}
else
{
g_dbus_method_invocation_return_error (MY_APP_ERROR,
MY_APP_ERROR_NO_WHINING,
"Hey, %s, there will be no whining!",
g_dbus_method_invocation_get_sender (invocation));
}
return TRUE;
}
[...]
object = my_app_frobber_stub_new ();
my_app_frobber_set_verbose (object, TRUE);
g_signal_connect (object,
"handle-hello-world",
G_CALLBACK (on_handle_hello-world),
some_user_data);
[...]
error = NULL;
id = g_dbus_interface_register_object (G_DBUS_INTERFACE (object),
connection,
"/path/of/object",
&error);
]]></programlisting></informalexample>
<para>
To facility atomic changesets (multiple properties changing at
the same time), <function>GObject::notify</function> signals are
queued up when received. The queue is drained in an idle handler
and will cause emissions of the
<function>org.freedesktop.DBus.Properties::PropertiesChanged</function>
signal with all the properties that has changed. Use
<function>g_dbus_interface_stub_flush()</function> to empty the
queue immediately.
</para>
</refsect2>
</refsect1>
<refsect1>
<title>C Type Mapping</title>
<para>
Scalar types, strings (including object paths (type-string
<literal>o</literal>), signatures (type-string
<literal>g</literal>) and bytestrings (type-string
<literal>ay</literal>)) and arrays of string (type-string
<literal>as</literal>) and arrays of bytestrings (type-string
<literal>aay</literal>) are mapped to the natural types,
e.g. <type>gboolean</type>, <type>gdouble</type>,
<type>gint</type>, <type>gchar*</type>, <type>gchar **</type> and
so on. Everything else is mapped to the <type>GVariant</type>
type.
</para>
<para>
This automatic mapping can be turned off by using the annotation
<literal>org.gtk.GDBus.C.ForceGVariant</literal> - if used then a
<type>GVariant</type> is always exchanged instead of the
corresponding native C type. This annotation may be convenient to
use when using the type-string <literal>ay</literal> for data with
embedded NUL bytes.
</para>
</refsect1>
<refsect1>
<title>Stability Guarantees</title>
<para>
No guarantees about the API and ABI of the code generated by
<command>gdbus-codegen</command> are given. This means that code
generated by future versions of this program may have a different
API or ABI even if the underlying D-Bus interface hasn't
changed. As such, always include the generated code in
distribution tarballs and never expose the code in any stable
interfaces.
</para>
<para>
Future versions of <command>gdbus-codegen</command> will provide
ABI and API guarantees on the generated code.
</para>
</refsect1>
<refsect1>
<title>Author</title>
<para>
Written by David Zeuthen <email>zeuthen@gmail.com</email> with
a lot of help from many others.
</para>
</refsect1>
<refsect1>
<title>Bugs</title>
<para>
Please send bug reports to either the distribution bug tracker
or the upstream bug tracker at
<ulink url="https://bugzilla.gnome.org/enter_bug.cgi?product=glib"/>.
</para>
</refsect1>
<refsect1>
<title>See also</title>
<para>
<citerefentry>
<refentrytitle>gdbus</refentrytitle><manvolnum>1</manvolnum>
</citerefentry>
</para>
</refsect1>
</refentry>

View File

@ -205,6 +205,7 @@
<xi:include href="gsettings.xml"/>
<xi:include href="glib-compile-schemas.xml"/>
<xi:include href="gdbus.xml"/>
<xi:include href="gdbus-codegen.xml"/>
</chapter>
</part>

View File

@ -2,7 +2,7 @@ include $(top_srcdir)/Makefile.decl
NULL =
SUBDIRS=
SUBDIRS = gdbus-codegen
if OS_UNIX
SUBDIRS += libasyncns xdgmime

View File

@ -0,0 +1,27 @@
NULL =
bin_SCRIPTS =
EXTRA_DIST =
codegendir = $(libdir)/gdbus-codegen
codegen_PYTHON = \
__init__.py \
codegen.py \
codegen_main.py \
codegen_docbook.py \
config.py \
dbustypes.py \
parser.py \
utils.py \
$(NULL)
bin_SCRIPTS += gdbus-codegen
EXTRA_DIST += gdbus-codegen.in
gdbus-codegen: gdbus-codegen.in Makefile
$(AM_V_GEN) sed -e s,@libdir\@,$(libdir), -e s,@PYTHON\@,$(PYTHON), $< > $@.tmp && mv $@.tmp $@
@chmod a+x $@
clean-local:
rm -f *~

View File

@ -0,0 +1 @@

2104
gio/gdbus-codegen/codegen.py Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,283 @@
# -*- Mode: Python -*-
import sys
import argparse
import config
import utils
import dbustypes
import parser
# ----------------------------------------------------------------------------------------------------
class DocbookCodeGenerator:
def __init__(self, ifaces, docbook):
self.ifaces = ifaces
self.docbook = docbook
def print_method_prototype(self, i, m, in_synopsis):
max_method_len = 0
if in_synopsis:
for _m in i.methods:
max_method_len = max(len(_m.name), max_method_len)
else:
max_method_len = max(len(m.name), max_method_len)
max_signature_len = 0
if in_synopsis:
for _m in i.methods:
for a in _m.in_args:
max_signature_len = max(len(a.signature), max_signature_len)
for a in _m.out_args:
max_signature_len = max(len(a.signature), max_signature_len)
else:
for a in m.in_args:
max_signature_len = max(len(a.signature), max_signature_len)
for a in m.out_args:
max_signature_len = max(len(a.signature), max_signature_len)
if in_synopsis:
self.out.write('<link linkend="gdbus-method-%s.%s">%s</link>%*s ('
%(utils.dots_to_hyphens(i.name), m.name, m.name, max_method_len - len(m.name), ''))
else:
self.out.write('%s%*s ('
%(m.name, max_method_len - len(m.name), ''))
count = 0
for a in m.in_args:
if (count > 0):
self.out.write(',\n%*s'%(max_method_len + 2, ''))
self.out.write('IN %s%*s %s'%(a.signature, max_signature_len - len(a.signature), '', a.name))
count = count + 1
for a in m.out_args:
if (count > 0):
self.out.write(',\n%*s'%(max_method_len + 2, ''))
self.out.write('OUT %s%*s %s'%(a.signature, max_signature_len - len(a.signature), '', a.name))
count = count + 1
self.out.write(');\n')
def print_signal_prototype(self, i, s, in_synopsis):
max_signal_len = 0
if in_synopsis:
for _s in i.signals:
max_signal_len = max(len(_s.name), max_signal_len)
else:
max_signal_len = max(len(s.name), max_signal_len)
max_signature_len = 0
if in_synopsis:
for _s in i.signals:
for a in _s.args:
max_signature_len = max(len(a.signature), max_signature_len)
else:
for a in s.args:
max_signature_len = max(len(a.signature), max_signature_len)
if in_synopsis:
self.out.write('<link linkend="gdbus-signal-%s.%s">%s</link>%*s ('
%(utils.dots_to_hyphens(i.name), s.name, s.name, max_signal_len - len(s.name), ''))
else:
self.out.write('%s%*s ('
%(s.name, max_signal_len - len(s.name), ''))
count = 0
for a in s.args:
if (count > 0):
self.out.write(',\n%*s'%(max_signal_len + 2, ''))
self.out.write('%s%*s %s'%(a.signature, max_signature_len - len(a.signature), '', a.name))
count = count + 1
self.out.write(');\n')
def print_property_prototype(self, i, p, in_synopsis):
max_property_len = 0
if in_synopsis:
for _p in i.properties:
max_property_len = max(len(_p.name), max_property_len)
else:
max_property_len = max(len(p.name), max_property_len)
max_signature_len = 0
if in_synopsis:
for _p in i.properties:
max_signature_len = max(len(_p.signature), max_signature_len)
else:
max_signature_len = max(len(p.signature), max_signature_len)
if in_synopsis:
self.out.write('<link linkend="gdbus-property-%s.%s">%s</link>%*s'
%(utils.dots_to_hyphens(i.name), p.name, p.name, max_property_len - len(p.name), ''))
else:
self.out.write('%s%*s'
%(p.name, max_property_len - len(p.name), ''))
if p.readable and p.writable:
access = 'readwrite'
elif p.readable:
access = 'readable '
else:
access = 'writable '
self.out.write(' %s %s\n'%(access, p.signature))
def print_synopsis_methods(self, i):
self.out.write(' <refsynopsisdiv role="synopsis">\n'%())
self.out.write(' <title role="synopsis.title">Methods</title>\n'%())
self.out.write(' <synopsis>\n'%())
for m in i.methods:
self.print_method_prototype(i, m, in_synopsis=True)
self.out.write('</synopsis>\n'%())
self.out.write(' </refsynopsisdiv>\n'%())
def print_synopsis_signals(self, i):
self.out.write(' <refsect1 role="signal_proto">\n'%())
self.out.write(' <title role="signal_proto.title">Signals</title>\n'%())
self.out.write(' <synopsis>\n'%())
for s in i.signals:
self.print_signal_prototype(i, s, in_synopsis=True)
self.out.write('</synopsis>\n'%())
self.out.write(' </refsect1>\n'%())
def print_synopsis_properties(self, i):
self.out.write(' <refsect1 role="properties">\n'%())
self.out.write(' <title role="properties.title">Properties</title>\n'%())
self.out.write(' <synopsis>\n'%())
for p in i.properties:
self.print_property_prototype(i, p, in_synopsis=True)
self.out.write('</synopsis>\n'%())
self.out.write(' </refsect1>\n'%())
def print_method(self, i, m):
self.out.write('<refsect2 role="method" id="gdbus-method-%s.%s">\n'%(utils.dots_to_hyphens(i.name), m.name))
self.out.write(' <title>The %s() method</title>\n'%(m.name))
self.out.write(' <indexterm zone="gdbus-method-%s.%s"><primary sortas="%s.%s">%s.%s()</primary></indexterm>\n'%(utils.dots_to_hyphens(i.name), m.name, i.name_without_prefix, m.name, i.name, m.name))
self.out.write('<programlisting>\n')
self.print_method_prototype(i, m, in_synopsis=False)
self.out.write('</programlisting>\n')
self.out.write('<para>%s</para>\n'%(self.expand(m.doc_string)))
self.out.write('<variablelist role="params">\n')
for a in m.in_args:
self.out.write('<varlistentry>\n'%())
self.out.write(' <term><literal>IN %s <parameter>%s</parameter></literal>:</term>\n'%(a.signature, a.name))
self.out.write(' <listitem><para>%s</para></listitem>\n'%(self.expand(a.doc_string)))
self.out.write('</varlistentry>\n'%())
for a in m.out_args:
self.out.write('<varlistentry>\n'%())
self.out.write(' <term><literal>OUT %s <parameter>%s</parameter></literal>:</term>\n'%(a.signature, a.name))
self.out.write(' <listitem><para>%s</para></listitem>\n'%(self.expand(a.doc_string)))
self.out.write('</varlistentry>\n'%())
self.out.write('</variablelist>\n')
self.out.write('</refsect2>\n')
def print_signal(self, i, s):
self.out.write('<refsect2 role="signal" id="gdbus-signal-%s.%s">\n'%(utils.dots_to_hyphens(i.name), s.name))
self.out.write(' <title>The "%s" signal</title>\n'%(s.name))
self.out.write(' <indexterm zone="gdbus-signal-%s.%s"><primary sortas="%s::%s">%s::%s</primary></indexterm>\n'%(utils.dots_to_hyphens(i.name), s.name, i.name_without_prefix, s.name, i.name, s.name))
self.out.write('<programlisting>\n')
self.print_signal_prototype(i, s, in_synopsis=False)
self.out.write('</programlisting>\n')
self.out.write('<para>%s</para>\n'%(self.expand(s.doc_string)))
self.out.write('<variablelist role="params">\n')
for a in s.args:
self.out.write('<varlistentry>\n'%())
self.out.write(' <term><literal>%s <parameter>%s</parameter></literal>:</term>\n'%(a.signature, a.name))
self.out.write(' <listitem><para>%s</para></listitem>\n'%(self.expand(a.doc_string)))
self.out.write('</varlistentry>\n'%())
self.out.write('</variablelist>\n')
self.out.write('</refsect2>\n')
def print_property(self, i, p):
self.out.write('<refsect2 role="property" id="gdbus-property-%s.%s">\n'%(utils.dots_to_hyphens(i.name), p.name))
self.out.write(' <title>The "%s" property</title>\n'%(p.name))
self.out.write(' <indexterm zone="gdbus-property-%s.%s"><primary sortas="%s:%s">%s:%s</primary></indexterm>\n'%(utils.dots_to_hyphens(i.name), p.name, i.name_without_prefix, p.name, i.name, p.name))
self.out.write('<programlisting>\n')
self.print_property_prototype(i, p, in_synopsis=False)
self.out.write('</programlisting>\n')
self.out.write('<para>%s</para>\n'%(self.expand(p.doc_string)))
self.out.write('</refsect2>\n')
def expand(self, s):
for key in self.expand_member_dict_keys:
s = s.replace(key, self.expand_member_dict[key])
for key in self.expand_iface_dict_keys:
s = s.replace(key, self.expand_iface_dict[key])
return s
def generate_expand_dicts(self):
self.expand_member_dict = {}
self.expand_iface_dict = {}
for i in self.ifaces:
key = '#%s'%(i.name)
value = '<link linkend="gdbus-interface-%s.top_of_page">%s</link>'%(utils.dots_to_hyphens(i.name), i.name)
self.expand_iface_dict[key] = value
for m in i.methods:
key = '%s.%s()'%(i.name, m.name)
value = '<link linkend="gdbus-method-%s.%s">%s()</link>'%(utils.dots_to_hyphens(i.name), m.name, m.name)
self.expand_member_dict[key] = value
for s in i.signals:
key = '#%s::%s'%(i.name, s.name)
value = '<link linkend="gdbus-signal-%s.%s">"%s"</link>'%(utils.dots_to_hyphens(i.name), s.name, s.name)
self.expand_member_dict[key] = value
for p in i.properties:
key = '#%s:%s'%(i.name, p.name)
value = '<link linkend="gdbus-property-%s.%s">"%s"</link>'%(utils.dots_to_hyphens(i.name), p.name, p.name)
self.expand_member_dict[key] = value
# Make sure to expand the keys in reverse order so e.g. #org.foo.Iface:MediaCompat
# is evaluated before #org.foo.Iface:Media ...
self.expand_member_dict_keys = self.expand_member_dict.keys()
self.expand_member_dict_keys.sort(reverse=True)
self.expand_iface_dict_keys = self.expand_iface_dict.keys()
self.expand_iface_dict_keys.sort(reverse=True)
def generate(self):
self.generate_expand_dicts()
for i in self.ifaces:
self.out = file('%s-%s.xml'%(self.docbook, i.name), 'w')
self.out.write(''%())
self.out.write('<?xml version="1.0" encoding="utf-8"?>\n'%())
self.out.write('<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"\n'%())
self.out.write(' "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [\n'%())
self.out.write(']>\n'%())
self.out.write('<refentry id="gdbus-%s">\n'%(i.name))
self.out.write(' <refmeta>'%())
self.out.write(' <refentrytitle role="top_of_page" id="gdbus-interface-%s.top_of_page">%s</refentrytitle>\n'%(utils.dots_to_hyphens(i.name), i.name))
self.out.write(' <indexterm zone="gdbus-interface-%s.top_of_page"><primary sortas="%s">%s</primary></indexterm>\n'%(utils.dots_to_hyphens(i.name), i.name_without_prefix, i.name))
self.out.write(' </refmeta>'%())
self.out.write(' <refnamediv>'%())
self.out.write(' <refname>%s</refname>'%(i.name))
self.out.write(' <refpurpose>%s</refpurpose>'%(i.doc_string_brief))
self.out.write(' </refnamediv>'%())
if len(i.methods) > 0:
self.print_synopsis_methods(i)
if len(i.signals) > 0:
self.print_synopsis_signals(i)
if len(i.properties) > 0:
self.print_synopsis_properties(i)
self.out.write('<refsect1 role="desc" id="gdbus-interface-%s">\n'%(utils.dots_to_hyphens(i.name)))
self.out.write(' <title role="desc.title">Description</title>\n'%())
self.out.write(' <para>%s</para>\n'%(self.expand(i.doc_string)))
self.out.write('</refsect1>\n'%())
if len(i.methods) > 0:
self.out.write('<refsect1 role="details" id="gdbus-methods-%s">\n'%(i.name))
self.out.write(' <title role="details.title">Method Details</title>\n'%())
for m in i.methods:
self.print_method(i, m)
self.out.write('</refsect1>\n'%())
if len(i.signals) > 0:
self.out.write('<refsect1 role="details" id="gdbus-signals-%s">\n'%(i.name))
self.out.write(' <title role="details.title">Signal Details</title>\n'%())
for s in i.signals:
self.print_signal(i, s)
self.out.write('</refsect1>\n'%())
if len(i.properties) > 0:
self.out.write('<refsect1 role="details" id="gdbus-properties-%s">\n'%(i.name))
self.out.write(' <title role="details.title">Property Details</title>\n'%())
for s in i.properties:
self.print_property(i, s)
self.out.write('</refsect1>\n'%())
self.out.write('</refentry>\n')
self.out.write('\n')

View File

@ -0,0 +1,171 @@
# -*- Mode: Python -*-
import sys
import argparse
import config
import utils
import dbustypes
import parser
import codegen
import codegen_docbook
def find_arg(arg_list, arg_name):
for a in arg_list:
if a.name == arg_name:
return a
return None
def find_method(iface, method):
for m in iface.methods:
if m.name == method:
return m
return None
def find_signal(iface, signal):
for m in iface.signals:
if m.name == signal:
return m
return None
def find_prop(iface, prop):
for m in iface.properties:
if m.name == prop:
return m
return None
def apply_annotation(iface_list, iface, method, signal, prop, arg, key, value):
for i in iface_list:
if i.name == iface:
iface_obj = i
break
if iface_obj == None:
raise RuntimeError('No interface %s'%iface)
target_obj = None
if method:
method_obj = find_method(iface_obj, method)
if method_obj == None:
raise RuntimeError('No method %s on interface %s'%(method, iface))
if arg:
arg_obj = find_arg(method_obj.in_args, arg)
if (arg_obj == None):
arg_obj = find_arg(method_obj.out_args, arg)
if (arg_obj == None):
raise RuntimeError('No arg %s on method %s on interface %s'%(arg, method, iface))
target_obj = arg_obj
else:
target_obj = method_obj
elif signal:
signal_obj = find_signal(iface_obj, signal)
if signal_obj == None:
raise RuntimeError('No signal %s on interface %s'%(signal, iface))
if arg:
arg_obj = find_arg(signal_obj.args, arg)
if (arg_obj == None):
raise RuntimeError('No arg %s on signal %s on interface %s'%(arg, signal, iface))
target_obj = arg_obj
else:
target_obj = signal_obj
elif prop:
prop_obj = find_prop(iface_obj, prop)
if prop_obj == None:
raise RuntimeError('No property %s on interface %s'%(prop, iface))
target_obj = prop_obj
else:
target_obj = iface_obj
target_obj.annotations.insert(0, dbustypes.Annotation(key, value))
def apply_annotations(iface_list, annotation_list):
# apply annotations given on the command line
for (what, key, value) in annotation_list:
pos = what.find('::')
if pos != -1:
# signal
iface = what[0:pos];
signal = what[pos + 2:]
pos = signal.find('[')
if pos != -1:
arg = signal[pos + 1:]
signal = signal[0:pos]
pos = arg.find(']')
arg = arg[0:pos]
apply_annotation(iface_list, iface, None, signal, None, arg, key, value)
else:
apply_annotation(iface_list, iface, None, signal, None, None, key, value)
else:
pos = what.find(':')
if pos != -1:
# property
iface = what[0:pos];
prop = what[pos + 1:]
apply_annotation(iface_list, iface, None, None, prop, None, key, value)
else:
pos = what.find('()')
if pos != -1:
# method
combined = what[0:pos]
pos = combined.rfind('.')
iface = combined[0:pos]
method = combined[pos + 1:]
pos = what.find('[')
if pos != -1:
arg = what[pos + 1:]
pos = arg.find(']')
arg = arg[0:pos]
apply_annotation(iface_list, iface, method, None, None, arg, key, value)
else:
apply_annotation(iface_list, iface, method, None, None, None, key, value)
else:
# must be an interface
iface = what
apply_annotation(iface_list, iface, None, None, None, None, key, value)
def codegen_main():
arg_parser = argparse.ArgumentParser(description='GDBus Code Generator')
arg_parser.add_argument('xml_files', metavar='FILE', type=file, nargs='+',
help='D-Bus introspection XML file')
arg_parser.add_argument('--interface-prefix', nargs='?', metavar='PREFIX', default='',
help='String to strip from D-Bus interface names for code and docs')
arg_parser.add_argument('--c-namespace', nargs='?', metavar='NAMESPACE', default='',
help='The namespace to use for generated C code')
arg_parser.add_argument('--generate-c-code', nargs='?', metavar='OUTFILES',
help='Generate C code in OUTFILES.[ch]')
arg_parser.add_argument('--generate-docbook', nargs='?', metavar='OUTFILES',
help='Generate Docbook in OUTFILES-org.Project.IFace.xml')
arg_parser.add_argument('--annotate', nargs=3, action='append', metavar=('WHAT', 'KEY', 'VALUE'),
help='Add annotation (may be used several times)')
args = arg_parser.parse_args();
all_ifaces = []
for f in args.xml_files:
xml_data = f.read()
f.close()
parsed_ifaces = parser.parse_dbus_xml(xml_data)
all_ifaces.extend(parsed_ifaces)
if args.annotate != None:
apply_annotations(all_ifaces, args.annotate)
for i in parsed_ifaces:
i.post_process(args.interface_prefix, args.c_namespace)
c_code = args.generate_c_code
if c_code:
h = file(c_code + '.h', 'w')
c = file(c_code + '.c', 'w')
gen = codegen.CodeGenerator(all_ifaces, args.c_namespace, args.interface_prefix, h, c);
ret = gen.generate()
docbook = args.generate_docbook
if docbook:
gen = codegen_docbook.DocbookCodeGenerator(all_ifaces, docbook);
ret = gen.generate()
sys.exit(0)
if __name__ == "__main__":
codegen_main()

View File

@ -0,0 +1,6 @@
# -*- Mode: Python -*-
DATADIR = "@datarootdir@"
DATADIR = DATADIR.replace(
"${prefix}", "@prefix@")
VERSION = "@VERSION@"

View File

@ -0,0 +1,288 @@
# -*- Mode: Python -*-
import utils
class Annotation:
def __init__(self, key, value):
self.key = key
self.value = value
self.annotations = []
class Arg:
def __init__(self, name, signature):
self.name = name
self.signature = signature
self.annotations = []
self.doc_string = ''
def post_process(self, interface_prefix, c_namespace, arg_number):
if len(self.doc_string) == 0:
self.doc_string = utils.lookup_docs(self.annotations)
if self.name == None:
self.name = 'unnamed_arg%d'%arg_number
# default to GVariant
self.ctype_in_g = 'GVariant *'
self.ctype_in = 'GVariant *'
self.ctype_out = 'GVariant **'
self.gtype = 'G_TYPE_VARIANT'
self.free_func = 'g_variant_unref'
self.format_in = '@' + self.signature
self.format_out = '@' + self.signature
if not utils.lookup_annotation(self.annotations, 'org.gtk.GDBus.C.ForceGVariant'):
if self.signature == 'b':
self.ctype_in_g = 'gboolean '
self.ctype_in = 'gboolean '
self.ctype_out = 'gboolean *'
self.gtype = 'G_TYPE_BOOLEAN'
self.free_func = None
self.format_in = 'b'
self.format_out = 'b'
elif self.signature == 'y':
self.ctype_in_g = 'guchar '
self.ctype_in = 'guchar '
self.ctype_out = 'guchar *'
self.gtype = 'G_TYPE_UCHAR'
self.free_func = None
self.format_in = 'y'
self.format_out = 'y'
elif self.signature == 'n':
self.ctype_in_g = 'gint '
self.ctype_in = 'gint16 '
self.ctype_out = 'gint16 *'
self.gtype = 'G_TYPE_INT'
self.free_func = None
self.format_in = 'n'
self.format_out = 'n'
elif self.signature == 'q':
self.ctype_in_g = 'guint '
self.ctype_in = 'guint16 '
self.ctype_out = 'guint16 *'
self.gtype = 'G_TYPE_UINT'
self.free_func = None
self.format_in = 'q'
self.format_out = 'q'
elif self.signature == 'i':
self.ctype_in_g = 'gint '
self.ctype_in = 'gint '
self.ctype_out = 'gint *'
self.gtype = 'G_TYPE_INT'
self.free_func = None
self.format_in = 'i'
self.format_out = 'i'
elif self.signature == 'u':
self.ctype_in_g = 'guint '
self.ctype_in = 'guint '
self.ctype_out = 'guint *'
self.gtype = 'G_TYPE_UINT'
self.free_func = None
self.format_in = 'u'
self.format_out = 'u'
elif self.signature == 'x':
self.ctype_in_g = 'gint64 '
self.ctype_in = 'gint64 '
self.ctype_out = 'gint64 *'
self.gtype = 'G_TYPE_INT64'
self.free_func = None
self.format_in = 'x'
self.format_out = 'x'
elif self.signature == 't':
self.ctype_in_g = 'guint64 '
self.ctype_in = 'guint64 '
self.ctype_out = 'guint64 *'
self.gtype = 'G_TYPE_UINT64'
self.free_func = None
self.format_in = 't'
self.format_out = 't'
elif self.signature == 'd':
self.ctype_in_g = 'gdouble '
self.ctype_in = 'gdouble '
self.ctype_out = 'gdouble *'
self.gtype = 'G_TYPE_DOUBLE'
self.free_func = None
self.format_in = 'd'
self.format_out = 'd'
elif self.signature == 's':
self.ctype_in_g = 'const gchar *'
self.ctype_in = 'const gchar *'
self.ctype_out = 'gchar **'
self.gtype = 'G_TYPE_STRING'
self.free_func = 'g_free'
self.format_in = 's'
self.format_out = 's'
elif self.signature == 'o':
self.ctype_in_g = 'const gchar *'
self.ctype_in = 'const gchar *'
self.ctype_out = 'gchar **'
self.gtype = 'G_TYPE_STRING'
self.free_func = 'g_free'
self.format_in = 'o'
self.format_out = 'o'
elif self.signature == 'g':
self.ctype_in_g = 'const gchar *'
self.ctype_in = 'const gchar *'
self.ctype_out = 'gchar **'
self.gtype = 'G_TYPE_STRING'
self.free_func = 'g_free'
self.format_in = 'g'
self.format_out = 'g'
elif self.signature == 'ay':
self.ctype_in_g = 'const gchar *'
self.ctype_in = 'const gchar *'
self.ctype_out = 'gchar **'
self.gtype = 'G_TYPE_STRING'
self.free_func = 'g_free'
self.format_in = '^ay'
self.format_out = '^ay'
elif self.signature == 'as':
self.ctype_in_g = 'const gchar *const *'
self.ctype_in = 'const gchar *const *'
self.ctype_out = 'gchar ***'
self.gtype = 'G_TYPE_STRV'
self.free_func = 'g_strfreev'
self.format_in = '^as'
self.format_out = '^as'
elif self.signature == 'aay':
self.ctype_in_g = 'const gchar *const *'
self.ctype_in = 'const gchar *const *'
self.ctype_out = 'gchar ***'
self.gtype = 'G_TYPE_STRV'
self.free_func = 'g_strfreev'
self.format_in = '^aay'
self.format_out = '^aay'
class Method:
def __init__(self, name):
self.name = name
self.in_args = []
self.out_args = []
self.annotations = []
self.doc_string = ''
def post_process(self, interface_prefix, c_namespace):
if len(self.doc_string) == 0:
self.doc_string = utils.lookup_docs(self.annotations)
name = self.name
overridden_name = utils.lookup_annotation(self.annotations, 'org.gtk.GDBus.Name')
if overridden_name:
name = overridden_name
self.name_lower = utils.camel_case_to_uscore(name).lower().replace('-', '_')
self.name_hyphen = self.name_lower.replace('_', '-')
arg_count = 0
for a in self.in_args:
a.post_process(interface_prefix, c_namespace, arg_count)
arg_count += 1
for a in self.out_args:
a.post_process(interface_prefix, c_namespace, arg_count)
arg_count += 1
class Signal:
def __init__(self, name):
self.name = name
self.args = []
self.annotations = []
self.doc_string = ''
def post_process(self, interface_prefix, c_namespace):
if len(self.doc_string) == 0:
self.doc_string = utils.lookup_docs(self.annotations)
name = self.name
overridden_name = utils.lookup_annotation(self.annotations, 'org.gtk.GDBus.Name')
if overridden_name:
name = overridden_name
self.name_lower = utils.camel_case_to_uscore(name).lower().replace('-', '_')
self.name_hyphen = self.name_lower.replace('_', '-')
arg_count = 0
for a in self.args:
a.post_process(interface_prefix, c_namespace, arg_count)
arg_count += 1
class Property:
def __init__(self, name, signature, access):
self.name = name
self.signature = signature
self.access = access
self.annotations = []
self.arg = Arg('value', self.signature)
self.arg.annotations = self.annotations
self.readable = False
self.writable = False
if self.access == 'readwrite':
self.readable = True
self.writable = True
elif self.access == 'read':
self.readable = True
elif self.access == 'write':
self.writable = True
else:
raise RuntimeError('Invalid access type %s'%self.access)
self.doc_string = ''
def post_process(self, interface_prefix, c_namespace):
if len(self.doc_string) == 0:
self.doc_string = utils.lookup_docs(self.annotations)
name = self.name
overridden_name = utils.lookup_annotation(self.annotations, 'org.gtk.GDBus.Name')
if overridden_name:
name = overridden_name
self.name_lower = utils.camel_case_to_uscore(name).lower().replace('-', '_')
self.name_hyphen = self.name_lower.replace('_', '-')
# recalculate arg
self.arg.annotations = self.annotations
self.arg.post_process(interface_prefix, c_namespace, 0)
class Interface:
def __init__(self, name):
self.name = name
self.methods = []
self.signals = []
self.properties = []
self.annotations = []
self.doc_string = ''
self.doc_string_brief = ''
def post_process(self, interface_prefix, c_namespace):
if len(self.doc_string) == 0:
self.doc_string = utils.lookup_docs(self.annotations)
if len(self.doc_string_brief) == 0:
self.doc_string_brief = utils.lookup_brief_docs(self.annotations)
overridden_name = utils.lookup_annotation(self.annotations, 'org.gtk.GDBus.Name')
if overridden_name:
name = overridden_name
else:
name = self.name
if name.startswith(interface_prefix):
name = name[len(interface_prefix):]
self.name_without_prefix = name
name = utils.strip_dots(name)
name_with_ns = utils.strip_dots(c_namespace + '.' + name)
self.camel_name = name_with_ns
if len(c_namespace) > 0:
self.ns_upper = utils.camel_case_to_uscore(c_namespace).upper() + '_'
self.name_lower = utils.camel_case_to_uscore(c_namespace) + '_' + utils.camel_case_to_uscore(name)
else:
self.ns_upper = ''
self.name_lower = utils.camel_case_to_uscore(name_with_ns)
self.name_upper = utils.camel_case_to_uscore(name).upper()
for m in self.methods:
m.post_process(interface_prefix, c_namespace)
for s in self.signals:
s.post_process(interface_prefix, c_namespace)
for p in self.properties:
p.post_process(interface_prefix, c_namespace)

View File

@ -0,0 +1,11 @@
#!/usr/bin/python
import os
import sys
path = os.path.join('@libdir@', 'gdbus-codegen')
sys.path.insert(0, path)
from codegen_main import codegen_main
sys.exit(codegen_main())

255
gio/gdbus-codegen/parser.py Normal file
View File

@ -0,0 +1,255 @@
# -*- Mode: Python -*-
import dbustypes
import sys
import xml.parsers.expat
class DBusXMLParser:
STATE_TOP = 'top'
STATE_NODE = 'node'
STATE_INTERFACE = 'interface'
STATE_METHOD = 'method'
STATE_SIGNAL = 'signal'
STATE_PROPERTY = 'property'
STATE_ARG = 'arg'
STATE_ANNOTATION = 'annotation'
def __init__(self, xml_data):
self._parser = xml.parsers.expat.ParserCreate()
self._parser.CommentHandler = self.handle_comment
self._parser.CharacterDataHandler = self.handle_char_data
self._parser.StartElementHandler = self.handle_start_element
self._parser.EndElementHandler = self.handle_end_element
self.parsed_interfaces = []
self._cur_object = None
self.state = DBusXMLParser.STATE_TOP
self.state_stack = []
self._cur_object = None
self._cur_object_stack = []
self.doc_comment_last_symbol = ''
self._parser.Parse(xml_data)
COMMENT_STATE_BEGIN = 'begin'
COMMENT_STATE_PARAMS = 'params'
COMMENT_STATE_BODY = 'body'
COMMENT_STATE_SKIP = 'skip'
def handle_comment(self, data):
comment_state = DBusXMLParser.COMMENT_STATE_BEGIN;
lines = data.split('\n')
symbol = ''
body = ''
in_para = False
params = {}
for line in lines:
orig_line = line
line = line.lstrip()
if comment_state == DBusXMLParser.COMMENT_STATE_BEGIN:
if len(line) > 0:
colon_index = line.find(': ')
if colon_index == -1:
if line.endswith(':'):
symbol = line[0:len(line)-1]
comment_state = DBusXMLParser.COMMENT_STATE_PARAMS
else:
comment_state = DBusXMLParser.COMMENT_STATE_SKIP
else:
symbol = line[0:colon_index]
rest_of_line = line[colon_index+2:].strip()
if len(rest_of_line) > 0:
body += '<para>' + rest_of_line + '</para>'
comment_state = DBusXMLParser.COMMENT_STATE_PARAMS
elif comment_state == DBusXMLParser.COMMENT_STATE_PARAMS:
if line.startswith('@'):
colon_index = line.find(': ')
if colon_index == -1:
comment_state = DBusXMLParser.COMMENT_STATE_BODY
if not in_para:
body += '<para>'
in_para = True
body += orig_line + '\n'
else:
param = line[1:colon_index]
docs = line[colon_index + 2:]
params[param] = docs
else:
comment_state = DBusXMLParser.COMMENT_STATE_BODY
if len(line) > 0:
if not in_para:
body += '<para>'
in_para = True
body += orig_line + '\n'
elif comment_state == DBusXMLParser.COMMENT_STATE_BODY:
if len(line) > 0:
if not in_para:
body += '<para>'
in_para = True
body += orig_line + '\n'
else:
if in_para:
body += '</para>'
in_para = False
if in_para:
body += '</para>'
if symbol != '':
self.doc_comment_last_symbol = symbol
self.doc_comment_params = params
self.doc_comment_body = body
def handle_char_data(self, data):
#print 'char_data=%s'%data
pass
def handle_start_element(self, name, attrs):
old_state = self.state
old_cur_object = self._cur_object
if self.state == DBusXMLParser.STATE_TOP:
if name == DBusXMLParser.STATE_NODE:
self.state = DBusXMLParser.STATE_NODE
else:
raise RuntimeError('Cannot go from state "%s" to element with name "%s"'%(self.state, name))
elif self.state == DBusXMLParser.STATE_NODE:
if name == DBusXMLParser.STATE_INTERFACE:
self.state = DBusXMLParser.STATE_INTERFACE
iface = dbustypes.Interface(attrs['name'])
self._cur_object = iface
self.parsed_interfaces.append(iface)
elif name == DBusXMLParser.STATE_ANNOTATION:
self.state = DBusXMLParser.STATE_ANNOTATION
anno = dbustypes.Annotation(attrs['name'], attrs['value'])
self._cur_object.annotations.append(anno)
self._cur_object = anno
else:
raise RuntimeError('Cannot go from state "%s" to element with name "%s"'%(self.state, name))
# assign docs, if any
if self.doc_comment_last_symbol == attrs['name']:
self._cur_object.doc_string = self.doc_comment_body
if self.doc_comment_params.has_key('short_description'):
short_description = self.doc_comment_params['short_description']
self._cur_object.doc_string_brief = short_description
elif self.state == DBusXMLParser.STATE_INTERFACE:
if name == DBusXMLParser.STATE_METHOD:
self.state = DBusXMLParser.STATE_METHOD
method = dbustypes.Method(attrs['name'])
self._cur_object.methods.append(method)
self._cur_object = method
elif name == DBusXMLParser.STATE_SIGNAL:
self.state = DBusXMLParser.STATE_SIGNAL
signal = dbustypes.Signal(attrs['name'])
self._cur_object.signals.append(signal)
self._cur_object = signal
elif name == DBusXMLParser.STATE_PROPERTY:
self.state = DBusXMLParser.STATE_PROPERTY
prop = dbustypes.Property(attrs['name'], attrs['type'], attrs['access'])
self._cur_object.properties.append(prop)
self._cur_object = prop
elif name == DBusXMLParser.STATE_ANNOTATION:
self.state = DBusXMLParser.STATE_ANNOTATION
anno = dbustypes.Annotation(attrs['name'], attrs['value'])
self._cur_object.annotations.append(anno)
self._cur_object = anno
else:
raise RuntimeError('Cannot go from state "%s" to element with name "%s"'%(self.state, name))
# assign docs, if any
if attrs.has_key('name') and self.doc_comment_last_symbol == attrs['name']:
self._cur_object.doc_string = self.doc_comment_body
elif self.state == DBusXMLParser.STATE_METHOD:
if name == DBusXMLParser.STATE_ARG:
self.state = DBusXMLParser.STATE_ARG
arg_name = None
if attrs.has_key('name'):
arg_name = attrs['name']
arg = dbustypes.Arg(arg_name, attrs['type'])
direction = attrs['direction']
if direction == 'in':
self._cur_object.in_args.append(arg)
elif direction == 'out':
self._cur_object.out_args.append(arg)
else:
raise RuntimeError('Invalid direction "%s"'%(direction))
self._cur_object = arg
elif name == DBusXMLParser.STATE_ANNOTATION:
self.state = DBusXMLParser.STATE_ANNOTATION
anno = dbustypes.Annotation(attrs['name'], attrs['value'])
self._cur_object.annotations.append(anno)
self._cur_object = anno
else:
raise RuntimeError('Cannot go from state "%s" to element with name "%s"'%(self.state, name))
# assign docs, if any
if self.doc_comment_last_symbol == old_cur_object.name:
if attrs.has_key('name') and self.doc_comment_params.has_key(attrs['name']):
doc_string = self.doc_comment_params[attrs['name']]
if doc_string != None:
self._cur_object.doc_string = doc_string
elif self.state == DBusXMLParser.STATE_SIGNAL:
if name == DBusXMLParser.STATE_ARG:
self.state = DBusXMLParser.STATE_ARG
arg_name = None
if attrs.has_key('name'):
arg_name = attrs['name']
arg = dbustypes.Arg(arg_name, attrs['type'])
self._cur_object.args.append(arg)
self._cur_object = arg
elif name == DBusXMLParser.STATE_ANNOTATION:
self.state = DBusXMLParser.STATE_ANNOTATION
anno = dbustypes.Annotation(attrs['name'], attrs['value'])
self._cur_object.annotations.append(anno)
self._cur_object = anno
else:
raise RuntimeError('Cannot go from state "%s" to element with name "%s"'%(self.state, name))
# assign docs, if any
if self.doc_comment_last_symbol == old_cur_object.name:
if attrs.has_key('name') and self.doc_comment_params.has_key(attrs['name']):
doc_string = self.doc_comment_params[attrs['name']]
if doc_string != None:
self._cur_object.doc_string = doc_string
elif self.state == DBusXMLParser.STATE_PROPERTY:
if name == DBusXMLParser.STATE_ANNOTATION:
self.state = DBusXMLParser.STATE_ANNOTATION
anno = dbustypes.Annotation(attrs['name'], attrs['value'])
self._cur_object.annotations.append(anno)
self._cur_object = anno
else:
raise RuntimeError('Cannot go from state "%s" to element with name "%s"'%(self.state, name))
elif self.state == DBusXMLParser.STATE_ARG:
if name == DBusXMLParser.STATE_ANNOTATION:
self.state = DBusXMLParser.STATE_ANNOTATION
anno = dbustypes.Annotation(attrs['name'], attrs['value'])
self._cur_object.annotations.append(anno)
self._cur_object = anno
else:
raise RuntimeError('Cannot go from state "%s" to element with name "%s"'%(self.state, name))
elif self.state == DBusXMLParser.STATE_ANNOTATION:
if name == DBusXMLParser.STATE_ANNOTATION:
self.state = DBusXMLParser.STATE_ANNOTATION
anno = dbustypes.Annotation(attrs['name'], attrs['value'])
self._cur_object.annotations.append(anno)
self._cur_object = anno
else:
raise RuntimeError('Cannot go from state "%s" to element with name "%s"'%(self.state, name))
else:
raise RuntimeError('Unhandled state "%s" while entering element with name "%s"'%(self.state, name))
self.state_stack.append(old_state)
self._cur_object_stack.append(old_cur_object)
def handle_end_element(self, name):
self.state = self.state_stack.pop()
self._cur_object = self._cur_object_stack.pop()
def parse_dbus_xml(xml_data):
parser = DBusXMLParser(xml_data)
return parser.parsed_interfaces

View File

@ -0,0 +1,56 @@
# -*- Mode: Python -*-
def strip_dots(s):
ret = ''
force_upper = False
for c in s:
if c == '.':
force_upper = True
else:
if force_upper:
ret += c.upper()
force_upper = False
else:
ret += c
return ret
def dots_to_hyphens(s):
return s.replace('.', '-')
def camel_case_to_uscore(s):
ret = ''
insert_uscore = False
prev_was_lower = False
for c in s:
if c.isupper():
if prev_was_lower:
insert_uscore = True
prev_was_lower = False
else:
prev_was_lower = True
if insert_uscore:
ret += '_'
ret += c.lower()
insert_uscore = False
return ret
def lookup_annotation(annotations, key):
if annotations:
for a in annotations:
if a.key == key:
return a.value
return None
def lookup_docs(annotations):
s = lookup_annotation(annotations, 'org.gtk.GDBus.DocString')
if s == None:
return ''
else:
return s
def lookup_brief_docs(annotations):
s = lookup_annotation(annotations, 'org.gtk.GDBus.DocString.Short')
if s == None:
return ''
else:
return s