Showing posts with label User Interface. Show all posts
Showing posts with label User Interface. Show all posts

Sunday, December 06, 2009

An alternative way to create the menu bar

I don't like resources. I really don't. I can understand their usefulness for features such as string tables or embedded icons, but when it comes to the Windows Mobile menu bar definition, I just hate the whole thing. Take a good look at how the CrypSafe sample app's menu bar is defined:

ATL_IDW_MENU_BAR SHMENUBAR DISCARDABLE
BEGIN
IDR_MAINFRAME,
2,
I_IMAGENONE, ID_ACTION, TBSTATE_ENABLED, TBSTYLE_AUTOSIZE,
ID_ACTION, 0, NOMENU,
I_IMAGENONE, ID_MENU, TBSTATE_ENABLED, TBSTYLE_DROPDOWN TBSTYLE_AUTOSIZE,
ID_MENU, 0, 0,
END
Intuitive, right? Incidentally, this resource is defined in the .rc2 file and the ATL_IDW_MENU_BAR identifier is used as a default parameter of the CreateSimpleCEMenuBar method of the CFrameWindowImplBase class template. So what do you have to do in order to change the menu bar? Gasp!

There is a better way, fortunately. A way that you can encapsulate and that makes the whole process a bit more transparent.

You create a Windows Mobile menu bar by calling the SHCreateMenuBar API typically from your main window's WM_CREATE handler. As you can see the function takes a single parameter, a pointer to a SHMENUBARINFO structure where you define the menu bar. There are two ways to create a menu bar: you either specify a menu bar resource ID or you provide your own HMENU by specifying the SHCMBF_HMENU flag. This is in fact a much more palatable alternative because you can declaratively create your menu bar in a single location of your application's code. Using my beloved WTL, here's how the code would look like on the main frame's OnCreate handler:

if(m_mainMenu.CreateMenu())
{
m_mainMenu.AppendMenu(MF_BYCOMMAND MF_ENABLED MF_STRING,
ID_BACK, _T("Back"));
m_mainMenu.AppendMenu(MF_BYCOMMAND MF_ENABLED MF_STRING,
ID_MENU, _T("Menu"));

SHMENUBARINFO mbi = { 0 };
mbi.cbSize = sizeof(mbi);
mbi.hwndParent = m_hWnd;
mbi.dwFlags = SHCMBF_HMENU;
mbi.nToolBarId = (UINT)(HMENU)m_mainMenu;
mbi.hInstRes = ModuleHelper::GetResourceInstance();
mbi.nBmpId = 0;
mbi.cBmpImages = 0;
mbi.hwndMB = NULL;

BOOL bRet = ::SHCreateMenuBar(&mbi);
if(bRet != FALSE)
{
m_hWndCECommandBar = mbi.hwndMB;
SizeToMenuBar();
}
}
The m_mainMenu variable is a CMenu, of course. The advantage of this approach is that you create the main menu bar in a very explicit way and if you later want to change it you know where to find the code, and stop guessing what that crappy SHMENUBAR resource declaration means...

Tuesday, December 01, 2009

A simple header button

Now that we have a header for the application, what about adding some useful stuff to it, like buttons? The picture on the left shows the second version of the touch header in action with a "back" button that implements the same functionality as the menu bar's "Back" menu. This button should only be visible when there is somewhere to go back to, so we should be able to add it and remove it as we please.

For now, the header button is a very simple object containing up to 3 CImage objects (for the normal, depressed and disabled states). This is not a regular Windows button but instead a "sensitive area" of the header that just behaves like a button (just like what happens with regular toolbars).

The button itself is implemented in the CTouchToolbarItem class (see sample code below). It derives from CRefCount so you can use the CRefPtr smart pointer class template to manage it and forget about deleting... The class contains three CImage instances, one for each possible state (these will later be changed to smart pointers as well in order to allow for better reuse).

Buttons are set through the virtual SetupTouchHeader method in each of the child views. Instead of just setting the header text, you can now set up to two buttons (left with index zero and right with index one). The button activation messaging is very similar to a regular menu: the WM_COMMAND message is sent to the parent window (the main frame) with the command ID as the wParam parameter.

A final thought: the header belongs to the frame window and is set up by the child view when they are shown. Is this a good design? I'm wondering if these should "belong" to the child view instead and be replaced along with it, possibly with some fancy animation. What do you think?

Sample code: CrypSafe08.zip (406 KB)

Sunday, November 15, 2009

A basic header

In this post I'm adding a very simple header to the CrypSafe sample, as you can see from the picture. Graphically it is a simple gray gradient with some text printed with an embossed look. Despite of the sleek look, the implementation is quite simple, as you can see from reading the CTouchHeader class source code (see sample source below).

The header is implemented as a simple WTL header window. The WTL protocol for headers and footers is quite simple: the frame window sends an empty WM_SIZE message (both width and height are set to zero) to the header and footer signaling these to position themselves in the main frame client rectangle. The remaining space will be occupied by the child view window.

Implementing this protocol is quite simple: handle the WM_SIZE message and reposition the header at the top of the main frame:

void CTouchHeader::OnSize(UINT nType, CSize size)
{
if(size.cx == 0 && size.cy == 0)
{
CWindow wndParent(GetParent());
CRect rc;

wndParent.GetClientRect(&rc);
rc.bottom = rc.top + m_cyHeader;
MoveWindow(&rc);
}
}

The m_cyHeader variable contains the height in pixels of the header. Now, you just need to paint the header with your favorite gradient. Painting the text with the embossed look is also a simple task: you just need to paint it twice in different colors, offsetting the second painting by one or two pixels down. You get the best effect by painting first with a darker color.

As of this implementation, you don't get a very smart header control: it just paints the text it is given. However, we can make this text change according to some application context just like when you switch views. In the sample code below, the header is always present between view switches and the CChildViewManager merely asks each CChildView that is brought into view to update the header text through the virtual SetupTouchHeader function.

Now that this is in place, we can add more features to the header and make it more useful for the whole UI...

Sample code: CrypSafe07.zip (345 Kb)

Friday, November 06, 2009

HOWTO: Close Application on Minimize

This is a popular question lately: how do I close my application when the user clicks the "smart minimize button"? This button does exactly that - it minimizes your application and does not close it. Your main application window is minimized when it receives a WM_SIZE message with the SIZE_MINIMIZED constant in the wParam parameter. All you have to do is call PostMessage(WM_CLOSE) and you are done. Here's a sample WTL handler:


LRESULT CCloseOnMinFrame::OnSize(UINT /*uMsg*/,
WPARAM wParam,
LPARAM /*lParam*/,
BOOL& bHandled)
{
if(wParam == SIZE_MINIMIZED)
{
PostMessage(WM_CLOSE);
bHandled = TRUE;
return 0;
}
// Not handled here
bHandled = FALSE;
return 1;
}

Monday, October 19, 2009

The Hold Gesture


After writing my last post, I started wondering if I could implement other useful gestures to control the touch list. So I started to wonder what kind of gestures would be needed for a real list-based application, like the CrypSafe prototype I have been working on. One of the issues that you will be confronted with is the requirement of, somehow, single out a single list item and then apply some sort of command to it. Think about deleting a list item: wouldn't it be nice that by clicking the item in a special way you would be able to do just so? There are a lot of other actions you might want to perform in a list item this way (edit, move up or down, you name it). Microsoft actually solved this issue some time ago with the "tap-and-hold" gesture, but gave it a very specific implementation with those circles rolling around the screen to denote it. Alas, I don't like it so I decided to reinvent the wheel and tweak the CTouchGesture in order to implement this gesture. It's actually quite simple: if you press an area of the screen and you don't move or release the finger for some time, a hold gesture is returned by the timer event.

To illustrate the use of this gesture, I implemented a very simple demo based on AppStart (yes, I was lazy) a so that it shows a "context toolbar" when you hold a given list item (see picture). In this case I added an "edit" and a "delete" button that you could use to change the list item. To make the whole thing a bit more fun, I added a small animation to the hold gesture where you can see the item expanding to reveal the "toolbar". Getting information about the pressed toolbar button would be a simple matter of overriding the HitTest function. Note that when the toolbar is displayed you can still flick and click because the item merely changed its size.

Here is the sample app: AppStart05.zip (268 KB)

Sunday, October 18, 2009

Minor touch improvements

In this blog post I'm returning to the touch window code to show you a couple of improvements that were needed.

First, there was the issue of stopping the list halfway through a scroll. If you start dragging the list and then stop, wait a little and then release the finger or stylus, the list would still scroll. This is not an intended (nor intuitive) behavior: the user scrolls the list up to a position and he / she wants it to stay put by stopping the finger / stylus for a fraction of a second and then releasing it.

The second issue happened when the list was "bouncing back" if you forced it to scroll down from the top (or scrolling up from the bottom). Under some occasions you could actually stop the list from scrolling back to its "rest" position leaving it in an awkward state.

To solve the first issue I changed the bulk of the code in the CTouchGesture class and turned it into a state machine with four inputs:
  1. Press - The user pressed the finger / stylus
  2. Move - The user is dragging the finger / stylus
  3. Release - The user released the finger / stylus
  4. Timer - Called every 200 ms in order to check transient conditions
Each input is implemented by a method with the same name and the novelty here is that each of the first three returns a value of GestureType (NoGesture, ClickGesture, FlickGesture). The return type is used by the CTouchWindow mouse event handlers to determine what to do (nothing, a click or a flick). When flicking through the list, the CTouchGesture returns the delta movement through the new GetDelta function.

By implementing the gesture recognition as a state machine we get a much better chance of determining and handling the harder to detect situations, such as:
  • Input noise such as when the user flicks and accidentally releases the screen for a very short period. This is now handled by the code and the state machine assumes that the previous flick is still happening.
  • Intermediate motion stop, such as when the user is flicking and stops halfway. This situation is detected by the timer event that essentially resets all displacement and time accumulators and assumes that the user wants to do nothing (this is not interpreted as a click, of course).
Finally, I changed the code a little bit so that it does not allow the list to be in an "unnatural" position. Whenever the list stops it is checked for such a situation (showing the canvas to the top or bottom when the list is larger than the window). When such a situation is detected, the list is automatically scrolled back into position.

To illustrate all of this, I turned back to the AppStart sample simply because it has a bigger list. Here it is for your viewing pleasure (or not...):

Sample code: AppStart03.zip (166 KB)

Monday, September 28, 2009

Improvements

After reading Vincent's comment on my last post, I took a second look at the scrolling code and scuttled the InvalidateRect scrolling mechanism. The fact is that while on some older devices this did work in an acceptable fashion, it did not work that well on more recent models and you can actually see some "bumps" in the scrolling speed. The code now uses a timer (again) but instead of indirectly painting the window through the InvalidateRect / UpdateWindow calls, it now directly invokes the painting function. The result is a very smooth scroll on all devices I have tested the code with.

I also changed the way the ScrollLeft and ScrollRight view transitions work. Instead of painting the bitmap at full speed, I added a very small sleep period to each iteration so that each transition is performed in approximately 250 milliseconds. The first paint operation is timed and a per-iteration sleep period is calculated so that the whole process takes the quarter-second period to unfold. With this improvement, you will be able to see the view transition on all devices (especially the ones with a faster CPU and QVGA screen).

Finally, I decided to add a couple of new view transitions: Fade and Explode / Implode. The first transition uses the AlphaBlend API function to fade from the existing view to the new view (like in a Power Point presentation). I have to say that this is not a very compelling transition, but inspired me to write the second. The Explode / Implode view transition also tries to mimic one of the most famous iPhone view transitions (when you launch an application). The existing view is zoomed in while the new view fades in while also zooming in from half its original size. The Implode effect does the reverse. The result was a bit disappointing because AlphaBlend operation seems to be very greedy (you can replace it by a simple StretchBlt and compare the results). The GDI is not very good at this stuff, unfortunately...

Sample code: CrypSafe06.zip (323KB)

Sunday, September 20, 2009

View transitions

Now that I managed to get some decent finger feedback from the list, it's time to get back to the CrypSafe prototype and add some view transitions. The code I'm using is based on an article I published last year on CodeProject: Animating View Transitions on Windows Mobile. Please read it before continuing as what you will see here is an extension of what I wrote there.

Essentially this article explored the ability to do some fashionable (read iPhone-like) view transitions using child views implemented as regular Win32 controls (such as a tree view, a list view or even a dialog). The view transitions were implemented using a very simple mechanism:
  • Capture the existing view as a bitmap;
  • Remove the from the frame container;
  • Paint the view bitmap on the frame client area;
  • Create the new child view window off screen;
  • Enter a loop where the bitmap is scrolled to the requested direction a few pixels;
  • Every time the bitmap is scrolled, move the new child window to the contiguous position thus creating the illusion that both windows are moving in lockstep.
That was a bit crude but worked. One of the lessons I learned from writing this article is that, generally, you cannot force an arbitrary window to paint itself to a memory DC. This would be very useful for some advanced visual effects. By reading the docs you might even be tempted (as I was) to send a WM_PAINT message to the hidden window with your memory DC in the WPARAM and expect it to paint there, but that just doesn't work for all windows. That's why I had to use MoveWindow for the animation.

Now that we are rendering the touch windows and lists directly on a memory DC, there is a better chance to improve on the original algorithm and implement a smoother view transition algorithm. This is what you will find in the sample code (see below).

The major change I made to the code was to CChildViewBase where you can now see a GetBitmap virtual method. If this method returns NULL, then the child view is not able to render itself on a bitmap and the old brute-force method will be used. If, on the other hand, the child view is able to render itself to a bitmap it must do so here. Note how this is implemented in the CCrypSafeView class: the painting engine is called directly and a new HBITMAP is returned for the child view manager to paint.

The results are here for you to see: acceptable on some devices, way too fast on others and slower on older devices. What we need to do here is quite simple: use the same kinematics equations to control the view transition motion and leave nothing to chance.

Comments and suggestions are welcome!

Sample code: CrypSafe05.zip (349 KB)

Sunday, September 13, 2009

Better touch

My professional life changed quite a bit recently and that's why I have not been posting as frequently as usual. I finally seem to have reached some balance and now's the time to resume my blog work.

One of the faults I found in the last version of the published code concerned finger sensitivity. This is a real issue in touch screens based on resistive technology (see a discussion about this topic on Marcus Perryman's blog). The bottom line is simple: resistive screens were made for a stylus, not for your finger. They are much more precise than capacitive screens (like the one found on the iPod Touch and iPhone), but require pressure. Capacitive screens are less precise but require only a very soft finger contact in order to operate. Resistive screens expect a very small pressure area (the tip of a stylus). An adult index finger uses up a very large area on the touch screen and the net result is noise and erratic motion messages.

You can see this in the last sample code I published: flick the list and then click it. It should stop the list but it doesn't (that's how it works on my HTC Touch Pro). What happens is that a single finger press is interpreted by the highly sensitive resistive screen as a sequence of one WM_LBUTTONDOWN message, a couple of WM_MOUSEMOVE messages and the final WM_LBUTTONUP. Inspecting the LPARAM parameter you will see that the POINT structure shows some fluctuations on the x and y coordinates. This means that a single finger press is actually equivalent to a small doodle drawn with your stylus. You will be lucky if the first and last POINT values are the same (they almost never are).

To mitigate this issue and provide better (more reliable) finger action feedback I made some adjustments to the code. The first thing I realized is that one of the sources of "position noise" was the first WM_MOUSEMOVE message. The offset between the WM_LBUTTONDOWN position and the first WM_MOUSEMOVE message seems to provide more variance than the offset to the second WM_MOUSEMOVE. To even things out a little bit I now discard the first offset and start calculating the gesture from the first WM_MOUSEMOVE message. Also, I brought back the concept of sensitivity to filter out smaller movements. Finally take a look at the code in CTouchGesture::Move method. Instead of calculating the move offset in a single if clause, I split the code into two, one for the vertical motion and the other for the horizontal motion.

The final result feels a bit better and more reliable on all the machines I have tested the code with, but the final word is yours.

Sample code: AppStart02.zip (164 KB)

Tuesday, August 25, 2009

Touch Improvements

The last version of the touch window and touch lists still needed improvements, notably on scrolling smoothness and clicking accuracy. In this post I'm presenting new versions of both classes where I tried to address these issues. The bottom line is that clicking feels much better but scrolling is still a bit jagged. I have to say that in order to get a game-like smooth screen scrolling one would have to choose something like DirectDraw because GDI was not made for this. Anyway, you will be the judge.

First I changed how the window scrolls by removing the timer. How do you force the window to scroll without a timer? Well, it's kind of easy: set up a scrolling mechanism that determines the next position based on the current time (I showed how to do that with the kinematic equations), set up a cutoff point (time and / or position) and just invalidate the whole window after painting. If you just invalidate the window, you allow all other messages to be processed and when the message queue is empty, the OS will send you a WM_PAINT message. If the window is still scrolling, you calculate the new position (based on the current time), paint the window and if the motion has not stopped, you invalidate the window again. This way you get a more natural way of scrolling the window and you know that you will get the best screen update frequency that GDI can muster. Note that in order to implement this in a generic way, I had to implement the OnPaint handler in CTouchWindow. This class delegates to its children through the "static virtual" Paint method.

In this process I had to update the way the kinematic equations are calculated due to some rounding errors I found on QVGA devices. To solve the issue, I changed the main equation back to the more classical form but reduced the timer precision from millisecond to hundredths of a second (divided by 10 in order to get smaller number from multiplication). The rounding error seems to be gone. I have also added a double criteria to test if the motion did end: now the code tests for both time limit and end point.

To help with both scrolling and clicking, I added a new class named CTouchGesture that essentially handles all the data coming from the stylus (mouse) messages and helps CTouchWindow determine if the last gesture was a click or a "flick". Note that for flicking, the class adds up all the partial moves (compensating for changes in direction) and reports an "average" flick speed (total displacement and time) instead of the last move.

Clicking the items is now a bit more reliable because the code tests for clicking eligibility. If the window is moving and you click it, there will not be an OnClick call: you will only get one if the window is still to begin with.

I hope that these modifications did improve the code and the user experience, but with my limited assortment of devices I cannot have a good judgment on that. So please tell me what you think!

Sample code: AppStart01.zip (161 KB)

Monday, August 10, 2009

Item Activation

I'm still not sure how this is going to end, but right now items can be focused, selected and activated. An item gets the focus when you use the arrow keys to navigate the list and that is meant to mean the "current" item in the list. When you select an item it gets added to a selection list (in case you need to use multiple-selection lists). Note that focus does not mean selection nor selection means focus. Finally, an activated item is the one you just "pressed" or clicked.

The code I'm publishing today shows how to set the focus on a particular item (just added a highlighter to the DrawItem method) by navigating the list with the arrow keys and how it can be activated by directly clicking it or by pressing the enter key on the focused item.

I had to make some changes to the CTouchWindow class template in order to make sure that scrolling (or flicking through) the list does not get confused with a click. If you hook the application with Remote Spy you will see an interesting pattern of messages when clicking an item: WM_LBUTTONDOWN, WM_MOUSEMOVE (may occur more than once) and WM_LBUTTONUP. What's interesting is that the "mouse move" message always shows up even if it reports the same screen position as the "button down" message. Is this a bug, Microsoft? Anyway, the code already handles null movements so...

When an item is selected, the CCrypSafeView::OnItemChangedState method is called by the base class and to handle the item activation you must handle the TLN_ITEMACTIVATED code. Just take a look at the sample code to see how it is done. Note that you test nmtl.dwState for nonzero meaning activation - it is zero when the item is "deactivated".

Sample code: CrypSafe04.zip (325 KB - now includes the OleDbClient lib)

Saturday, July 11, 2009

Kinematics

How do you make the touch list behave like a real physical object? What's the secret behind making the list bounce smoothly back to its original position? How do you decelerate it when you quickly flick through it like if it had some sort of "friction"? In short: how do you make it work like an iPhone list? The answer is simple: kinematics, the study of motion.

In this post I'm adding some kinematic effects to the list to make it work like if it had both weight and some "springs" to attach it to the extremes of the window. These "springs" will make the list bounce back when the list is either showing its first or last element and you force it to scroll down or up (respectively). Also, when scrolling through very large lists, you want them to slow down in a realistic fashion, like a real object would.

There are a lot of changes to the base CTouchWindow class in order to include these kinematic additions. Interestingly, some parts of the code actually became simpler. This base class is used to implement the touch list that only performs vertical scrolling, but it must also accommodate for a possible horizontal scrolling. To make the kinematics implementation easier, I created a helper class named CTouchMotion that is used to calculate the list position as a function of time. You initialize each instance (vertical and horizontal) with the desired acceleration (in pixels per squared second), initial speed (in pixels per second), the initial and final positions of the motion (the final position is redundant, me thinks) and the total motion time. The x and y positions of the motion (just y for the touch list) are calculated by the GetPosition function that takes the time offset (since the beginning of the motion) as milliseconds. The function just computes the classical x = 0.5 * a * t * t + vi * t + xi equation, where x is the position for time t, a is the acceleration, vi is the initial speed and xi is the initial position. Notice that the function must transform the input in milliseconds to seconds in order to get the appropriate result. This is a concern because I must perform all calculations using integers to get the best performance possible. If you look at the implementation of the GetPosition function you will see that I calculate the 0.5 * a * t term first and convert it to a pixels per second speed. Next I add the initial speed, multiply the result by t and then convert the result to pixels by dividing by 1000. Finally, xi is added and we get the proper result. Also notice how each step is accurately rounded to make sure nothing is lost during conversions.

While I was debugging this code I found a very interesting bug. Originally, the function was using the time offset as a DWORD (an unsigned value). Occasionally the list would simply disappear while scrolling. The bug was due to the conversions performed between signed and unsigned integers and sometimes they behaved differently from what I expected, and would throw the list origin to very large negative numbers. The problem was solved by casting the time offset to a signed integer.

You can also see that the function uses a time limit that works as a "break" if you accidentally call it with a time offset larger than the one you specified. Why is this? Simple: the equation is a simple parabola that computes a trajectory until the speed (the first derivative) is zero. This is when the list stops. If you don't limit the motion, you would actually see the list bouncing back with a positive acceleration like when you throw a ball up, and it comes back down. You only want the upward movement - the one where the speed decreases until zero.

Another big change happened in the way the motion timer is calculated. The previous version used the speed of the last WM_MOUSEMOVE (displacement and time). This concept was discarded and I assumed that the movements would have a set of fixed behaviors:
  • Bounce-back movements would last 500 milliseconds.
  • List deceleration would take 2 seconds.
You can see these calculations in the CTouchWindow::SetupMotion function. This is called when the list is about to move (on the WM_LBUTTONUP handler) and during the timer (OnTimer) function in order to test for boundary conditions. There is something that's still amiss here: when you transition from a scroll to a bounce-back, the initial speed is not being considered so you see a bit of a harsh transition. I will correct this later.

Finally, and because you can now have an empty space drawn before the list (and also after, but this was already in the previous implementation), I added a fourth color to the list: the canvas color. This is what lies "beneath" the list and helps to convey the notion that the list exists above another surface (thanks for the suggestion, Anatoly).

The code is not fully cleaned up yet and you will see some more changes to this kinematic code. Meanwhile, here is the project for your perusal:

Sample code: CrypSafe03.zip (99 KB)

Thursday, July 09, 2009

Bouncing the list

While I was preparing the code for the next post, I realized that something really important is missing from the touch list: it does not "bounce". Use the sample I published in the last post and try to move the list. It will not budge. Similar implementations allow you to move the list out of it's stable position (minimal energy position?) and it will move back to where it was. It gives you a nice sense that you are dealing with a physical inertial entity.

The sample code I'm publishing today just allows for this and simply resets the list to it's stable position without any animation or kinematic feedback. Right now I'm going through some high-school kinematic equations in order to implement some properly accelerated animations to the list. Meanwhile, check the source code here: CrypSafe02.zip. As you can see, the list painting now allows for empty space both before and after the list so that when you force it down it will not leave garbage at the top.

Monday, June 29, 2009

A better look

Here's a better look for the CrypSafe main view. As you can see I'm using a new font for the item text, added a separation line between the items and painted the background with a different brush for odd-numbered items. The changes to the code are not very dramatic, so let's take a look at them.

The first change is the new font. To use a new font I generally declare a CFont object on the view class like this:

private:
CFont m_largeFont;

This way I know that the font will exist throughout the life cycle of the containing view. Creating the font itself is always a bit of a pain, but i prefer to use the following method because it does give me full control over what is going on. The following code snippet was taken from the view constructor in CCrypSafeView.cpp:

LOGFONT lf;
int nLogPixelsY = DRA::LogPixelsY();

lf.lfHeight = DRA::HIDPIMulDiv(-12, nLogPixelsY, 72);
lf.lfWidth = 0;
lf.lfEscapement = 0;
lf.lfOrientation = 0;
lf.lfWeight = FW_NORMAL;
lf.lfItalic = FALSE;
lf.lfUnderline = FALSE;
lf.lfStrikeOut = 0;
lf.lfCharSet = ANSI_CHARSET;
lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfQuality = CLEARTYPE_QUALITY;
lf.lfPitchAndFamily = DEFAULT_PITCH | FF_SWISS;
_tcscpy(lf.lfFaceName, TEXT("Tahoma"));
m_largeFont.CreateFontIndirect(&lf);

The code at the top is the most important one because it makes sure that we create the font with the right size in points, independently of the resolution of your device's screen.

Now that the new font is ready to use, let's see how to use it on the DrawItem method. First, you need to declare an HFONT variable:

HFONT hFont;

This is used to store the DC's currently selected font while we use our custom font. Setting the new font is easy:

hFont = dc.SelectFont(m_largeFont);

When we are done with the new font, we must set the old DC font back:

dc.SelectFont(hFont);

To paint the text with a left border, I copied the item CRect to a new instance:

CRect rcText(rcItem);

Before painting, the left value is adjusted:

rcText.left += DRA::SCALEX(4);

Note that this will correctly scale in higher DPI screens. As you can see from the included image, the even-numbered items have a white background while the odd-numbered ones have a very light gray background. As I explained in the previous post, the client code in DrawItem is supposed to paint the background, and doing it is extremely easy:

COLORREF rgb(m_rgbBack);
if(iItem % 2) rgb = RGB(0xf0, 0xf0, 0xf0);
brush.CreateSolidBrush(rgb);
dc.FillRect(&rcItem, brush);

The m_rgbBack variable is declared by CTouchListBase and contains the default background color (this color is used to fill in the unpainted space at the bottom of the list). If the item has an odd number, I replace the default white with a light gray and use this RGB value to create a brush. Painting the item's background is a simple issue of calling FillRect with the supplied item CRect (rcItem).

Now we can paint the item's text making sure that it is painted with a transparent background mode:

int nBkMode = dc.SetBkMode(TRANSPARENT);
dc.DrawText(pItem->GetText(), -1, &rcText, DT_LEFT | DT_VCENTER);
dc.SetBkMode(nBkMode);

Note that the text is painted using the rcText rectangle, not the item's. This way we get the left margin effect. Finally we can print the bottom separation line:

CPen pen;
HPEN hPen;
pen.CreatePen(PS_SOLID, 1, m_rgbLine);
hPen = dc.SelectPen(pen);
dc.MoveTo(0, rcItem.bottom - 1);
dc.LineTo(rcItem.right, rcItem.bottom - 1);
dc.SelectPen(hPen);

The m_rgbLine contains the default color for the separation line (gray). As you can see, this is not rocket sience. Next, I will explore how to add a navigation cursor and key handling.

Sample code: CrypSafe01.zip (96 KB)

Monday, June 15, 2009

A simple GPS viewer

Here's a simple GPS viewer application. I wrote it to help me in testing the transition to reference counted pointers in my budding Windows Mobile native (WTL-based) framework. In the process I have learned a few things about reference counted pointers, especially when NOT to use them.

One of the changes I made to the way the CPropertyListView class is used is that it contains pointers to items created on the heap and not on the stack. This means that you now have to create items like this:

m_pGpsFix = new CPropertyString(L"Fix", L"Unknown");

Note that the m_pGpsFix variable is actually a "smart pointer" and you don't have to worry about deleting it in the destructor. Nor does the list, in fact... When each item's reference count reaches zero, the last smart pointer that references the object will delete it (and that's why you cannot have stack allocated items). This is when you should use smart pointers, so when should you use simple C++ pointers? I found out the hard way when adding these items to the list. My original (and right) prototype was:

void CTouchListBase::AddItem(CTouchListItem* pItem)

When I replaced the C++ pointer with a smart one, I immediately lost one of the best features these things have: the ability of a base class pointer to refer to a derived class object. Understanding that I don't know enough about C++ class templates to make this work (not even sure if that's possible - will have to look at Jossutti's book), I decided to fall back to straight C++ pointers. This poses no problem because the method internally will use the smart pointer class constructor to build a new instance using the raw pointer and add it to the underlying array, so the reference counting is respected.

The sample application just starts the GPSID and displays some data from the GPS on a dialog. As you can see from the ZIP file, there are two additional library projects that make up the framework. Note that these are subject to change and do have bugs!

Sample code: GpsView.zip (93 KB)

Thursday, May 07, 2009

AllKeys, documented

Here is the key capturing API we've all been waiting for since the demise of GAPI: AllKeys.

Tuesday, April 21, 2009

Native GDI+ on CodeProject

Vincent Richomme just posted an article on Code Project on how to use the GDI+ libaries through native code. If you think it's hard to add that extra cool look to your native GDI app, do take a look at Vincent's article!

Tuesday, April 14, 2009

Is IImage caching a good idea?

On my previous post I described a very simple solution to improve the performance of IImage::Draw - caching the converted image. This does speed up the process of drawing the alpha blended picture but has one drawback: you store the image twice. From what I understood from the IImagingFactory::CreateImageFromBuffer online documentation, the supplied buffer is not immediately used and must be there throughout the IImage object lifetime. So when you cache the image you are essentially storing two representations of the same thing (the original encoding  and the decoded version). While this may not be a big issue for small images, this becomes a serious problem when using lots of images and / or larger images. So what can we do about this?

The idea is to have a single 32 bpp ARGB HBITMAP in memory per image. As I showed before, using the shell API to load the images is a bad idea because it shrinks them to 16 bpp. Is there any other alternative to this? We can try to create a 32 bpp bitmap in memory and then use the IImage object to paint it. After releasing the IImage object, we should get a properly-formatted 32 bpp ARGB bitmap. On my next post I will illustrate this technique that was validated by master guru Alex Feinman. 

Monday, April 13, 2009

Revisiting the Carousel - II

I finally found a solution for the speed problem of rendering the carousel icons: caching the image. After a big wild goose chase, the solution was under my very nose all the time. To see the dramatic performance improvement, open the CarouselDemo2 project I published on my last post, and go to the image.h file. At the top of the file, there is a private method named CreateImage, where the IImage object is created. Right after creating the object:

hr = spFactory->CreateImageFromBuffer(m_pImageData, m_nImageSize, BufferDisposalFlagNone, &m_spImage);

just add the following lines:

if(SUCCEEDED(hr))
hr = m_spImage->SetImageFlags(ImageFlagsCaching);

Now run the demo again and see how much the performance has improved!

Now that this issue is solved, let me tell you about the wild goose chase. My original idea was to use the AlphaBlend API that has been added to Windows Mobile 5. This function does support per-pixel alpha blending so it looked very promising. Unfortunately, there seems to be no easy way to load a 32 bpp bitmap image with Windows Mobile. I tried using SHLoadImageResource (I read somewhere that this would keep the alpha channel intact) but the returned HBITMAP was smashed down to 16 bpp, so the alpha channel was lost. I still have not given up to find an easy way to load the PNG files into memory, and when I do you will be the first to know. Oh, by the way, if you do know please post a comment here!

Saturday, April 11, 2009

Revisiting the Carousel

What's the difference between the two QVGA carousel implementations above? And what about the two VGA implementations below?


The top carousel icons look much better than the ones below, especially the ones with round shapes. What's the difference? While the images at the bottom carousel are regular Windows icons drawn from an image list container, the images at the top carousel are PNG images drawn using the IImage object. These PNG files were created with an "alpha channel", an extra byte of information that specifies how transparent each pixel is. Contrary to Windows CE icons which support only the concept of full transparency or full opaqueness, an alpha value determines how transparent each pixel is, so it can blend with the background and create very smooth transitions (so much nicer and easier on the eye). Using the right tools (these icons were produced using Axialis Icon Workshop), you can easily create these images and render them on the device screen.

The sample project (CarouselDemo2) illustrates how this can be implemented in code. First, I removed all the icon-related code and added two new classes (both on the image.h file): CImage and CImageArray. The first class encapsulates an IImage object and provides minimal services for loading the image from resources and drawing it on a given DC. The second class merely groups instances of the first in an array for convenience.

The great thing about IImage is that it allows us to load a raw byte stream of data making up a recognizable bitmap (more codecs can be added) and transforms it into a usable bitmap (not an HBITMAP, mind you). The supported image formats include JPEG, GIF and PNG with the nice alpha channel feature. All you have to do is load the image and draw it. Simple!

Well, not so fast... Really: it's dreadfully slow! If you run the new demo application you will see what I mean: the carousel scrolls like mud.

I previously had a similar experience where using IImage::Draw on a graphics-intensive GDI application proved impossible to use. The solution was to pre-render the PNG files (no transparencies here) to an HBITMAP and cache them, so I was not really surprised that the painting would be slower (but not that slow!). Is there any way around it? Hopefully yes, and I will write about it (or about my failure to achieve it) on my next blog post.