Plugins for PhoneGap + Windows Phone Mango

We recently added plugin support to WP7 PhoneGap apps. I will outline here what you need to do to start extending the functionality for WP7 PhoneGap projects.

All WP7 PhoneGap plugins must derive from the PhoneGap base command. More specifically, the WP7GapClassLib.PhoneGap.Commands.BaseCommand class.
Plugin commands are dealt with generically throughout the framework, and base command provides the base interface for you to pass data back to JavaScript. This approach also prevents JavaScript code from calling arbitrary native code.

I recently posted a plugin titled PGSimpleShare to my GitHub repo. You can clone/fork it here : https://github.com/purplecabbage/phonegap-plugins/tree/master/WindowsPhone/PGSocialShare

The PGSimpleShare allows for simple updates to share links and status updates on social networks. Windows Phone Mango includes accounts for popular social networks, and the updated SDK provides a simple way to post data to them. The PGSimpleShare plugin exposes this same functionality to JavaScript running in a PhoneGap application. When you call this plugin to share a statusUpdate, the user will be presented with a native dialog previewing the update and allowing them to choose which networks they want to post it to. On my phone I see Facebook, Twitter, LinkedIn, and Window’s Live, all updated simultaneously ( as far as my code is concerned )

Plugins provide their interface to the application via some JavaScript code, this is done as expected inside a js file. Here is some JS for a simple plugin, taken from the recent PGSocialShare plugin I posted on GitHub:
To call your native side implementation, simply call PhoneGap.exec(winCallbackFunction, failCallbackFunction, pluginName, methodName, argsObj); The WP7 version of PhoneGap.exec will do the work of managing your callbacks if supplied, as well as turning the argsObj into a JSON object that can be passed to your native code. In the case of the shareStatus function defined above, the framework, on the native side will look for a class named PGSocialShare. ( fully qualified: WP7GapClassLib.PhoneGap.Commands.PGSocialShare ) When it finds this class it will instantiate it if it hasn’t already, then it will attempt to call the ‘share’ method on it. Here is a portion of the native implementation of the ‘share’ function :

Note the implementation of the share function is public, returns void, and expects 1 string argument, this is currently the signature for ALL plugin methods that are callable via the framework.

The above code then continues on to deserialize the JSON representation of the arguments it is expecting via a data-contract. See the full source code for details on this.
Based on the shareType passed in, we will call another method in our class; namely ‘shareStatus’.
This method then proceeds to pass the status message on to the SDK ShareStatusTask. There is no return value from the native SDK’s ShareStatusTask, so we have no way of knowing if the user cancelled it, or which networks they chose to post the status to. PGSocialShare::shareStatus then calls DispatchCommandResult which is defined by WP7GapClassLib.PhoneGap.Commands.BaseCommand, and will signal to JavaScript that the call has succeeded. In cases where we need to pass back some data, or signal an error condition vs a success, we can use the PluginResult`s enum of statuses ( statii ? )
We can also signal that we want JavaScript to keep our callback, for cases where we are monitoring sensor data, like the Accelerometer command.

Hopefully this is enough for everyone to get started developing plugins for Windows Phone! Also, I have attempted to keep PGSocialShare device-agnostic in the definition of the methods, so hopefully we will see the same plugin implemented on other devices as well. I look forward to your comments, questions, and critriques!

Cheers,
Jesse

Implementing WebStorage for PhoneGap + Windows Phone Mango ( Part 1 )

Windows Phone 7 with the Mango updates includes the new IE9 which is a very capable browser, and has support for many new standard HTML5 APIs.

Some of the feature highlights (IMHO) include:

  • addEventListener : no more conditional event code
  • querySelectorAll : easily grab DOM elements by id/class/type etc.
  • WebStorage APIs : localStorage + sessionStorage
  • ES5 : Function.bind, Array.forEach, …

The reader: But wait, I thought this post was going to be about how the WebStorage APIs were added to PhoneGap for WP7, but you just said IE9 supports it, what gives?

The writer: I’m getting there just wait …

So, IE9 implements the complete spec for WebStorage as defined here: http://dev.w3.org/html5/webstorage/
Unfortunately, this implementation is only available to web pages that are loaded from a domain because of the way the data stores are sandboxed per domain. In the context of a PhoneGap application, our page is loaded from IsolatedStorage ( aka: file:// ) so we are not assigned a domain by IE9, so we do not have access to localStorage.

Okay, so having seen this I realized that I needed to polyfill here, and provide an implementation. However, upon attempting to set window.localStorage to my own object, I received an error stating that window.localStorage was read-only? oh crap! After a little more exploration, I remembered my ECMA. ECMAScript 5th Edition to be precise, and IE9 supports it. So after a quick test, I discovered that I could duck-punch/polyfill window.localStorage using Object.defineProperty(obj, prop, descriptor); Sweet!

You can look ahead to the JavaScript implementation here : DomStorage.js

The JavaScript implementation supplies the following interface to window.localStorage and window.sessionStorage :

interface Storage {
readonly attribute unsigned long length;
DOMString? key(unsigned long index);
getter DOMString getItem(DOMString key);
setter creator void setItem(DOMString key, DOMString value);
deleter void removeItem(DOMString key);
void clear();
};

Implementing this on the native side was a little different than a typical plugin. Many of the calls are synchronous, so I needed to have some data up front, and a method to call native code synchronously. Note: I could have implemented the entire interface using the FileAPI, but this would mean storing the entire key/value set in JavaScript so that it could be called synchronously. After some experimentation, I discovered that even though C# code cannot return a value to a JavaScript call to ScriptNotify, it can set a value from C# before execution is passed back to JavaScript, so we can mimic the behavior of a return value.

In this example, the value of this._result is set before window.external.Notify returns, so it is available as a return value from the JavaScript function.

var retVal = null;
if(this.keys.indexOf(key) > -1)
{
window.external.Notify("DOMStorage/" + this._type + "/get/" + key);
retVal = this._result;
this._result = null;
}
return retVal;

Note: While this works, perfectly, we do have to be careful that we don’t again call ScriptNotify in the callback to set the _result value, otherwise we could overflow the stack with multiple nested calls.

More to come soon, done a lot of blogging and not enough coding for today. Stay tuned.

Announcing PhoneGap for Windows Phone Mango

 

Over the last month and a bit, Nitobi has been working closely with Microsoft to bring PhoneGap to WP7 devices. I am happy to say that it’s now here, and ready for beta exposure.

The Genesis of PhoneGap for Windows Phone 7

 

Our starting point was the excellent work of Matt Lacey, who created the initial project and did the initial exploration of device functionality. The upcoming Windows Phone Mango update to devices brings a rich set of HTML5 features and IE9 to the device.

Thanks to Microsoft sponsorship, Sergei Grebnov has been making contributions to the code and has implemented the MediaCapture and Camera APIs. This is Sergei’s first foray into PhoneGap, but he has proven to be a valuable asset to the project and was up to speed quickly.

Nitobi has dedicated two developers to the project, myself and Herm Wong. We’ve been busy dusting off our Sliverlight+C# skills and implementing the other APIs.  ( the infamous Shazron has also jumped in just this week )

Here’s the outcome!

Some code  here : https://github.com/phonegap/phonegap-wp7

Some more info here: http://bit.ly/PhoneGapMangoIntro

What You’ll Need to Get Started

 

So you want to get on it, enough talk? You will need Visual Studio 2010 with the “WP7 SDK” : http://create.msdn.com/en-us/home/getting_started installed (the free express version works fine )
Detailed instructions will be posted shortly as a getting started guide on PhoneGap.com, in the meantime :

  • fork/git or download/unzip the repo to your harddrive
  • copy the file GapAppStarter.zip to the folder : \My Documents\Visual Studio 2010\Templates\ProjectTemplates\
  • Launch Visual Studio 2010 and select to create a new project ( PhoneGapAppStarter should be listed as an option, give it a name )
  • Right-Click on the solution and select Add->Existing Project, and add the project :  framework\WP7GapClassLib.csproj from the downloaded repo
  • Right-Click your main project and “Add Reference” to the WP7GapClassLib project
  • build and run!

 

Where Are We ? What APIs Are Done?

 

Here’s an overview of where we’re at:

  • Accelerometer
  • Camera
  • Compass (unit testing is waiting on us having a device that supports compass)
  • Contacts
  • Events (partial, still underway)
  • GeoLocation
  • MediaCapture
  • Connection
  • Notification

These have all been implemented per the spec, and function as expected with some quirks being added to the documentation as you read this.

The ‘deviceready’ event is fired on startup, and like other device platforms, is the signal that you can begin making PhoneGap API calls.
The GeoLocation API did not require any work, as IE9 implements the spec as defined by W3C.

Still to come :

  • File
  • Storage

How Does it Work? A peek under the hood.

 

PhoneGap-WP7 includes a library project which contains the core functionality, and you reference this project from your own project. Your own project will include the www folder which is where your Gap html/js/css will live. All files in the www folder must be added to the project in Visual Studio and marked as content so they will be packaged with your app when it runs on the phone. We will be releasing a Visual Studio template to allow you to simple select NewProject->PhoneGap-WP7 project and auto-magically be on your way.

Packaging of applications is quite different on WP7. All resources (your PhoneGap js/html/css code in the www folder) are packaged into the XAP as resources but cannot be accessed directly at runtime, so an extra unpackaging step is required.
When the app is first run, all resources listed in the manifest are copied from the binary XAP to IsolatedStorage. IsolatedStorage is a per application File location, similar to a per app Documents folder in iOS. IsolatedStorage is managed per app, so separate applications cannot interact with the same document store. We are working to make this as transparent as possible, so your workflow does not have to change. Build scripts and tooling will eventually take care of the dirty work, but for now you will be building directly from Visual Studio.

After unpackaging the contents of the www folder, your www/index.html file is loaded into an embedded headless browser control. This is essentially the same paradigm as other platforms, except here it is an IE9 browser and not a webkit variant. IE9 is a much more standards-compliant browser than previous IEs, and implements commonly used html5 features like DOMContentLoaded events, addEventListener interfaces, and CSS3. Be sure to use to get the html5 implementation otherwise the browser may fallback to a compatibility mode, and your code will likely choke and die. You should also use in your html .

Gotchas + Known Issues

 

IE9 does not expose touch events, or even mouse events to JavaScript. The only UI event that is available to your code is the click event. This means that many interfaces that are based on scrolling libraries and a WebKit DOM will not function as expected. The browser control DOES appear to support the CSS value of overflow:scroll, however there is no momentum and the scrolling feels sticky. I have done some quick exploration into exposing mouse events to JavaScript via the container and they do look promising. I will be moving on to this after I completed the Events API so your code can override the back-button and search-button.

IE9 supports localStorage, and sessionStorage, however they are not available to pages that are loaded without a domain. We will be investigating implementing this API ourselves, and managing the storage in IsolatedStorage.

Reporting issues, tracking progress and keeping up to date.

 

The project code is maintained on github at https://github.com/phonegap/phonegap-wp7, so you can follow it there. Any issues you come across can be filed in the Issue Tracker on github.
As with the other devices, general question can be directed to the PhoneGap mailing list, where the community is ready and waiting to help. For questions specific to Windows Phone 7, please include ‘WP7′ in the subject.

Will PhoneGap for WP7 support plugins?

 

This was a key focus, as keeping the architecture plug-able is a primary concern, and in my view, where the real power lies.
PhoneGap-WP7 maintains the plugability of other platforms via a command pattern, to allow developers to add functionality with minimal fuss, simply define your C# class in the WP7GapClassLib.PhoneGap.Commands namespace and derive your class from BaseCommand.

PhoneGap exec works in exactly the same way as other platforms :

PhoneGap.exec(callbackSuccessFunction,callbackErrorFunction, PLUGINNAME, PLUGINMETHODNAME, paramObj);

What is Left to Do? How can You Contribute?

 

Sergei has begun working on the File API, so you can expect full file access to create, modify, delete files as well as upload/download to/from a server.
I am busily trying to wrap up some of the life-cycle events (Events API) so your application can be notified when the app is pushed to the background. I will be looking into exposing mouse events to JavaScript shortly after that.

If you have expertise in any of the Native portions, or JavaScript, you are welcome to fork the repo on github.

Keep in mind: PhoneGap can only accept pull requests from contributors who have signed the CLA so we can make sure that PhoneGap remains open source and free. PhoneGap is dual licensed as defined here : http://www.phonegap.com/about/license

Even if you don’t contribute code back, I/we would love to hear about your experience building with PhoneGap for WP7, good, bad or indifferent. Please direct your kudos, or comments to the Facebook page at http://www.facebook.com/PhoneGap. You are also welcome to contribute to the documentation, and wiki pages, got a great getting started tutorial? Let us know! Want to tell the world about your WP7 PhoneGap app? Let us know!

We will be posting new information to the blog as updates are made, as well as on the mailing list, and PhoneGap.com.

 

Forever Endeavor

-jm

WP7 – Good to know

When things stop working, and code won’t run you will continuously see a error : #80020006
You need to exit the app and open IE on the emulator, click the ‘allow or cancel’ button to send browsing history to MS.
After that, if you relaunch your app, js will run.
Seems this check applies to the embedded browser as well, although this may just be an emulator thing.