Archive for September, 2009

Lock Free Multithreading in Qt

Wednesday, September 30th, 2009

If multithreading is challenging to get right in your applications, then lock-free multithreading is down-right killer.

This article won’t go into detail about lock-free algorithms, but instead I will offer a “poor man’s” method for crossing thread boundaries in Qt without using locks (no mutexes, no semaphores). At least, your code won’t have any locks. More on that later.

For years, Qt has sported an easy-to-use threading library, based around a class called QThread. As of Qt4, you can use QThread to start your own event loops. This might sound somewhat uninteresting at first, but it means you can have your own signals and slots outside the main thread. The Trolls created a new way to connect signals to slots such that signals can actually cross thread boundaries. I can now emit a signal in one thread and receive it in a slot in a different thread. This is hugely useful when you want to, for example, integrate a blocking-happy library into your application. Here’s what I’m talking about in pictures:

Signals can arrive at any time from the threads, just like any other signal, and the code in the main event loop doesn’t know anything about multi-threading, locks, or condition variables.

An Example

Let’s say you want to integrate with a third-party library that blocks when you call its functions. Of course, if you call this library from your main event loop, your application will freeze while it’s running. That would be annoying, and you can give your users a better experience than that. Let’s wrap that library in a QThread. First, you need to declare a new QThread subclass, like this:

class MyLibraryWrapper : public QThread
{
Q_OBJECT
public:
    MyLibraryWrapper();
protected:
   void run();
signals:
   void done(const QString &results);
private slots:
   void doTheWork();
};

The run() method is called automagically by Qt when the caller calls start() on your thread. This is similar to how Java’s Thread class works.

The done() signal is how the object tells you it is finished with its work. It emits a QString in this example, but it can emit anything you want (note that if you want to emit non-primitive or non-Qt types, you need to use the Q_DECLARE_METATYPE() macro, which we won’t go into in this article).

The doTheWork() slot is there to actually do the blocking work. It has to be a slot so we can put it to work after our event loop starts up (which you’ll see in a minute).

Now for the implementation of MyLibraryWrapper:

MyLibraryWrapper::MyLibraryWrapper() : QThread()
{
  // We have to do this to make sure our thread has the
  // correct affinity.
  moveToThread(this);

  // This will do nothing until the user calls start().
}

void MyLibraryWrapper::run()
{
  // This schedules the doTheWork() function
  // to run just after our event loop starts up
  QTimer::singleShot(0, this, SLOT(doTheWork()));

  // This starts the event loop. Note that
  // exec() does not return until the
  // event loop is stopped.
  exec();    
}

void MyLibraryWrapper::doTheWork()
{
  // Do the heavy-duty blocking stuff here
  // (simulated by a 5 second sleep for
  // this example)
  sleep(5);

  // When you're done, emit the results:
  emit done("First job's finished.");
  
  // And some more sleeping for fun
  sleep(3)
  emit done("Second job's finished.");

  // ...
}

To actually use this new class, all you have to do is instantiate it in your main event loop and connect it to a slot. Here’s an example. Let’s say you have a QMainWindow called MyMainWindow. This is how you would set it up as a result of a user button click:

void MyMainWindow::on_someButton_clicked()
{
  MyLibraryWrapper *wrapper = new MyLibraryWrapper();

  // This is the magic that tells the wrapper to
  // notify us when it's done. We use a QueuedConnection
  // to make sure Qt delivers the signal in a thread
  // safe manner
  connect(wrapper, SIGNAL(done(QString)),
          this, SLOT(wrapperDone(QString)),
          Qt::QueuedConnection);

  // This kicks off the wrapper's event loop by causing its
  // run() method to be called
  wrapper->start();
}

void MyMainWindow::wrapperDone(const QString &results)
{
  // The wrapper is now done with its long, blocking
  // operation, and we didn't freeze the application.
  // Yay for us!

  qDebug() << "Here are your results:" << results;
}

Conclusion

Notice that none of our code uses a semaphore, condition variable, or mutex? Using QThread makes it super easy to wrap up libraries that need to block the event loop in a way that is transparent to the caller.

I claimed earlier that this code would be “lock free”. I can’t actually claim that is 100% true. I don’t know for sure, but I imagine that Qt’s internal event loop code does indeed use locks to pass signals between event loops. All I know for sure is that this code crosses thread boundaries without any locks.

Stay tuned for another article that shows how you can call setter functions on your threaded objects without any need for locks.

Model/View/Presenter and Qt?

Sunday, September 27th, 2009

Here’s a question for Qt hackers:

Does Qt implement the Model/View/Presenter design pattern?

The short answer is (drumroll): it depends on some stuff. Let’s dive into it and give you a real answer.

First of all, I am no Model/View/Presenter expert. I’ve only read what little information is available online, and I’ve never implemented an application with it (though it turns out that I’ve been using it for years on accident). Bottom line: Please correct me.

If you search the Qt documentation, you won’t find any mention of this design pattern (although the more prevalent Model/View/Controller does make many appearances).

Before we start, we should define Model/View/Presenter. The MSDN and Wikipedia summarize it thus:

  1. It is a multi-tiered design pattern that helps separate display logic from business logic in a testable way.
  2. The View is kept as thin and ignorant as possible
  3. It enables better automated unit testing (and helps prevent relying on awkward UI test runners)
  4. It moves lots of logic out of the View and into the Presenter (things like input validation for example)
  5. The Presenter should be common to multiple views (though I’m not totally sure on this one — please correct me)
  6. Methods in the Presenter should not return a value (i.e., void) and should take no arguments.

Let’s look at a typical Qt application. I like to use Qt Designer to design as much of my user interface as possible. Doing so, my source code tends to look like this:

Qt veterans should be able to identify the boxes in this graphic quickly, but for those of you who don’t work in Qt every day, let me explain.

Your Data Model

The data model is a class (or set of classes) that provides access to your app’s data. It emits signals to tell you when its data has changed (like if another app changed the data), and provides slots you can call to change the data yourself. You may have, for example, a list of User objects in your app, and maybe they are all contained within a UserModel class. When a user’s phone number changes, your model may emit a signal called phoneNumberChanged(). If a new user is created, the UserModel would emit something like userAdded(User*) and likewise userRemoved(User*) when a user goes away.

Your Widget Subclass

When using Designer, you have to choose a QWidget-derived class from which your widget will inherit. Your widget may be a dialog, a main window, or even a nested widget inside some scroll box. Your widget subclass will usually connect to the data model’s signals (userAdded(), userRemoved(), and friends). Its job is to notice when the data model changes, and represent that on the screen by manipulating the view. It is also responsible for taking user input and pushing it into the model (like when the user wants to change a User‘s phone number, for example).

Generated UI Class

When you create and save a form in Qt Designer, it gets saved with a .ui extension. This file actually contains a bunch of XML that describes how you laid stuff out on the screen. Qt provides a tool called uic that takes that XML file and produces C++. uic stands for User Interface Compiler. The code that it generates is the view. It only does one thing: Draw crap on the screen, and tell you when the user does stuff. It is an extremely thin UI layer. So thin in fact, that it cannot implement any business logic at all. It’s simply not possible. The code is generated and unalterable (unless you’re an idiot and think it’s okay to go hack that code after it’s generated — hey, I’ve done stupid stuff too).

Now let’s apply some labels to our diagram:

I believe the widget subclass actually does conform to all the rules of a Presenter, even though it doesn’t conventionally bear that name. Let’s look at the rules again and see if it fits the bill:

  1. Separates display logic from business logic: Yes
  2. The View is thin and ignorant: Yes
  3. Enables automated unit testing: Yes (you can write unit tests against your widget subclass quite easily)
  4. It moves UI-related logic out of the View into the Presenter: Yes In fact, the View can do almost no input validation at all (unless you specify inputMasks in Designer, and note that QValidators are instantiated in the widget subclass).
  5. The Presenter should be common to multiple views: No Qt could allow this, but most people just don’t do it (perfectly possible, but I’ll discount it because it is not used in practice or recommended in the docs).
  6. Methods in the Presenter should not return a value: Yes Your widget subclass’s slots have to be void (and even if you do specify a return value, Qt ignores it anyway, so Qt actually enforces this requirement).

Conclusion

Qt can most definitely implement Model/View/Presenter, and in fact, the Qt documentation recommends exactly that, though they never use the term “Presenter”. You should probably also read up on the Model/View/Presenter’s latest development, since some argue that the term ought to be retired and replaced with new terminology, which coincidentally fits even better with Qt conventions.

What do you think? Does Qt actually implement this Design Pattern? It’s pretty important to recognize this stuff, or we can end up screwing up pretty bad.

Qt Stylesheet Sidebar Tutorial

Friday, September 18th, 2009

In some applications, a nice looking sidebar can really add some polish. In this tutorial, we’ll show you how to make a sidebar using nothing but Designer and Qt’s stylesheets. When we’re done, we’ll have this:

Step 1 Open Designer and create a new widget for your app. Enjoy the blank slate for a moment. When you’ve had enough zen, move on to step 2.

Step 2 Drop a couple QFrames onto the widget.

Step 3 Apply a horizontal layout to your widget (click on the background and then click the horizontal layout button in the toolbar). Then give the left-hand frame a maximum size of 200. This will become the sidebar and we don’t want it to occupy half of the screen. You may have to tweak this in your application depending on your user’s font size.

Step 4 Name your left-hand frame “sidebarFrame” and then add this stylesheet code to your widget (right-click on the top-most node in the Object Inspector and select “Change styleSheet…”).

#sidebarFrame {
background: #8af;
border: none;
border-right: 1px solid black;
}

This gives the sidebar a blue background and a single-pixel black border between it and the application’s main content area, like this:

Step 5 Drop a QFrame inside the sidebarFrame on the left.

Step 6 Add a custom property to the new QFrame that you just dropped on the widget. Do this by clicking the green “plus” sign in Designer’s property editor and picking “String”. In the popup dialog, type the word “class” (without quotes). By doing this, we are giving this widget a custom property named “class”. In the property editor, type the word “SidebarFrame” for the “class”. This should appear at the very bottom of the property editor.

After giving your new frame a class, add this style sheet code to your stylesheet:

QFrame.SidebarFrame {
border-top-left-radius: 10px;
border-top-right-radius: 10px;
border: 1px solid black;
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0 #56a, stop: 0.1 #016);
}

Now you should have this:

Step 7 That forms the outside of the frame. Now we’ll do the interior. Drop a QLabel and a QFrame inside your new QFrame, like this:

Step 8 Give the inner QFrame a custom “class” property of “SidebarInnerFrame”, and add this style sheet code:

QFrame.SidebarFrame QLabel {
color: white;
font-weight: bold;
}

QFrame.SidebarInnerFrame {
background: white;
border: none;
border-top: 1px solid black;
}

That will stylize the QLabel (which will be the title label for this box) to give it white, bold text. It will also stylize the inner frame to be white. You should have this now:

Step 9 Now layout your box by clicking on the box and then clicking the vertical layout button. Afterwards, give it the following spacing and margins in the “Layout” section of the property editor:

layoutLeftMargin 0
layoutTopMargin 5
layoutRightMargin 0
layoutBottomMargin 0
layoutSpacing 5

Having done that, you should see this:

Step 10 Drop some checkboxes or something inside your box and lay them out vertically (do this by clicking on the inner frame and then clicking on the vertical layout button). Then click on the light blue sidebar frame and give it a vertical layout. Insert a vertical spacer in the bottom, and you should see this:

Step 11 Now that you have your styles and layouts in place you can copy and paste the sidebar boxes to your heart’s content. You can name them whatever you want because we are using the “class” custom property to stylize them. These boxes can contain any widgets you like.

As an exercise for the reader, figure out why you can’t read the text of QLabels when you drop them inside these boxes.

Enjoy your finished product:

I am consistently impressed at how powerful Qt’s stylesheets are. You can do some really neat things with very little effort, all in a friendly WYSIWYG environment.

Happy hacking!

Qt Stylesheets Button Bar Tutorial

Thursday, September 17th, 2009

To demonstrate the awesomeness of Qt’s stylesheets, we’ll make a modern looking button bar (inspired by Qt Creator) that looks like this:

Let’s get started

Step 1 Open Designer and create a new empty widget:

Step 2 Toss a couple QFrames on the widget, one above the other. Name them topFrame and bottomFrame, like this:

Step 3 Apply a vertical layout to your widget (just click on the background area and then click the vertical layout button in Designer’s toolbar. It should look like this now:

Step 4 Drag and drop a few buttons and a horizontal spacer onto the frame you called “topFrame” (don’t forget to name it if you haven’t already)

Step 5 Apply a horizontal layout to the “topFrame”

Step 6 Set the vertical size policy for the “topFrame” to “Fixed”. This makes it shrink to a minimum size and lets the bottom frame grow to fill the rest of the widget.

Step 7 Set your margins and spacings to 0 (do this by clicking on the background and at the bottom of Property editor you’ll find the “Layout” section which lets you specify this stuff).

Step 8 Add a style sheet to your widget (right click on the top-most entry in the Object Inspector and select “Change styleSheet…”). Put this style in there for now:

#topFrame {
border: none;
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0 #a6a6a6, stop: 0.08 #7f7f7f,
stop: 0.39999 #717171, stop: 0.4 #626262,
stop: 0.9 #4c4c4c, stop: 1 #333333);
}

#bottomFrame {
border: none;
background: white;
}

That will give the topFrame a nice modern background that looks like this:

Step 9 Now stylize the buttons. Add this to your stylesheet:

#topFrame QPushButton {
color: #333;
border: 2px solid #555;
border-radius: 11px;
padding: 5px;
background: qradialgradient(cx: 0.3, cy: -0.4,
fx: 0.3, fy: -0.4,
radius: 1.35, stop: 0 #fff, stop: 1 #888);
min-width: 80px;
}

#topFrame QPushButton:hover {
background: qradialgradient(cx: 0.3, cy: -0.4,
fx: 0.3, fy: -0.4,
radius: 1.35, stop: 0 #fff, stop: 1 #bbb);
}

#topFrame QPushButton:pressed {
background: qradialgradient(cx: 0.4, cy: -0.1,
fx: 0.4, fy: -0.1,
radius: 1.35, stop: 0 #fff, stop: 1 #ddd);
}

That style sheet makes the buttons have rounded corners, a nifty radial gradient background, and modern hover and click effects, like this:

Now press Ctrl+R and view the finished product:

Aren’t Qt stylesheets awesome?

Qt Stylesheets Tutorial

Thursday, September 10th, 2009

Stylesheets add spicy flavor to your boring Qt GUIs.

For a long time, Qt has allowed you to decorate your GUIs with CSS’ish style sheets. Inspired by the web, stylesheets are a great way to stylize your Qt GUI, but it seems that few people use them. In this tutorial, we’ll create an example dialog in Qt using Designer and stylesheets. This tutorial assumes that you can get around in Qt Designer, and that you understand a little about Qt layouts.

Step 1 Create a new empty form, named MyLoginForm.

Step 2 Add a QFrame to your form, and apply a vertical layout to your form (any layout will work actually: vertical, horizontal or grid). Give your form about 30 pixels of layout margin around its perimeter. Name the QFrame “mainFrame”. When dealing with stylesheets, it’s convenient to name your widgets in Designer, even if you don’t plan to use them by name in your code (we won’t be writing any code besides CSS in this tutorial).

Step 3 In Designer’s object inspector, right-click on the top-level entry in the tree (called “MyLoginForm”), and select “Change styleSheet…” from the menu. You’ll get a little editor dialog like this:

This is where we specify the style sheet for our form. You can put a style sheet on any widget in your form, but I prefer to do all my stylizing at the parent widget (“MyLoginForm” in this case). I prefer to do it this way because you’ll never have to go hunting to find your style sheet — it’s all in one place in your form. Since stylesheets cascade down to the child widgets, you can stylize any widget in your form from this point.

Side note: “CSS” stands for “Cascading Style Sheets”

Let’s type in some CSS into the style sheet editor, like this:

#MyLoginForm {
background: gray;
}

#mainFrame {
border: 3px solid gray;
border-radius: 40px;
background: white;
}

After clicking OK on the editor dialog, you should see this:

If your’s doesn’t look like this, you may have forgotten to change the parent widget’s name to “MyLoginForm” or the QFrame’s name to “mainFrame” (yes, capitalization does matter — Qt stylesheets are case sensitive). Or you may have mistyped something into the CSS dialog.

One cool feature is that you get to preview the style changes right as you make them. You don’t have to compile, save, or run anything. Designer does a very good job of showing your stylesheet changes live (WYSIWYG for you old-timers).

Let me explain what we just did. In CSS, a pound sign, ‘#’, in front of a name is how we stylize an individual widget by that name. In our example, #MyLoginForm identifies the parent widget (i.e., the background area). All we did there is give it a gray background with background: gray;.

For #mainFrame, we gave it a thick gray border, a white background, and rounded corners.

Step 4 Let’s add some widgets to make this dialog actually do something. Drag and drop a pair of QLineEdits, QLabels, and a single QPushButton on the form inside “mainFrame” and arrange them roughly like this:

Step 5 Now apply a grid layout to “mainFrame”. Just select “mainFrame” by clicking on it (taking care not to accidentally select one of the QLineEdits or QLabels instead). Then click the grid layout button in Designer’s toolbar (optionally, you can go to the menu bar and click “Form” -> “Lay Out in a Grid”, or just press Ctrl+5 for you keyboard hackers).

Then give your layout some margin. I used 50 pixels of margin and 15 pixels for both vertical and horizontal spacing.

This is what you should have now:

Step 6 Let’s stylize those boring QPushButton and QLineEdits. Add this to the style sheet for MyLoginForm:

QLineEdit {
padding: 1px;
border-style: solid;
border: 2px solid gray;
border-radius: 8px;
}

QPushButton {
color: white;
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #88d, stop: 0.1 #99e, stop: 0.49 #77c, stop: 0.5 #66b, stop: 1 #77c);
border-width: 1px;
border-color: #339;
border-style: solid;
border-radius: 7;
padding: 3px;
font-size: 10px;
padding-left: 5px;
padding-right: 5px;
min-width: 50px;
max-width: 50px;
min-height: 13px;
max-height: 13px;
}

Notice that we didn’t use the pound sign this time. When you omit the pound sign, you are specifying a “class” of widgets to stylize instead of a single widget by name. So in this case, we stylized all widgets of type “QLineEdit” and “QPushButton” (and any widget that may inherit from those widgets too).

That gives the QPushButton a cool gradient look and rounds the edges of the QLineEdits, like this:

Step 7 Now let’s make that boring white background a gradient instead. Replace the “background: white;” line in the “#mainFrame” section with this instead:

background: QLinearGradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #eef, stop: 1 #ccf);

Now you should see this:

Step 8 Since stylizing is all about detail and little tweaks, let’s mess a bit with the label font and the background color by changing the background for “#MyLoginForm” to “background: white”, and adding this:

QLabel {
font-weight: bold;
font-size: 15px;
}

Now we get our finished product:

Isn’t it great how much you can do in Designer with style sheets? There are even things you can do with style sheets that can’t be done without writing lots of yucky C++ code. For example, you can change the border style of just a single side of a QFrame.

Oddities

There is one gotcha to keep in mind when using style sheets: Once you use a style sheet, it will often override other properties, like the “font” property or the “frameStyle” property. Keep this in mind when Designer changes properties you didn’t expect.

The other oddity with style sheets is that there’s no way to “include” external style sheet files into your widget’s style sheet. This means that you can’t have a common style sheet that gets applied to your entire application like you can in the web. I have a Qt patch that allows you to do this, but so far the Trolls haven’t done anything with it (to my knowledge). This would be immensely useful.

Cross Platform Note
A style sheet tutorial wouldn’t be complete without a comment on cross-platform issues. The dialog we just designed will look exactly the same on Linux, Windows, and Mac OS X because we stylized it so aggressively. If you want your widgets to look native on each platform, you should generally use style sheets sparingly, but if your goal is to have a consistent look across all platforms, style sheets are your best friend.

Conclusion

Now that I have discovered the power of style sheets in Qt, I use them whenever possible. What cool things have you done with Qt style sheets?

Mozy Woes on Mac

Friday, September 4th, 2009

Mozy has been working fine on my Mac for about 6 months (aside from the massive memory usage it requires during backup), but starting about a week ago, I can’t make Mozy finish (or even start) a backup. I’ve tried uninstalling it, removing all configs, reinstalling it, using the shipped config defaults, and I still get this error in /Library/Logs/Mozy.log:

INF (backup) Starting backup
INF (backup) Using 108.7 MB of memory
INF (backup) User ID is [snipped for paranoia's sake]
INF (backup) Checking for update
INF (backup) Connecting to [snipped for paranoia's sake]
INF (backup) Version is up-to-date (1.4.3.3)
INF (backup) Adding new history entry
INF (backup) Cleaning up temporary files
INF (backup) Loading encryption key
INF (backup) Loading machine information ...
INF (backup) Connecting to [snipped for paranoia's sake]
INF (backup) Loading configuration from the server
INF (backup) Connecting to [snipped for paranoia's sake]
INF (backup) Fetching the manifest hash from the server
INF (backup) Connecting to [snipped for paranoia's sake]
INF (backup) Server version is 1.3.0.19
INF (backup) Building backup set
ERR (backup) Churn is not running, exiting backup
INF (backup) Cleaning up, finishing
INF (backup) Updating existing history entry
INF (backup) Finished backup (Client error)
INF (backup) Backing up history
INF (backup) Using 108.9 MB of memory
INF (backup) Ending backup

Sometimes I see this as well:

ERR (churn) Failed to scan files, stopping: database is locked

What is “Churn”? What database is locked? I am running Time Machine as well. Does that matter? Any ideas out there? I know some of you used to work at Mozy. Does any of this ring familiar?

On another note, does anyone else notice that Mozy Backups take a lot of memory on Mac OS X?


(click for bigger picture)

Mozy sits this way for hours on my Mac in the rare cases that it does actually get a backup started.