<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>cmarcelo&#039;s blog</title>
	<atom:link href="http://cmarcelo.org/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://cmarcelo.org/blog</link>
	<description></description>
	<lastBuildDate>Wed, 14 Apr 2010 18:16:51 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Qt event dispatchers and loops</title>
		<link>http://cmarcelo.org/blog/2010/04/14/qt-event-dispatchers-and-loops/</link>
		<comments>http://cmarcelo.org/blog/2010/04/14/qt-event-dispatchers-and-loops/#comments</comments>
		<pubDate>Wed, 14 Apr 2010 17:58:10 +0000</pubDate>
		<dc:creator>cmarcelo</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[ecore]]></category>
		<category><![CDATA[efl]]></category>
		<category><![CDATA[evas]]></category>
		<category><![CDATA[event]]></category>
		<category><![CDATA[mainloop]]></category>
		<category><![CDATA[qt]]></category>

		<guid isPermaLink="false">http://cmarcelo.org/blog/?p=51</guid>
		<description><![CDATA[Lately I&#8217;ve been working with Qt, a C++ framework for developing cross platform applications. Like many other frameworks/environments Qt enables event-driven programming. Using that methodology of programming, a typical Qt applications does something like this:

Setup the UI, start listening in socket.
Connect objects to react to: user manipulating the UI, connection happening in socket.
Calls app.exec().

That&#8217;s it. [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve been working with Qt, a C++ framework for developing cross platform applications. Like many other frameworks/environments Qt enables <a href="http://en.wikipedia.org/wiki/Event-driven_programming">event-driven programming</a>. Using that methodology of programming, a typical Qt applications does something like this:</p>
<ol>
<li>Setup the UI, start listening in socket.</li>
<li>Connect objects to react to: user manipulating the UI, connection happening in socket.</li>
<li>Calls <tt>app.exec()</tt>.</li>
</ol>
<p>That&#8217;s it. Then it&#8217;s job of <tt>app</tt> to act like a <i>dispatcher</i>, waiting for external world events to happen and propagating them to the application objects. Qt uses <a href="http://doc.qt.nokia.com/eventsandfilters.html">QEvent</a> to propagate those events.</p>
<p>Well, this is common in other frameworks. In some of them the word <i>mainloop</i> or <i>eventloop</i> is used to describe the job that <tt>app</tt> in Qt is doing. For example: <a href="http://www.enlightenment.org/p.php?p=about&#038;l=en">EFL</a> has the ecore mainloop, <a href="http://library.gnome.org/devel/glib/2.24/glib-The-Main-Event-Loop.html">glib</a> has a mainloop and <a href="http://nodejs.org/">Node.js</a> has this concept built in as well.</p>
<p>In this article I&#8217;ll focus mostly on <i>Qt machinery</i> to work with mainloops.</p>
<h3>Underneath <tt>app</tt></h3>
<p>One interesting aspect of the Qt implementation is that the concept of mainloop is abstracted, so other parts of Qt don&#8217;t heavily depend on how the mainloop is implemented. This supports Qt&#8217;s goal of being crossplatform. So the real class that implements a mainloop in Qt is not the <a href="http://doc.qt.nokia.com/qapplication.html">QApplication</a>, but another platform dependent class that implements the interface defined by <a href="http://doc.qt.nokia.com/qabstracteventdispatcher.html">QAbstractEventDispatcher</a>.</p>
<p>This abstract class is the minimum interface that QApplication needs to provide the event-driven programming for its users. This allows different implementations for each platform, and even multiple implementations on the same platform.</p>
<p>In Unix, for example, besides the default dispatcher implemented using POSIX API, you can use an event dispatcher implemented on top of glib mainloop. And this gives you something very nice: your program can make use of libraries that rely on the glib mainloop as well. This kind of integration has been done in other libraries as well, for example with <a href="http://blog.gustavobarbieri.com.br/2009/10/01/ecore-glib-main-loop-integration/">ecore on top of glib</a>.</p>
<p>When you instantiate QApplication, Qt will automatically create a proper event dispatcher for the platform and use it. However if you instantiate one before, QApplication will use it. But before we play with that, let&#8217;s look at event dispatchers a little bit more.</p>
<h3>What can an event dispatcher do?</h3>
<p>Well, if we look at QAbstractEventDispatcher, we&#8217;ll see the following groups of methods:</p>
<ul>
<li><b>Timer:</b> to register/unregister timers, so the mainloop will send a <a href="http://doc.qt.nokia.com/qtimerevent.html">QTimerEvent</a> to an object after certain time.</li>
<li><b>Socket notifier</b>: in Unix-world this would be registering/unregistering file descriptors to watch. The mainloop will send a <tt>QSockAct</tt> type of event to the socket notifier object.</li>
<li><b>Control</b>: to run one iteration of the mainloop, to enable another thread <i>wake</i> the mainloop if it is idle waiting for new external events.</li>
</ul>
<p>If you&#8217;re familiar with the <tt>select()</tt> function from POSIX, you can imagine how this functionality can be implemented. Running an iteration of the mainloop would be the <tt>select()</tt> call for example. Actually, that&#8217;s the way the default unix event dispatcher works in Qt.</p>
<p>With such an interface, it&#8217;s easy to see that Qt could run on top of most mainloops, and for this article I wrote a simple <i>QEventDispatcherEcore</i>, which implements this interface on top of EFL&#8217;s ecore mainloop.</p>
<h3>Show me the code!</h3>
<p>The code is in my <a href="http://cmarcelo.org/code/cgit/playground/">playground repository</a>, and the important file for now is the <a href="http://cmarcelo.org/code/cgit/playground/tree/qt-ecore-dispatcher/dispatcher.cpp?id=2b689a3e1f8843c1da3d6ef9091ea9ca6b0b0d3f">dispatcher.cpp</a>. You&#8217;ll see that it is all marked with <tt>###</tt> comments, which indicates points of the code that are incomplete: this is just a simple example of the concept, be warned!</p>
<p>I won&#8217;t go step by step in the code, because it should be not so hard to understand. The Ecore library gives us enough functionality to implement all Qt needs. I&#8217;ll highlight two pieces that I think deserve special explanation</p>
<p>First, how the <tt>wakeUp()</tt> call was implemented: since ecore mainloop didn&#8217;t have a similar functionality, I used the same trick as the Unix event dispatcher. The trick is to create a pipe and watch one of the ends inside the mainloop. Then, to wake up we simply write on the other end of the pipe.</p>
<p>A second important point is: the <tt>processEvents()</tt> function takes a <tt>flags</tt> argument, which indicates to the event dispatcher important parameters about the iteration it is going to run: whether it should ignore UI events or whether it should block waiting for the next event if there&#8217;s no event right now.</p>
<p>The <i>block until event show up</i> is a very important functionality, since we don&#8217;t want to spend all CPU cycles calling <tt>processEvents()</tt> again and again with no side effect, no new event being delivered, and avoid <a href="http://en.wikipedia.org/wiki/Busy_loop">busy loop</a>.</p>
<p>In the code for the event dispatcher example, what&#8217;s tricky is that while Ecore does have a <tt>iterate()</tt> primitive it doesn&#8217;t have a <tt>iterate_and_wait()</tt>. The rationale is that part of the work that Qt is doing here inside QApplication code<br />
<code>
<pre>
    // Simplified version of what QApplication do
    while (!quitLoop)
        processEvents(flagToWait);
</pre>
<p></code><br />
is something that usually libraries encapsulate for the user. In our case has a <tt>mainloop_begin()</tt> function to encapsulate the while-loop.</p>
<p>To the event dispatcher example, what I did was to simulate the functionality I wanted by making use of Ecore&#8217;s <tt>idle_exiter</tt> mechanism, which allow functions to be registered to be called after a iteration the mainloop</p>
<p><code>
<pre>
    // Simplified version of what Ecore do...
    while (!quitLoop) {
        // ...
        processEvents(flagToWait);
        // ...
        runIdleExiters();
    }
</pre>
<p></code></p>
<p>The trick was to register an <tt>idle_exiter</tt> that caused the mainloop to quit. After inspecting Ecore implementation, the result of doing this be exactly what I wanted to achieve with an <tt>iterate_and_wait()</tt> primitive without changing the API.</p>
<h3>Hmmm, what&#8217;s the <tt>guidispatcher</tt>?</h3>
<p>If you followed the repository link, you&#8217;ll see there&#8217;s another dispatcher there in the <a href="http://cmarcelo.org/code/cgit/playground/tree/qt-ecore-dispatcher/guidispatcher.cpp?id=2b689a3e1f8843c1da3d6ef9091ea9ca6b0b0d3f">guidispatcher.cpp</a> file, that&#8217;s the <i>QEventDispatcherEcoreGUI</i>. To understand it we need to remember the difference between a QCoreApplication and a QApplication: the former doesn&#8217;t depend on GUI code, and the latter is the subclass with GUI functionality.</p>
<p>This separation also happens in event dispatchers. Using the case of Unix again, in Qt the GUI for Unix is based on X11. So a QApplication needs to create a X11 connection and watch for events, translate them to QEvents and send them to the proper objects.</p>
<p>This job is exactly what an event dispatcher is for. So in Unix, QCoreApplication uses the Unix&#8217; <tt>select()</tt> implementation we mentioned before, while QApplication uses a subclass of it, which also handles X11 events.</p>
<p>Letting the UI event handling inside the event dispatcher allows the existence of a flag to skip handling of UI events.</p>
<p>Back on our example. This new dispatcher is GUI-enabled, it watches for X11 events and translates them to QEvents for delivery with help of the function <a href="http://doc.qt.nokia.com/qapplication.html#x11ProcessEvent">QApplication::x11ProcessEvent()</a>. Note that since this is just a proof-of-concept, we are not checking for all the flags passed.</p>
<p>Inside the directory &#8216;qapplication&#8217;, there is one example using this dispatcher. It mixes a QWidget on the screen (using QApplication for the GUI) and an EFL window showing Evas in other. They are in the same process but with different X connections.</p>
<h3>Last but not least: the <tt>QEventLoop</tt></h3>
<p>If you look the Qt documentation, you can see there&#8217;s a <a href="http://doc.qt.nokia.com/qeventloop.html">QEventLoop</a> class. But, does this class do if the mainloop is already in the event dispatcher?</p>
<p>Simply put: QEventLoop is a <i>helper class</i> that provides convenient access to the dispatcher&#8217;s <tt>processEvents()</tt> call. For example, QEventLoop has an <tt>exec()</tt> method, that looks like this</p>
<p><code>
<pre>
    // Simplified version of QEventLoop::exec()
    while (!eventLoopQuit)
        dispatcher->processEvents();
</pre>
<p></code></p>
<p>One usage of this pattern is to make a function blocks but still running the mainloop (so things like UI still work). This enable APIs like the ones used in some <a href="http://doc.qt.nokia.com/qdialog.html">QDialogs</a></p>
<p><code>
<pre>
    QMessageBox msgBox;
    msgBox.setText("The document has been modified.");
    msgBox.setInformativeText("Do you want to save your changes?");
    msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Save);

    // Blocks until a button is clicked in the dialog, ret will contain information
    // to identify that button.
    int ret = msgBox.exec();
</pre>
<p></code></p>
<p>To see some downsides of this kind of API in dialogs, I recommend reading the article <a href="http://labs.qt.nokia.com/blogs/2010/02/23/unpredictable-exec/">Unpredictable exec()</a> from Qt Labs blogs.</p>
<h3>Further reading</h3>
<p>For those who are interested in digging further, there are many ways to go from here:</p>
<ul>
<li><b>Event-driven programming</b>: there are plenty of resources on the net, but I would like to point out two:
<ul>
<li>A talk about Node.js (<a href="http://s3.amazonaws.com/four.livejournal/20091117/jsconf.pdf">pdf</a> and <a href="http://jsconf.eu/2009/video_nodejs_by_ryan_dahl.html">video</a>). Node.js provides an environment for server-side programming in JavaScript based on events. The talk particularly highlights the advantages of using event-driven programming.</li>
<li>A talk from the Plan 9 conference in 2007 called <a href="http://swtch.com/~rsc/talks/threads07/">Threads without Locks</a>. The author shows the relation between usage of threads and event loops and how they can be used together to avoid locks for syncronization. These ideas appear also in <a href="http://golang.org/">Go programming language</a>.</li>
</ul>
</li>
<li><b>QThreads</b>: I didn&#8217;t mentioned threads, but in Qt, if your thread runs a loop, it&#8217;ll create a new event dispatcher. As of today you still can&#8217;t use custom dispatchers for the QThreads, only for the main thread.</li>
<li><b>Evas in Qt</b>: the example showed Evas being used in a Qt application. While this was one way to use Evas in Qt, there are other possibilities. You could just use the Evas library directly with Qt, without Ecore/EcoreEvas. But in that case you&#8217;ll need to do the job of feeding Evas with events yourself.</li>
</ul>
<p>That&#8217;s all folks.</p>
]]></content:encoded>
			<wfw:commentRss>http://cmarcelo.org/blog/2010/04/14/qt-event-dispatchers-and-loops/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Follow up on DBus + Emacs</title>
		<link>http://cmarcelo.org/blog/2010/02/26/follow-up-on-dbus-emacs/</link>
		<comments>http://cmarcelo.org/blog/2010/02/26/follow-up-on-dbus-emacs/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 04:09:41 +0000</pubDate>
		<dc:creator>cmarcelo</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[dbus]]></category>
		<category><![CDATA[elisp]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[notificationitem]]></category>
		<category><![CDATA[statusnotifier]]></category>

		<guid isPermaLink="false">http://cmarcelo.org/blog/?p=30</guid>
		<description><![CDATA[In my last post I used the example of NotificationItem protocol to experiment with the D-Bus bindings in Emacs. It was nice because I learned about lexical-let, and in the end it worked!
What is even better is that, not only the author of the D-Bus bindings in Emacs, Michael Albinus, commented on the post, but [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://cmarcelo.org/blog/2009/11/04/a-non-trivial-example-of-emacs-d-bus-bindings/">last post</a> I used the example of NotificationItem protocol to experiment with the D-Bus bindings in Emacs. It was nice because I learned about <tt>lexical-let</tt>, and in the end it worked!</p>
<p>What is even better is that, not only the author of the D-Bus bindings in Emacs, Michael Albinus, commented on the post, but also implemented functionality that I had to workaround before (thanks, Michael!). This means the code is smaller and the bindings are more complete.</p>
<p>In particular, the bindings now support</p>
<ul>
<li><em>registering properties</em>, and the binding will automatically implement the <strong>org.freedesktop.DBus.Properties</strong> interface (i.e. the <tt>Get</tt>, <tt>GetAll</tt> and <tt>Set</tt> methods).</li>
<li>unregistering objects now will <em>release the service name</em> if there are no more methods/properties registered for that service.</li>
</ul>
<p>Also during that time, the folks working with the protocol, kept reviewing it and the name of protocol changed, now it&#8217;s called <a href="http://notmart.org/misc/statusnotifieritem/index.html">StatusNotifier</a>.</p>
<p>The new code is available <a href="http://cmarcelo.org/code/cgit/playground/plain/elisp/statusnotifier.el">here</a> and should work with recent development versions of Emacs.</p>
<p>By the way, it&#8217;s far from being a complete implementation of the protocol, but it&#8217;s a nice start and was an excellent way to learn both DBus and Emacs :-).</p>
]]></content:encoded>
			<wfw:commentRss>http://cmarcelo.org/blog/2010/02/26/follow-up-on-dbus-emacs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A non-trivial example of Emacs D-Bus bindings</title>
		<link>http://cmarcelo.org/blog/2009/11/04/a-non-trivial-example-of-emacs-d-bus-bindings/</link>
		<comments>http://cmarcelo.org/blog/2009/11/04/a-non-trivial-example-of-emacs-d-bus-bindings/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 04:11:16 +0000</pubDate>
		<dc:creator>cmarcelo</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[closure]]></category>
		<category><![CDATA[dbus]]></category>
		<category><![CDATA[elisp]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[notificationitem]]></category>

		<guid isPermaLink="false">http://cmarcelo.org/blog/?p=9</guid>
		<description><![CDATA[This post will talk about the difficulties I had when implementing part of a simple but non-trivial D-Bus API using the Emacs bindings.
A few weeks ago we had to do some work related to D-Bus, the IPC solution from FreeDesktop. I took the chance to understand it better, reading a little bit about it and [...]]]></description>
			<content:encoded><![CDATA[<p><em>This post will talk about the difficulties I had when implementing part of a simple but non-trivial D-Bus API using the Emacs bindings.</em></p>
<p>A few weeks ago we had to do some work related to D-Bus, the IPC solution from <a href="http://freedesktop.org">FreeDesktop</a>. I took the chance to understand it better, reading a little bit about it and doing some experimenting.</p>
<p>There are some very useful tools to debug and experiment with D-Bus: I used a lot of <tt>dbus-send</tt> and <tt>qdbus</tt> (part of Qt library) to call methods of existing objects. Also used <a href="https://fedorahosted.org/d-feet/">d-feet</a> to explore the object interfaces. To monitor interactions in the bus, I used <a href="http://blog.fpmurphy.com/2009/02/dbus-monitor.html">dbus-monitor</a>.</p>
<p>However, one of the APIs we were interested in was the <a href="http://www.notmart.org/misc/notificationitem/">Notification Item</a>, which came from KDE but it is now in the path to become a freedesktop <em>blessed</em> specification. It aims to replace the <em>system tray</em> mechanism based on XEmbed.</p>
<p>The Notification Item is a little bit more complex to play with because it was based on the interaction of different services. You have a daemon to track items and hosts, and hosts will ask items about their properties. So, it wasn&#8217;t a simple matter of sending messages, it was necessary to get a service up with certain properties to see it work, i.e. just <tt>dbus-send</tt> and other tools were not enough.</p>
<p>Even though Qt has very nice tools for binding and implementing D-Bus APIs (for the real work we used those), I was aiming for something more &#8220;dynamic&#8221;, in the sense that I could build a notification item part by part, and see the interactions.</p>
<p>And then I ended up writing a small, but non-trivial, example of D-Bus usage in Emacs, using the brand new bindings available in <a href="http://lists.gnu.org/archive/html/info-gnu-emacs/2009-07/msg00000.html">Emacs 23</a>. It implements parts of the Notification Item. In a KDE desktop this means you can make an icon appear in the notification area on the panel and interact with Emacs through that icon.</p>
<p>The code is available <a href="http://cmarcelo.org/code/cgit/playground/plain/elisp/notificationitem.el">here</a>, I would be really glad to hear about different ways of doing things. In particular the usage of <code>lexical-let</code>.</p>
<p>The documentation of D-Bus bindings for Emacs is very nice, so I recommend it. Another take on understanding how D-Bus work is looking at <a href="http://techbase.kde.org/Development/Tutorials/D-Bus">KDE&#8217;s tutorials</a>, they also explain how to use Qt D-Bus bindings in C++.</p>
<p>I will not go into a line by line detailed description of the code. Instead, I&#8217;ll comment on things that I think made the example non-trivial: the usage of <code>lexical-let</code> to create handler (<em>callback</em>) functions, defining D-Bus properties and unregistering a service created in Emacs.</p>
<p>Note that this post is not meant to downplay the Emacs bindings, but to point out <strong>my</strong> difficulties in a real use, as well as how I overcame them. It really rocked to have those bindings available, without them this post wouldn&#8217;t exist and would lose a chance to learn a lot of things about both D-Bus and Emacs Lisp.<br />
<h3>The <code>lexical-let</code></h3>
<p> In Emacs, to react to methods being called on a certain object in a service, you have to use the function</p>
<p><code>
<pre>
(dbus-register-method BUS SERVICE PATH INTERFACE METHOD HANDLER)
</pre>
<p></code></p>
<p>so that when that method is called on your object in the given service, the function handler will be called.</p>
<p>In the Notification Item, one of such methods that items have to react to is <code>Activate</code>. In KDE, items are usually represented by icons in the panel, and the action of clicking triggers <code>Activate</code>. There is a <code>SecondaryActivate</code>, which in KDE is triggered by the middle click.</p>
<p>When coding the example, I made the choice that, instead of creating one Notification Item object for the entire session, it would be possible to create different items, with different handlers. And while each method has two integer parameters describing a position where the icon was activated, I wanted to have only one handler function with one parameter describing whether the activation was primary or secondary.</p>
<p>My <code>make-notification-item</code> function takes, among other things, the handler function I described. The code for actually registering the methods is (without the docstring)<br />
<code>
<pre>(<span style="color: #a020f0;">defun</span> <span style="color: #0000ff;">ni-register-activate-handlers</span> (service activate)
  (<span style="color: #a020f0;">lexical-let</span> ((act activate))
    (list (dbus-register-method <span style="color: #7a378b;">:session</span> service <span style="color: #8b2252;">"/NotificationItem"</span>
                                <span style="color: #8b2252;">"org.kde.NotificationItem"</span> <span style="color: #8b2252;">"Activate"</span>
                                (<span style="color: #a020f0;">lambda</span> (x y) (funcall act t)))
          (dbus-register-method <span style="color: #7a378b;">:session</span> service <span style="color: #8b2252;">"/NotificationItem"</span>
                                <span style="color: #8b2252;">"org.kde.NotificationItem"</span> <span style="color: #8b2252;">"SecondaryActivate"</span>
                                (<span style="color: #a020f0;">lambda</span> (x y) (funcall act nil))))))
</pre>
<p></code><br />
so I actually registered a <code>lambda</code>, to filter the discarded parameters and add the primary/secondary parameter. Note that this is going to call the function <code>act</code>, which is not defined in the lambda&#8217;s scope.</p>
<p>In many programming languages, what would happen is that the context where <code>act</code> is defined would be saved and attached to the lambda that is being passed around. This feature is what people call <em>lexical binding</em> (or <em>lexical scoping</em>), and the &#8220;lambda plus context&#8221; is called a <em>closure</em>.</p>
<p>But by default Emacs Lisp doesn&#8217;t support &#8216;closures&#8217; but instead will look into (what I will call) the <em>global context</em> for the <code>act</code> variable. So in my example, I could just use a <code>(setq 'act ...)</code> to change what action would take place when some item was activated. This is called <em>dynamic binding</em> (or <em>dynamic binding</em>). Actually what happens is that when the handler is called, <code>act</code> is not defined, so we get an error.</p>
<p>The code works because of the <code>lexical-let</code>. What it does, roughly binding. Behind the scenes, it is a macro that creates a unique symbol for <code>act</code> in what I called the global context and uses it in the code. So it works in dynamic binding mode. If we somehow found out the name of that generated symbol, we could mess with it just like we could if we were not using <code>lexical-let</code>.</p>
<p>While dynamic scoping is less common, it has some benefits. For a more detailed discussion on that topic, see the Emacs Wiki page <a href="http://www.emacswiki.org/emacs/DynamicBindingVsLexicalBinding">DynamicBindingVsLexicalBinding</a>.</p>
<p>The <code>lexical-let</code> is also used when defining the handler functions<br />
that respond to D-Bus queries on properties of the item object.</p>
<p>It seems to me that <code>lexical-let</code> was essential to allow multiple items to be created at the same time. This happens because of the way the bindings are done.  The handler function is called without passing any information regarding what D-Bus service/object was called. And at register time we have no other way to pass additional information that would be sent as argument when calling the handler.</p>
<p>If either of those were different, I could have a dispatch table mapping objects to real handlers, or some arbitrary data to real handlers.</p>
<h3>D-Bus Properties</h3>
<p>While writing the example, I discovered that D-Bus itself has a very low-level mechanism of <em>message passing</em> (or method calling) and many other features are built on top of that.</p>
<p>One of these high level concepts are the <em>D-Bus Properties</em>. In practice the idea is very simple, and could have appeared in different APIs based on D-Bus (maybe that&#8217;s the reason they are there&#8230;). Instead of having a series of methods for getting data associated with an object, you could have only one, and use an identifier to know which data you are talking about.</p>
<p>For example, in Notification Item, items have among other stuff: a category, a title and a status. Instead of having three getter methods, what the specification of Notification Item does is say that an item have those three properties. Of course, there&#8217;s a well defined interface for properties (it is the <strong>org.freedesktop.DBus.Properties</strong>).</p>
<p>However these high level features are not always available in the bindings. As of the time of this post, the Emacs binding only support reading other objects properties, but not registering new ones. So if you want to do that, you have to implement by hand <strong>org.freedesktop.DBus.Properties</strong> for your object.</p>
<p>In my code, that&#8217;s implemented in <code>my-dbus-register-properties</code> and its auxiliary functions. And that&#8217;s another place I&#8217;ve used <code>lexical-let</code>, this time to create different handlers for the <tt>Get</tt> method (part of D-Bus properties interface)<br />
<code>
<pre>
(<span style="color: #a020f0;">defun</span> <span style="color: #0000ff;">my-dbus-register-get</span> (bus service object prophash)
  (<span style="color: #a020f0;">lexical-let</span> ((ph prophash))
    (dbus-register-method
     bus service object dbus-interface-properties <span style="color: #8b2252;">"Get"</span>
     (<span style="color: #a020f0;">lambda</span> (iname pname)
       (list `(<span style="color: #7a378b;">:variant</span> ,(gethash pname ph)))))))
</pre>
<p></code><br />
in the code, I stored the properties of an item in a hash.</p>
<h3>How to make a service disappear?</h3>
<p>One last issue that I&#8217;ve tackled was the fact that the service continued to be visible to D-Bus clients after I unregistered all the methods.</p>
<p>After some research, I&#8217;ve found out that what really was happening was that when registering a method for a <em>named service</em> for the first time, the binding requested this name to the server by sending a message to the <em>server object</em> (<strong>org.freedesktop.DBus</strong>) this is inside the C code of the binding, and uses a wrapper function instead of explicitly building and sending a message.</p>
<p>Inspecting the binding code, I didn&#8217;t found the equivalent code for releasing this name in the server. So, even with no methods registered, the named still existed and pointed to the Emacs process.</p>
<p>This was an issue for me because the Notification Item API specifies that to unregister an item, you have to unregister (release) the associated name.</p>
<p>While the solution was simple enough<br />
<code>
<pre>
(<span style="color: #a020f0;">defun</span> <span style="color: #0000ff;">my-dbus-release-name</span> (service)
 (dbus-call-method
  <span style="color: #7a378b;">:session</span> dbus-service-dbus dbus-path-dbus dbus-interface-dbus
  <span style="color: #8b2252;">"ReleaseName"</span> service))
</pre>
<p></code><br />
this is something I think could be part of the Emacs bindings. Either for doing this automatically (as the requesting names is), or at least to error check when someone is trying to release a name which still have methods registered.</p>
<h3>Final thought</h3>
<p>It was rewarding to spend time understanding both D-Bus and Elisp. The knowledge helped me understand the D-Bus APIs that we were working at the time, including the Notification Item.</p>
<p>I hope that someone could pick up where I left and try to actually implement a feature in Emacs taking advantage of Notification Item. One obvious feature would be some alert system for the IRC clients in Emacs.</p>
]]></content:encoded>
			<wfw:commentRss>http://cmarcelo.org/blog/2009/11/04/a-non-trivial-example-of-emacs-d-bus-bindings/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A little Emacs experiment</title>
		<link>http://cmarcelo.org/blog/2008/04/26/a-little-emacs-experiment/</link>
		<comments>http://cmarcelo.org/blog/2008/04/26/a-little-emacs-experiment/#comments</comments>
		<pubDate>Sun, 27 Apr 2008 01:56:33 +0000</pubDate>
		<dc:creator>cmarcelo</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[editor]]></category>
		<category><![CDATA[elisp]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[productivity]]></category>
		<category><![CDATA[textmate]]></category>
		<category><![CDATA[yasnippet]]></category>
		<category><![CDATA[yegge]]></category>

		<guid isPermaLink="false">http://cmarcelo.wordpress.com/?p=7</guid>
		<description><![CDATA[As I mentioned before, after starting out the new job, in a new city, with a new language, and a new computer, I started playing with GNU Emacs editor. I kind of staled with Vim, knew how to do stuff, but I wasn&#8217;t feeling very pleased by Vimscript. On the other hand I was reading [...]]]></description>
			<content:encoded><![CDATA[<p>As I mentioned before, after starting out the new job, in a new city, with a new language, and a new computer, I started playing with <a href="http://www.gnu.org/software/emacs/">GNU Emacs</a> editor. I kind of <em>staled</em> with Vim, knew how to do stuff, but I wasn&#8217;t feeling very pleased by Vimscript. On the other hand I was reading good things about Emacs (many of them in <a href="http://steve-yegge.blogspot.com/">Steve Yegge</a> blog and his <a href="http://steve.yegge.googlepages.com/blog-rants"><em>Drunken Rants</em></a>) and always had some curiosity about Elisp.</p>
<p>At first I was using it just for playing at home, and kept using Vim at work, since my project was running at high speed and I was a little bit insecure &#8212; specially because I wanted to use a version from CVS that supported fancy Truetype fonts in the X11 environment. After some time, I got confident enough to use it full-time, bootstrapped my <code>.emacs</code> file with <a href="http://code.google.com/p/barbieri-playground/source/browse/dot-files/emacs">Barbieri&#8217;s <code>.emacs</code></a> plus minor modifications &#8212; funny thing is, for some reason I kept using Vim to edit my <code>.emacs</code> file for a few weeks.</p>
<p>Inside Emacs&#8217; <code>M-x info</code> library, there is a nice document, also available on the web, <a href="http://www.gnu.org/software/emacs/emacs-lisp-intro/">Programming in Emacs Lisp</a>. Nice because it explains Elisp but also how Emacs works at the same time &#8212; strongly recommended for those who are starting. Another good resource is Yegge&#8217;s <a href="http://steve-yegge.blogspot.com/2008/01/emergency-elisp.html">Emergency Lisp</a>, which is a good practical summary of the language.</p>
<p>During this process I kept talking to my friends about the new editor (we were all Vim users) and trying to push Emacs into them, too. It worked for at least <a href="http://dropthenumbers.wordpress.com">one of them</a>. He tried a bit, but missed some features from the editor he used to work, Textmate. We both immediatly concluded: <em>hey, Emacs should be able to do everything that Textmate did, and more</em>.</p>
<p>So he <a href="http://obvio171.wordpress.com/2008/04/12/yak-shaving-optimizing-brain-usage-for-code-snippets/">found out about yasnippet</a> that allowed the creation of mini-templates that are triggered by short strings and then using <code>TAB</code> (yes, the guy has two blogs, don&#8217;t ask me why). I ended up trying to solve another problem, which is to automatically insert the closing parenthesis when you insert the opening (abstract this to use with other interesting pairs of characters). It was just using the existing <code>skeleton-pair</code> feature available in Emacs, with a few twists.</p>
<h3>Show me the code</h3>
<p>I&#8217;ll comment on my solution, but you can also grab the raw file <a href="http://cmarcelo.org/code/cgit/playground/plain/elisp/paren-experiment.el">here</a>. By the way, I&#8217;ve used <a href="http://www.emacswiki.org/cgi-bin/wiki/Htmlize"><code>M-x htmlize-buffer</code></a> to create colorized pieces of code.</p>
<p><code></p>
<pre><span style="color:#ff7f24;">;; </span><span style="color:#ff7f24;">Paren experiment
</span>(setq skeleton-pair t)
(<span style="color:#00ffff;">defvar</span> <span style="color:#eedd82;">my-skeleton-pair-alist</span>
  '((?\) . ?\()
    (?\] . ?\[)
    (?} . ?{)
    (?<span style="color:#ffa07a;">" . ?"</span>)))</pre>
<p></code></p>
<p>First we needed to activate <code>skeleton-pair</code>. It&#8217;s part of <a href="http://www.emacswiki.org/cgi-bin/wiki/SkeletonMode"><code>skeleton-mode</code></a>. It allows you to type <tt>(</tt> and get <tt>()</tt> with the point (also known as cursor) positioned inside the parens. Also allows you to selected a region and type <tt>(</tt>, and the region will be inside the parens. In this block we also create a helper association list, that we&#8217;ll be using later.</p>
<p><code></p>
<pre>(<span style="color:#00ffff;">defun</span> <span style="color:#87cefa;">my-skeleton-pair-end</span> (arg)
  <span style="color:#ffa07a;">"Skip the char if it is an ending, otherwise insert it."</span>
  (interactive <span style="color:#ffa07a;">"*p"</span>)
  (<span style="color:#00ffff;">let</span> ((char last-command-char))
    (<span style="color:#00ffff;">if</span> (and (assq char my-skeleton-pair-alist)
             (eq char (following-char)))
        (forward-char)
      (self-insert-command (prefix-numeric-value arg)))))</pre>
<p></code></p>
<p>First real thing is here. We defined a function that accepts one argument. The <code>interactive</code> tells us how we fill the arguments when the function is called via some key or key combination interactively.</p>
<p>At this moment it&#8217;s nice to know that everything you type in Emacs will end up <em>triggering</em> some function. Even simple characters. When you type <tt>a</tt>, Emacs will look in a table and see what function it should call. Normal letters like <tt>a</tt> are bound to the function <code>self-insert-command</code>.</p>
<p>Back to the function: it&#8217;s body is very simple, if the character we typed (given by the <em>global</em> <code>last-command-char</code>) is one <em>closing char</em> present in our association list and the next character is the same, we just <code>forward-char</code>, otherwise, we add the character as usual. The idea is to bind this function to the closing chars like <tt>)</tt> and <tt>}</tt>. That&#8217;s what we do next:</p>
<p><code>
<pre>
(<span style="color:#00ffff;">dolist</span> (pair my-skeleton-pair-alist)
  (global-set-key (char-to-string (first pair))
                  'my-skeleton-pair-end)
  <span style="color:#ff7f24;">;; </span><span style="color:#ff7f24;">If the char for begin and end is the same,
</span>  <span style="color:#ff7f24;">;; </span><span style="color:#ff7f24;">use the original skeleton
</span>  (global-set-key (char-to-string (rest pair))
                  'skeleton-pair-insert-maybe))
</pre>
<p></code></p>
<p>So when you type <tt>(</tt> the function <code>skeleton-pair-insert-maybe</code> takes care, when you type <tt>)</tt> our function will take care of the ending. This gives the first feature over pure skeleton-pair: when you type <tt>(</tt> and then <tt>)</tt> you&#8217;ll end up with the right thing <tt>()</tt> instead of <tt>())</tt> that the plain skeleton pair would give you.</p>
<p>After testing a bit, and showing to others, we realize: if I press <tt>(</tt> and then backspace I would still have the <tt>)</tt> hanging around. Solutions? Well, let&#8217;s rebind <code>Backspace</code> to be smart enough about that, right? Well, that&#8217;s what I did at first: do my thing and call the original bind for backspace <code>backward-delete-char-untabify</code>. It worked&#8230;</p>
<p>&#8230;except when some language mode rebinds backspace, like <code>python-mode</code> because it uses backspace also to walk thru the possible indentations in the code and we would break their binding. And guess what? Lately I was coding mostly in Python. After some research, a solution came up:</p>
<p><code>
<pre>
(<span style="color:#00ffff;">defadvice</span> <span style="color:#87cefa;">backward-delete-char-untabify</span>
  (before my-skeleton-backspace activate)
  <span style="color:#ffa07a;">"When deleting the beginning of a pair, and the ending is next char, delete it too."</span>
  (<span style="color:#00ffff;">let</span> ((pair (assq (following-char) my-skeleton-pair-alist)))
    (and pair
         (eq (preceding-char) (rest pair))
         (delete-char 1))))
</pre>
<p></code></p>
<p>Short explanation: we say that this piece of code will run <em>before</em> <code>backward-delete-char-untabify</code> runs. It does what we need: if we are calling backspace to delete an opening paren and the closing paren is right after, we delete the closing one. After we run, the normal function will run and delete the opening one. Now <code>python-mode</code> or any other mode can rebind backspace as they want, everytime they use the original function, our code will run.</p>
<p>And that&#8217;s how we got the second feature (smart backspace). And that&#8217;s it. Actually after that, experimenting with other modes, like the <code>cc-mode</code> (default for C/C++ files), I discovered that the opening paren (as other opening chars) are binded to <code>c-electric-paren</code> to do indentation as you type.</p>
<p>I didn&#8217;t found an easy way to workaround this like in backspace, because the original function for <tt>(</tt> is <code>self-insert-char</code> but making an <em>advice</em> for this function would make our code run lots and lots of times unnecessarily. The other solution would be to create advices for the <code>c-electric-*</code> functions. But since I&#8217;m not using this smart parens when using C, I didn&#8217;t investigate further, so if you discover another clean way to do this, please tell me.</p>
<h3>Conclusion</h3>
<p>I hope this post could teach you something about Emacs. The code I present here is not very important, but the <em>concepts</em> around it are, for example: the binding of keys to functions in Emacs, or how to improve functions by using <code>defadvice</code>. Just <em>knowing</em> these concepts is already useful: later when you need something similar, you&#8217;ll know where to look. Even better, when solving a problem, you&#8217;ll have new ideas on how to solve it.</p>
<p>I&#8217;m still using this code, not sure for how long. I can say it&#8217;s useful when I&#8217;m coding Python &#8212; with a few exception cases. In other modes &#8212; like when typing normal text &#8212; the <em>smart parens</em> are not very useful for me, and in <code>erc</code> (one way to use IRC inside Emacs) they are even annoying, but that&#8217;s just me. If you try it, comments are welcome. Also are welcome new ideas on how to deal with these problems.</p>
]]></content:encoded>
			<wfw:commentRss>http://cmarcelo.org/blog/2008/04/26/a-little-emacs-experiment/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Hello (again?)</title>
		<link>http://cmarcelo.org/blog/2008/04/22/hello-again/</link>
		<comments>http://cmarcelo.org/blog/2008/04/22/hello-again/#comments</comments>
		<pubDate>Tue, 22 Apr 2008 03:08:50 +0000</pubDate>
		<dc:creator>cmarcelo</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[indt]]></category>
		<category><![CDATA[openbossa]]></category>
		<category><![CDATA[soc]]></category>

		<guid isPermaLink="false">http://cmarcelo.wordpress.com/?p=6</guid>
		<description><![CDATA[Hello, I am Caio Marcelo (in IRC the nickname is cmarcelo) and this is my brand new blog, mostly focused on technology, like many blogs I like to read.
I had a previous attempt, at blogspot, started almost two years ago to talk about my Summer of Code project. And the last post is from one [...]]]></description>
			<content:encoded><![CDATA[<p>Hello, I am Caio Marcelo (in IRC the nickname is cmarcelo) and this is my brand new blog, mostly focused on technology, like many blogs I like to read.</p>
<p>I had a previous attempt, at <a href="http://cmarcelo.blogspot.com">blogspot</a>, started almost two years ago to talk about my Summer of Code project. And the last post is from one year ago. I was very excited about our Free Software group in Unicamp (my university).</p>
<p>Since then, a lot of changes have taken place. I was hired by <a href="http://www.indt.org.br">INdT</a> (Instituto Nokia de Tecnologia) to work as a researcher on the <a href="http://www.openbossa.org">OpenBossa</a> labs in Recife/PE. This was about 8 months ago, when I joined the amazing people in the <strong>Concepts</strong> team and with them helped build <a href="http://openbossa.indt.org.br/canola/index.html">Canola2</a> (and contributed to lots of open source libraries to make it work), a media center for Nokia&#8217;s Internet tablets. After much work we have a great product for the tablets.</p>
<p>Well, that&#8217;s it for now. I have some other posts still in draft about other changes &#8212; the most <em>dramatic</em> being the one about leaving Vim to use Emacs. Let&#8217;s see if this time I keep a good posting rate :-)</p>
]]></content:encoded>
			<wfw:commentRss>http://cmarcelo.org/blog/2008/04/22/hello-again/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
