About a month ago I published an article which demonstrated how to create a WP7 application using static HTML pages and PhoneGap. Whilst PhoneGap makes the packaging of HTML / JavaScript / CSS and images into a breeze, one thing it doesn’t do is provide correct back-button support. Correct back-button support is a mandatory requirement for marketplace certification. Hitting the back button should navigate back through the various screens of an application. Hitting the back-button on the first screen should terminate the application.
The solution I published previously handles the WP7 back keypress in order to keep track of the back-stack depth. When the back-stack depth is just one, a back-button press exits the application. This works fine if backwards navigation is always controlled via the hardware back-button, however if your application has HTML anchor elements that navigate back to a previous page, or you use code such as javascript:history.go(-1), this back-stack handling code will not detect that a backwards navigation has occurred.
As an aside, WP7 applications really should use the hardware back-button for navigation. If you are writing a cross-platform PhoneGap application consider adapting your UI for each platform. This means removing the back-button you woudl have in your iOS version when ‘skinning’ for WP7.
In order to solve this issue I have updated the code to inspect the URL that the browser control is navigating to in order to detect backwards navigation. The class now maintains a list of URLs, which represent the navigation stack. This allows it to detect a backwards navigation.
/// <summary>/// Handles the back-button for a PhoneGap application. When the back-button/// is pressed, the browser history is navigated. If no history is present,/// the application will exit./// </summary>publicclass BackButtonHandler
{private WebBrowser _browser;private List<string> _backStack =new List<string>();public BackButtonHandler(PhoneApplicationPage page, PGView phoneGapView){// subscribe to the hardware back-button
page.BackKeyPress+= Page_BackKeyPress;
_browser = phoneGapView.Browser;// handle navigation events
_browser.Navigated+= Browser_Navigated;}/// <summary>/// Handle navigation in order to update our back-stack/// </summary>privatevoid Browser_Navigated(object sender, NavigationEventArgs e){string url = _browser.Source.OriginalString;// ensure all slashes are the same// app\www/index.html// see: https://issues.apache.org/jira/browse/CB-184
url = url.Replace("\\", "/");if(_backStack.Count<2){
_backStack.Add(url);}else{// check whether the URL represents a backwards navigationstring previousPage = _backStack[_backStack.Count-2];if(previousPage == url){
_backStack.RemoveAt(_backStack.Count-1);}}}/// <summary>/// Handle the hardware back-button/// </summary>privatevoid Page_BackKeyPress(object sender, CancelEventArgs e){// if we have items in the back-stack, route this event// to the browserif(_backStack.Count>1){
_browser.InvokeScript("eval", "history.go(-1)");
e.Cancel=true;}}}
Note: There use of url.Replace("\\", "/"), this is due to a minor issue with the PhoneGap WP7 native code, which I have raised in the Callback JIRA (CB-184).
To use this code simply create an instance of the class, passing the PGView (the PhoneGap user control) into teh constructor:
public MainPage(){
InitializeComponent();new BackButtonHandler(this, PGView);}
Because back-button handling is a mandatory requirement for WP7 applications, hopefully Nitobi will incorporate this code (or similar) into the PhoneGap Build service (which I tried earlier this week – it is pretty amazing!)
I have just received an email from Chris Maunder, co-founder of CodeProject, informing me that I have been awarded CodeProject MVP status for 2012. I am very pleased to have received this award, which is given to a small handful of individuals each year.
What I like about CodeProject is the fantastic quality of the articles submitted by the thousands of authors that participate in this site, with the only payment being their own please in the writing.
I have not written that many articles throughout the year, just four of them. However, I have put a lot of effort into each one of them – and thankfully they have been very well received. It is great that CodeProject favours quality over quantity. My articles for 2011 were:
I do also circulate some of my blog posts via the CodeProject Associate program..
On that note, it is almost three months since I last wrote an article … fortunately I do have an idea for the next article, so I had better get on with writting it …
I recently released an update of the HTML5 / PhoneGap application I wrote a few months ago to the marketplace. This update fixed the location detection issue, where the marketplace certification process failed to detect that the application was using geolocation data via the browser (this issue has been fixed in PhoneGap 1.2), plus a few cosmetic improvements.
This application still exhibits a few UI quirks that make it fairly obvious that this is not a native application, the first is the gray box that appears whenever a link is clicked, the second is the overall responsiveness – there is a short delay between clicking on links / buttons and the application responding. It is this responsiveness that I would like to tackle in this blog post. This delay unfortunately gives the impression that your application is less responsive than it actually is!
So where does this delay come from?
Despite the rise in popularity of touch interfaces, much of the web is still designed for interaction with a mouse and keyboard, with the DOM exposing events for mouse-up, mouse-down and click user interactions. The Windows Phone 7 browser control captures touch interactions and translates these into the required mouse events, firing them on the DOM element being interacted with. However, the browser itself also needs to support gestures such as pan, pinch-zoom and double-tap zoom.
If we consider for example the pinch-zoom feature, where the user places two fingers on the screen and moves them apart in order to zoom in. It is highly unlikely they will place both fingers on the screen simultaneously. If, when the first finger was placed, a mouse-down event was fired on the relevant DOM element, there would be no way to ‘cancel’ this event when the user’s second finger made contact with the screen shortly afterwards. For this reason the WP7 mobile browser does not properly support mouse-down / mouse-up events. You will find that mousedown, mouseup then click are always fired immediately in that order regardless of how long you hold your finger on the screen for. Clearly the need to add gesture support to the browser interferes with the way in which native touch events are translated into JavaScript mouse events.
Now consider the double-tap zoom feature, where the user taps twice in quick succession to zoom the web page by some fixed amount. If the DOM click event were fired on the first tap, this would cause a navigation to occur if an anchor element were tapped. This is certainly not the desired behaviour! Again, there is no way to ‘cancel’ an event once it is fired, so the only solution to this problem is, when the user first taps the screen, pause for a few hundred milliseconds to see if they tap a second time. Only after this pause is it safe to pass the interaction onto the DOM, firing a click event on the relevant DOM element.
The need to handle gestures in the native layer causes numerous issues for the browser event handling. Thankfully these issues are relatively minor for most websites, but if your aim is to create a HTML-based application with a native look and feel, these issues become quite major.
Improving responsiveness
The problem I want to tackle in this blog post is that of the click DOM event firing delay to support the double-tap gesture. With HTML5-based applications you will typically want to disable pinch zoom, double-tap zoom and (optionally) scrolling as I described in a previous blog post. As a result your application has no need for the double-tap and pinch gestures and we are safe to short-circuit this behaviour, immediately raising DOM click events when the user taps the screen.
My solution follows a similar approach to the utility class I wrote for suppressing pan / zoom, where event handlers are added to the Border that sits within the WebBrowser control visual tree:
In order to forward Tap gestures to the browser, we can add event handlers to the Border element, then use InvokeScript to pass this onto the DOM rendered within the TileHost.
The JavaScript code to achieve this is very simple, the DOM exposes an elementFromPoint function which allows you to hit test the DOM. The IE9 DOM interface also exposes a non-standard click function which invokes any click event handlers, this will cause an anchor element to navigate. Putting it together, if you have an anchor element at (x=100, y=100), you can cause it to navigate using the following simple code:
document.elementFromPoint(100,100).click()
Calling this JavaScript from our native C# code in response to Tap events is very easy. I have wrapped it up into a simple utility class:
/// <summary>/// Captures mouse left button up events, triggering an immediate/// click event on the clicked DOM element./// </summary>publicclass BrowserFastClick
{private WebBrowser _browser;private Border _border;public BrowserFastClick(WebBrowser browser){
_browser = browser;
browser.Loaded+=new RoutedEventHandler(Browser_Loaded);}privatevoid Browser_Loaded(object sender, RoutedEventArgs e){// locate the element used to capture mouse events
_border = _browser.Descendants<Border>().Last()as Border;
_border.Tap+= Border_Tap;}privatevoid Border_Tap(object sender, GestureEventArgs e){//determine the click location
var pos = e.GetPosition(_border);// forward to the browser
_browser.InvokeScript("eval",
string.Format("document.elementFromPoint({0},{1}).click()", pos.X, pos.Y));}}
To use it within a PhoneGap application, simply create an instance as follows:
new BrowserFastClick(PGView.Browser);
The net result is that your application becomes more responsive, with the browser immediately navigating links when they are first tapped.
I have updated the HTML5 SandwichFlow application I blogged about a few weeks ago to use this FastClick code. You can download the complete example here: HTML5SandwichFlow.zip
Last night, with my Christmas presents all wrapped and a lack of any decent programmes (festive or otherwise) on television, I had a few hours to kill, so decided to create a festive-themed WP7 game …
Ever since I first started writing code for Windows Phone 7 I have wanted to do something involving physics and the accelerometer. I finally found a few hours to spare to give it a go. This blog post doesn’t go into too much detail about Farseer, the Physics Engine that I used, I didn’t really have time to learn it in any great detail. This post is more about how quickly you can put together something really quite cool in quite a short space of time using libraries and code grabbed from the internet.
The simple app I created renders a maze that you ‘roll’ a small ball around by tilting your phone:
This works well in the new 7.1 emulator where you can tilt the emulator via the extended controls. However, it works best on a real device, where you can control tilt far more easily. See the video below:
Farseer Physics Engine
The game makes use of the popular Farseer Physics Engine. This library allows you to create a world populated with physics bodies, supporting features such as friction, joints, motors and much much more. As I am a Silverlight developer I made use of the Physics Helper library which allows you to use the Farseer engine within a Silvelight application with very little effort. With the Physics Helper you simply make the Physics Engine ‘aware’ of the objects you wish it to control and it does the rest, animating them as they are subjected to gravity and other interactions.
The simplest way to use Physics Helper is via behaviours, this allows you to create a fully functioning ‘world’ without writing a single line of C# code. For example, you can create a ball and a surface that it will fall towards, eventually coming to rest, with just a few lines of XAML:
<Canvas x:Name="canvas"><!-- create our 'world'--><i:Interaction.Behaviors><pb:PhysicsControllerBehavior/></i:Interaction.Behaviors><Ellipse Width="100" Height="100" Fill="Red"
Canvas.Left="80" Canvas.Top="100"><!-- make the engine aware of this element --><i:Interaction.Behaviors><pb:PhysicsObjectBehavior /></i:Interaction.Behaviors></Ellipse><Rectangle Width="500" Height="10" Fill="Blue"
Canvas.Top="500"><!-- make the engine aware of thisSTATIC element --><i:Interaction.Behaviors><pb:PhysicsObjectBehavior IsStatic="True"/></i:Interaction.Behaviors></Rectangle></Canvas>
I find this pretty amazing!
Physics Helper will do much more, it can handle complex paths and geometries, explosions and collisions with minimal effort. For a greater insight into just how much is possible, I would recommend Andy Beaulieu’s Channel 9 article. Andy is the creator of Farseer, so really knows his stuff!
My maze is generated in C# code, so despite the elegance of using Physics Helper via behaviours, I need to add elements to my canvas programmatically. This means that I have to make the physics engine aware of their existence in code also. To achieve this, I add the behaviour in code as follows:
/// <summary>/// Uses Physics Helper to create a physics body for the given element/// </summary>privatevoid AddPhysicsBody(FrameworkElement element, bool isStatic){
var behaviorCollection = Interaction.GetBehaviors(element);
behaviorCollection.Add(new PhysicsObjectBehavior(){
IsStatic = isStatic
});
var physicsObject = element.GetValue(PhysicsObjectMain.PhysicsObjectProperty)as PhysicsObjectMain;
_physicsController.AddPhysicsBody(physicsObject);}
Creating a Maze
I found numerous C# maze algorithms on the internet, most of them based on the same random-walk concept. There is a great description of this approach, with animated examples on this blog. Unfortunately every C# implementation I came across was tightly coupled to a specific UI framework, often WinForms or XNA (tut-tut remember to separate your concerns!). So, I took a simple maze algorithm from a software forum and ripped-out the WinForms / GDI rendering code. A new maze is constructed simply by creating an instance of the Maze class, passing it the number of rows and columns.
In order to render the maze using Silverlight elements, I simply took the original maze graphics code:
The above code creates a maze comprised of static physics objects, where the _mazeSize field dictates the scale of the maze:
Adding a Rolling Ball
Adding a ball to the maze is simply a matter of creating an ellipse and adding it at the maze entrance. Note, this physics-body is not static, so will move under the influence of gravity:
By default, the ‘world’ has gravity with a fixed Y component and no X component. This causes all non-static bodies to fall downwards as you might expect. In order to guide the ball around the maze by tilting the phone, we need to adjust gravity based on accelerometer readings. This is achieved by the following code:
privatevoid HandleAccelerometer(){
_sensor =new Accelerometer();
_sensor.Start();// 10 times a second, update the gravity
var gtimer =new DispatcherTimer();
gtimer.Interval= TimeSpan.FromSeconds(0.1);
gtimer.Tick+=(s, e)=>{if(_physicsController.Simulator!=null){
_physicsController.Simulator.Gravity.Y=5*-_sensor.CurrentValue.Acceleration.Y;
_physicsController.Simulator.Gravity.X=5* _sensor.CurrentValue.Acceleration.X;}};
gtimer.Start();}
Note: this uses a timer, rather than updating the simulator every time the accelerometer reading changes. I found that without the timer, I was repeatedly seeing the generic “Element is already a child of another element” exception. You will also notice in the code that the maze is built after a pause of a couple of seconds, again in order to avoid this issue. There’s something funny going on inside the Physics Helper!
Finally, we handle collisions in order to play a simple sounds effect a the ball bounces off each wall:
// locate the physics controller
_physicsController = mazeContainer.GetValue(PhysicsControllerMain.PhysicsControllerProperty)as PhysicsControllerMain;// load the WAV file
Stream stream = TitleContainer.OpenStream("boing1.wav");
_effect = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();// play on each collision
_physicsController.Collision+=(s,e)=> _effect.Play();
And there we have it, a simple maze game powered by the Farseer Physics engine. The whole thing only took about an hour to create, with code grabbed from the internet – a bit rough and ready, but I was impressed with how easy it was to create this game. There is much more that could be done, for example detecting when the ball reaches the end of the maze, advancing to a more difficult level, however, my time has run out on this bit of fun … Also, if I were to take this idea further, I would probably use XNA rather than Silverlight. The Physics Helper is great for simple XAML-only physics models, but I feel that it wasn’t really built for programmatic creation of bodies.
Note, you will have to download and install Physics Helper to run this code.
On another note, Farseer is clearly the result of hundreds of hours of development effort, which makes it easy to create realistic physics-based applications and games. Farseer is free to use under the MS-PL licence. However, I would urge anyone who has used this great library to create a WP7 game to donate via the Farseer codeplex site (scroll to the bottom).