December 10, 2009

Flash in QGraphicsView

Over the past couple of months, I have been working losing sleep over getting Flash to work in QGraphicsView on all platforms.  The good news is that flash now works in QGV on all platforms. Yes, that means that not only can QGV display Flash but can also rotate and transform flash when using QGraphicsWebViewIMPORTANT: Flash embedded in a QWebView using QGraphicsProxyWidget is NOT supported.

Youtube in QGVLauncher
Youtube in QGVLauncher

What follows is a brief summary of my work and the list of patches that you will need to get Flash working with Qt 4.6.0. Note that when I say plugin below, I mean NPAPI plugins like Flash. They have nothing to do with QWidget based plugins. QWidget based plugins should work in Qt 4.6.0 when using QGraphicsWebView. I have also simplified the concepts (in favor of being completely correct) in the post below so that it is readable.

Windowed and Windowless plugins

Flash gets embedded into web pages using an API called NPAPI (Netscape Plugin API). NPAPI provides two mechanisms to embed plugins into a web page – Windowed mode and Windowless mode.

Windowed mode – the idea is that the plugin gets a native widget handle and does it’s own mouse, keyboard processing. For example, on Windows, we give the plugin a HWND. The plugin will install a window proc and process events directly (i.e the events are never seen by the browser). On X11, the plugin embeds itself into the Window using XEmbed. When the browser scrolls, the browser moves the native window appropriately. Mac doesn’t support windowed mode.

Windowed mode should have been enough but it has a limitation that it interferes with the z-ordering of html elements.  Some sites like to put html _over_ their flash content (for example, menus). This can be achieved by making the menu html have a higher z-order than the plugin. Can you spot the conflict interest here between z-ordering of native widgets and z-ordering of HTML elements? The plugin native window is a child of the browser’s window and we have a situation where the browser wants to paint HTML after the child has painted itself! This is not possible since a parent window always draw before it’s child. There are other disadvantages too – it is also impossible to transform plugins (native widgets are rectangular), making them transparent is tricky and printing plugins requires lots of hacks.

Windowless mode – The idea here is that plugins just paint to a pixmap – platform’s graphics context to be more precise (HDC on Windows, Pixmap on X11, ContextRef on Mac). It is now the browser’s responsibility to pass (forward) mouse and keyboard events to the plugin. Since the browser now contains a screenshot/snapshot/pixmap of the plugin, the browser can transform plugins, draw it in the correct z-order, make is transparent even. The main disadvantage here is that it can tend to be a bit slow.

Evan has a better explanation of the modes. There’s also one by Robert from which I originally learnt about these modes but I cannot find the link anymore).

Flash

I keep saying Plugin but really we care only about Flash ;-) At least, for the moment that is our priority. All version of Flash supports Windowed mode. Only Flash 10 supports windowless mode on linux.

Flash lets the html/plugin author control the mode of operation using the wmode parameter (i.e pass it as part of html <object> tag). By default, it operates in windowed mode. Setting wmode to ‘transparent’  makes the html below visible through the flash. If wmode is set it to ‘opaque’, the html will not be seen through and the flash will have some solid background color (think of it as Qt::WA_OpaquePaintEvent, it allows for optimizations). transparent and opaque mode are implemented using ‘windowless’ mode. Here’s a great site to test out these modes in action.

Important: When in windowed mode, Flash expects a native window handle/id. A browser cannot force windowless mode – the mode is decided by the plugin. A browser can, in theory, say that it supports only windowless mode but this makes Flash crash (at least) on Linux. Hence, when we have a site like youtube (which uses Flash in windowed mode) in QGV, we need to come up with a way of providing flash with a window handle. There are two ways to deal with this problem – we can either give Flash a fake native window, we then grab the contents of this fake native window and paint it wherever we want OR we can inject the wmode ‘opaque’ parameter when loading flash in QGV. The former approach is platform specific and requires lots of work. The latter is a 10 line patch.

Plugins in QGraphicsView

Items inside QGraphicsView are not native widgets. They are just items on a canvas that can be transformed and visualized using multiple views. This means that windowed mode of plugins is not feasible (apart from the fact that we have no native widget handle for items on canvas). To make plugins work in QGV, we need to implement windowless mode.

X11 (Linux)

Windowed mode on Linux has already been implemented in Qt 4.5. What was missing is the windowless mode support. One nice feature is that Flash is able to fall back windowed mode when the browser says it cannot support windowless mode (vice versa crashes as I noted before). This is the reason that sites that use windowless mode work in QWebView with Qt 4.5.

To support Flash in QGV, I started out adding windowless mode support. In theory, implementing windowless mode is a matter of passing a X Pixmap to the plugin, but there were lots of problems. The entire history is on bugzilla bug 20081.

  • Flash uses a different X Display connection – the default one provided by gtk/gdk and not the one that Qt provides it. Ouch. This means that when flash paints something, we have to XSync to get changes reflected in the Qt connection and vice versa. The uglier part is that Qt somehow needs to get hold of gdk’s Display without linking to gdk. It’s all very hairy. (r49158).
  • Flash uses a different X Visual (the default system visual) rather than the one provided by Qt. This means that even if we created a 32-bit pixmap, Flash won’t be able to draw into it because it uses a 24-bit visual. Since people really wanted transparency to work, the solution is to grab the contents of the backing store to fake transparency. Very hairy stuff. This solution works in QWebView but not with QGraphicsWebView (r49169). We have turned off transparency in QGVuntil this Flash bug is fixed.
  • The NPAPI requires X Pixmap. QPixmap may or may not be backed by a X Pixmap depending on thegraphicssystem.
  • Print preview implementation of Qt holds a reference to the X Pixmap (because of QPicture). This meant that when the user prints we have to ‘let go’ of the X Pixmap because the print preview has to remain unaffected by on screen changes. At the same time, someone needs to destroy this X Pixmap when the print preview dialog close. This one was very tricky to solve. Actually, I didn’t solve it, Samuel did :-) (r50123)

All windowless mode changes for Linux are part of Qt/WebKit 4.6. QGV on linux can display Flash only in windowless mode. If Flash is in windowed mode (like in youtube), it does not work.  As mentioned there are two methods to fix windowed mode in QGV . Method 1 – we create a fake window and grab it’s contents. This can be achieved using X Composite and X Damage (as done in Fennec). I have a patch at 31232 but it requires more work. Method 2 – we can inject wmode opaque. This has been committed as part of 32059. If you need youtube to work in QGV, you need to apply that the patch r51759 on top of Qt 4.6.0.

Mac OS X

On the Mac, plugins operate in Windowless mode _always_.  There is no such thing as windowed mode on the Mac. NPAPI  on Mac supports various event models and painting models. Event model dictates how we pass the mouse/keyboard events to Flash (i.e which data structure is used to report events – NSEvent or the classic EventRecord).  Qt/WebKit only supports only the carbon event model and the CoreGraphics drawing model (there’s a open gl drawing model, core animation and a QuickDraw drawing model). ATM, only Carbon based apps can display flash. Qt/Cocoa apps (32 or 64 bit) cannot display Flash in QWebView or QGV. (Confusingly, this has nothing do with Qt/WebKit not supporting cocoa event model. It is possible for Qt/Cocoa apps to display using the carbon event model. This is tracked using 32376)

Now to the carbon event model – how it works is that the browser provides the plugin it’s window handle (a WindowRef), a ContextRef and the position (a rectangle) inside the window and Flash draws itself there.

Simple, no? You wish :-) Unlike in QWebView, one cannot provide a rectangle as the position of Flash since the Flash could be transformed. For those new to Mac, ContextRef is like a QPainter (it can be over any paint device – a widget, pixmap, image). What we do is to get the ContextRef of a QPixmap and pass the position as (0, 0, width, height). Unfortunately, Flash requires the WindowRef parameter to be valid because it seems to be using it to detect if the window is ‘active’ for processing mouse move events. To workaround, we create a fake hidden window. In addition, we also fake the fact that this fake hidden window is the active window (else Flash won’t process mouse move events)! If you thought this was insane, you should check out what the chrome devs do (they intercept carbon calls of Flash by injecting a library using DYLD_INSERT_LIBRARY at runtime). See 311833179431979 for more history.

None of the patches are in Qt 4.6.0. You need to apply  r51234 for painting; r51105r51412 for mouse handling andr51485 for context menu position. Currently, printing does not work on the Mac. This is tracked at 31975. Flash transparency works fine in QGV.

Windows

Windows has always supported Windowed and Windowless mode (Thanks to Apple). Printing already works thanks to some awesome hacks. Flash transparency works in QGV. However, the problem (as mentioned above) is that Flash expects a HWND when in windowed mode. So, youtube inside QGV requires a HWND. Fix is to inject wmode opaque. You need to apply r51979 on Qt 4.6.0

Symbian

The hardwork here was done by Yael. See 29302 for more details.

Gitorious

I have done the necessary cherry-picking and published a branch (based of 4.6.0) athttp://qt.gitorious.org/~girish/qt/girishs-qt/commits/4.6.0-gv-flash. With that branch, Qt should support Flash in QGV on all platforms in all modes.

More information

If you need more information on internal working of plugins, Yael, Torarne and I have writtenhttp://trac.webkit.org/wiki/QtWebKitPlugins. Drop by on irc channel #qtwebkit on freenode for any clarification. Performance needs some love, we are working on it.

My work would not have been possible without the tireless reviews of SimonHolgerKenneth. Thanks guys! Simon, in particular, who  kept pushing me to try out various possibilities/hacks. I cannot thank him enough! And it’s a matter of great pride that I am now a webkit commiter! :-)

The guys at Linden Lab have made ubrowser support Qt/WebKit (llqtwebkit). With the above changes, flash works in ubrowser.

Qt/WebKit in ubrowser

November 21, 2009

Qt DevDays 2009 SFO

(A very late update on DevDays 2009 SFO. I am one lazy blogger)

In an unexpected twist of events, I ended up attending Qt Developer Days at SFO. I had just one week to get my visa, flight and hotel bookings in place, so I wasn’t too hopeful. Amazingly, I got my visa interview appointment in 2 days  and received the passport by courier in another 2 days! Also, the chennai embassy didn’t have any long queues that every indian so dreads. Either the U.S.A visa process has made giant leaps or it’s the downturn .

1. Sebastian Nyström talked about Qt being everywhere and that it was being used by Google, Skype et al. One of the slides showed a screenshot mashup of ‘cool’ Qt applications. I was pleasantly surprised to see Hyves Photo Uploader in there :-) Slides here (slide 11, we have the highest z-order even)

2. Tapani Mikola mentioned the ‘death of widgets’ in one his slides when presenting QML. QML is awesome and the talk was excellent but I am a bit saddened by the ‘death of widgets’ phrase – as much as I like all the new developments, qgv is no where near providing all the ui elements required to develop applications on the desktop. Ask an app developer, he will give you many examples of widgets that Qt lacks. When was the last new widget that was added to Qt, that made you go ‘nice!’ or ‘finally!’? Maybe I am reading too much into the phrase ;)

3. Meeting up with old friends made me really miss Norway and the oslo development team :(

4. Major shortage of Qt developers – I lost count of the number of people looking for Qt developers and consultants. The interest in Qt has exploded after Nokia has taken over. I have been in 2 dev days as Trolltech employee before and it was nothing like this. It was crazy, a few people had signed up for the conference only to hire more developers/consultants. Funnily, I even ended up getting two job offers with no interview! If you are a Qt developer and out of job, you are not looking at the right places. On the topic, we are still hiring.

5. Qt Certification at SFO didn’t see as much participation as munich, but Vladmir thought it was up to a great start. Roop and I are Qt Certified even :)

If you missed Dev Days, be sure to plan on being there the next time (the munich event was even bigger and had 700 delegates). If you want to keep up with the trends in Qt development, there is nothing like meeting the people who are making the change. You just cannot afford to miss these events.

November 9, 2009

~/research cleanup (part 2)

Final part of my ~/research cleanup

1. slidelistviewselection – A widget in which item selection moves with animation from one item to another. I made this initially for an embedded device on which itemviews was too heavy.

2. skinnable mediaplayer – An example that shows how to create a skinnable Qt app (see my old blog post).

3. bubblelist – An example of how one can create a scrollable item in graphicsview (like QScrollArea which scrolls  i.e positions a big widget)

4. lineeditwithclearbutton – Line edit with clear button (see my old blog post)

http://labs.trolltech.com/blogs/2007/06/06/lineedit-with-a-clear-button/

October 6, 2009

~/research cleanup

A habit that I picked up from my job at Trolltech was to put all my experimental code in a directory called research. Each project gets its own sub-directory there. We used to also have a similarly named folder in p4 depot and it was totally unmanageable. I wonder what happened to all that code after they moved to git – there were hundreds of very interesting code samples there.

Back to me, over the years (yeah, like past 4-5 years), I have abused my research directory for examples, bug reports, writeups, screenshots/videos, blog posts and I thought it’s about time I clean it up :) . I have been cleaning up 10-15 subdirectories a day for the past week (I have ~100 more to go) and I have to admit I grossly overestimated the value of the stuff in there :) . But here’s what I found worth sharing so far (all of them are Qt examples, of course):

  • customfont – How to load and use custom fonts.
  • mplayerembed – How to embed mplayer into your app and control movie play (X11 only)
  • customnetworkreply – This lets you create custom url’s inside qt/webkit. For example, you can embed a myapp://give/me/some/stuff or a http://myapp/foo.png. Code inspired from assistant.
  • textlayoutprimer – I wrote this one when I was trying to understand how laying out text works inside QTextEdit (using QTextLayout). More didactic than an usable example.
  • translucentbackground – Translucent background example (Uses ARGB visuals, requires composition manager)
  • clipboardwatcher – Displays content of clipboard/selection as they change. Very useful to test dnd. I think I stole initial parts of the code from a similar Qt example.

I am still figuring what is a good way to maintain all this sample/throw away code. I also have ~/tmp where I have code that I can nuke without any thought. Any suggestions? What do you do? A problem I have had is I never manage to find the right code samples when I need them. I have already found many dups when cleaning up!

September 22, 2009

Displaying html with animated gifs

When consulting for Hyves, we wanted a light-weight widget that displays html and animated gifs (for smileys) for the chat client and for tooltips. The option to use Qt/WebKit was out since we intended to create numerous instances of this widget (it consumed lots of memory) and the rendering was not as fast we would like. QLabel does not support animated gifs, so that was not an option either.

Instead of writing a basic html parser, layouter and renderer, I thought I can somehow trick QTextDocument into displaying animated gifs. You can see the basic idea in this kb but to get it working with animations wasn’t easy. One good thing about adding the feature to QTextDocument is that you can set it on QTextBrowser and QTextEdit.

Without further ado, get the code here. Label is a richtext label that does not support links or selection. TextBrowser is a browser that supports selection and links. TextEdit is an editor with support for undo/redo.

P.S. Thanks to Hyves for making it possible to actually publish this code; they released most of their code as GPL.

September 18, 2009

Non-selectable QWebView

There are situations where you don’t want text to be selected and images to be dragged in your QWebView (See my previous post). Qt does not provide support out of the box, but this is fairly straightforward to do. I wrote a quick hack to demonstrate, get it here.

September 16, 2009

KDocker 4.0 released

Almost a year back, I was looking for a maintainer for kdocker. I had practically given up, when out of the blue John contacted me to be the new maintainer. What more, he had already ported it Qt4! That made handing over maintainership to him a no-brainer :)

Also, KDocker is now moved from sourceforge to launchpad. Once I regain access to sourceforge, I will update the sourceforge page.

Read the release announcement here. If you are interested in helping  out with translating the app, please contact John.

September 12, 2009

Side effects of using QtWebKit for desktop apps

Integrating the web into desktop apps is now incredibly easy thanks to Qt WebKit.  Qt WebKit also allows us to embed any Qt widget inside the html. This feature makes it extremely tempting to develop full blown desktop applications using Qt WebKit – your interface is entirely designed using html/css (instead of .ui) and you as a C++ developer decide what parts are best done in Qt/C++ and embed them into the html page.

The above scheme works very well (for the most part). However, there are a lot of features that make our applications feel native, that we take for granted in desktop apps when using Qt/C++ but not so when using Qt WebKit. So here is a list of short comings that you should know about.

1. Focus handling - Tab focus  doesn’t work at all when navigating from html into a c++ plugin and vice versa.

2. Keyboard accelerators - In html, you can specify accelerator using ‘accesskey’. They don’t seem to work in QtWebKit. They do work in google chrome, so must be something to do with the Qt port.

3. Text can be selected and images can be dragged – Your main ui is html, what did you expect :) ?

4. Plugins will get deleted if you hide them – If you hide your C++ plugin/widget using ‘display: none’, Qt/WebKit will delete it. In your traditional Qt program, all your data is part of the widget – now it’s all gone. To prevent this, you have to write all your widgets to use the model-view paradigm. An alternative is to use ‘visibility: hidden’ which won’t delete the plugin but the plugin will continue to hog space in the layout. Side note: In Qt 4.4.x, plugins weren’t deleted (aka leak). Starting Qt 4.5.x, they were deleted – we found this problem when our app starting crashing gloriously when we moved to Qt 4.5.x.

5. Fluid layouts - When the windows resizes, UI elements inside are expected to reposition and resize nicely; the window must have a nice minimum size – that is all done by QLayout does. This is really hard to get right when using html. You will most likely end up writing js layouting code.

6. Moving data back and forth is slow – Passing Qt types from C++ to JS works very well using QJson. Converting complex types like a QPixmap to html img is really really slow, since you have to convert in into png first. Also, using this method crashes Asus laptops/Windows, probably some graphics card issue, nevertheless your app has to deal with it.

8. RTL – Qt will layout your widgets automatically when your app is run in a RTL environment. With HTML, you will have to provide an alternate html file, do your own RTL detection, implement sizing fixes to elements for different languages and so on.

9. Translations – Qt provides you linguist, lrelease, lupdate. When using HTML, you will have to roll out your own translation framework (this is an awful lot of work).

10. Misc – There are other minor problems depending on your Qt version - the default fonts of html and qt didn’t match. There was a time when a 12pt font of Qt and 12 pt font of webkit don’t match (this seems to be fixed now). Displaying plugins inside divs had some artifacts.

Note that the above is not a case against using Qt/WebKit for developing desktop apps since they can all be worked around. It’s more for you to know what you will be up against if you decide to go down this road.

Update 1: Added note on rtl and translations

September 4, 2009

We are hiring!

It’s been a year and a half since my good friend Roopesh and I started this company, ForwardBias Technologies.  Starting our own business has been nothing short of exhilarating and fabulous.  Estimating turnover, pricing, talking to customers, deciding company vision/direction is all very very thrilling!

Since inception, we have been focusing our energies on Qt consulting. We have managed to carve a nice niche for ourselves in “high end” Qt consulting market – we have developed paint engines (yes, plural!), custom styles, a really cool full blown webkit application (which we will blog about shortly), hacked on koffice (for only a short while, unfortunately) and a lot more. I think I can safely say that our customers are enthralled with our work – every one of them has offered us more work.

And, we are also working on our hush-hush product in parallel. And despite me saying it’s all very exciting and fun, we are also getting a wee bit exhausted with all the action. It’s just two of us and we need more people!

So, am very happy to say, we are hiring! We have spoken our hearts out in that page and what we would like to repeat is that this is a company made for developers by developers and we are looking for fearless programmers – our customers and product requires one to constantly learn new things on the job and become good at it very fast.

And of course, some bonus points if you are already know KDE/Qt development.

October 21, 2008

Tata Wimax keepalive

My tata wimax connection works well most of the time but it has a supremely annoying feature that to get connected, one is redirected to login in their login site (pretty much how the internet connection works in many hotels). If you are idle for sometime, it will auto logoff. Since my internet connection is not so fast, I usually download over the night and open a keepalive window.

This worked well up until a couple of months back. Now they seem to have decided to disconnect users at random times regardless of internet activity. Not to be deterred by the challenge, I started thinking of how to work around this. The login screen looks like this:

I needed something that keeps logging me in automatically. Qt/WebKit was the obvious choice. It would have been trivial had the post URL of the above form not been dynamic (i.e it has a magic session number in the POST url).

So, here’s what I had to do:
1. Keep loading some website at periodic intervals. Check if I get redirected to their login page. It was a bit tricky to use Qt/WebKit to detect a redirect (in fact, there are two redirects); one has to resort to using timers and check if all the redirection has been done and the pages have been completely loaded.

2. Once the page is loaded I need to get the “dynamic” post URL of the form. I could do a grep in the html but that would be too simple :-) So, I tried evaluateJavaScript that will look in the DOM and return me the post url. Unfortunately, the QVariant returned by evaluateJavaScript() is always null. So, the next strategy was to fill the form details and submit the form entirely using JavaScript. And that worked like a charm :-)

You can find the git repo here (btw, Assembla rocks!).

It struck me later that I probably didn’t need Qt WebKit at all. I think a html/js loading a website periodically in a separate frame and trying to logon if necessary could have worked as well.

Older Posts »