Friday, October 11, 2013

Phonegap Diaries: Technologies

Introduction

Here I’m going to review the programming technologies used in the Twentyfour Challenge.  These include:
  •         Html5
  •          CSS3
  •          Javascript
  •          JQuery Mobile
  •          PhoneGap

Html5

There’s not too much to say about Html5 as I only used a couple of features that are specific to it:  local storage and the <audio> tag.  I also used a specific tag that is crucial to all PhoneGap projects.
Local storage is incredibly easy to use.  I use it to store the game options for Twentyfour and to keep track of the high scores.  The code below saves the game options:

function storeOptions () {
 // must use JSON stringify here!
 localStorage["tfc.options"] = JSON.stringify(options);
}

Here’s the code that reads the stored options:

function loadOptions () {     
 // are options in localStorage?
 if (localStorage["tfc.options"]) {
  options = JSON.parse(localStorage["tfc.options"]);
  // Options that are not strings need to be converted
  options.difficulty = Number(options.difficulty);
  options.count      = Number(options.count);      
  options.soundEnabled = Number(options.soundEnabled);
 }
 game.numSystem = options.numSystem;
 game.difficultyLevel = options.difficulty;
 game.countProblems = options.count;
 game.soundEnabled = options.soundEnabled;
};

The tag is complemented by a simple DOM-oriented API to play the sound file that is referenced.  It is also very easy to use.  The sound file (applause) worked in the Chrome browser, the iOS simulator, and an iPhone 4 device running iOS6.  It did not work in my own Android device (Samsung Galaxy Stellar I200), my iPad2, and another iPhone4 running iOS7.  I know I did everything right so I decided not to advertise the applause function.

A crucial <meta> tag needed by PhoneGap (really just the html5 compliant browser) is:
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, minimum-scale=1, maximum-scale=1" >

There are many stackoverflow questions regarding the application’s web page being shown in a teensy-weensy font.  The solution is to add the above meta tag.

There’s one more thing that almost drove me crazy regarding a brower-based application – the back button.  The application runs as a “WebView” (Android terminology) where the browser does not display any “chrome”  (not Google Chrome, this is chrome like the back button, forward button, refresh, etc.).  This works fine on iOS but on Android there is a hardware back button.

I found that while playing a game of Twentyfour you must not use the back button at all as it destroys the state tracking that the app must perform.  I will discuss the solution later in this article.

CSS3

Most of the styling for Twentyfour comes from JQuery Mobile.  My hat is off to the professionals that developed CSS/html code that is portable across Safari, Chrome, and Internet Explorer, especially since the vendors of these browsers compete against one another.

I did, however, have to define a few styles for specific situations.  Here’s the problem “goal” which is really a button with some style changes.


The style changes are:

.goal-style   {
  text-align: center;
  background: chartreuse;
  ui-disabled: true;
}

 The trick to achieving this style is to add it dynamically when the page is rendered.  

            $('#problem-goal').addClass('goal-style');

The most important reason for learning CSS is due to the fact that JQuery uses its notion of a selector extensively.

Javascript

Ah, Javascript, how do I hate thee?  I speak these words as a Java programmer who trusts the statically typed language completely.  Remember that Twentyfour started as a native Android application that at its heart contained six classes with 775 lines of code (carriage returns counted here).  This includes a simple algebraic expression parser and evaluator.

Since I was skeptical of translating my Java code to Javascript by hand, I first sought an automated solution in the Google Web Toolkit (GWT).  Google created the GWT so they could create sophisticated browser-based applications (think Google Maps) in Java and then convert the client part to html/javascript.  I did get my 775 lines of java code translated by GWT, but then realized that there was no way to incorporate the generated javascript into a PhoneGap application.

So I hand translated to Javascript using techniques documented by David Flanagan in “Javascript: The Definitive Guide.”  It resulted in six classes and 588 lines of code.

Yes, there were type conversion surprises during development, but thorough testing flushed them out.  I developed unit test cases for the important code and gained the desired degree of confidence in the reincarnated algebraic expression parser and evaluator.

On every page of the application I included all of the Javascript files of the application (including JQuery Mobile files).  This was recommended in various books and Internet articles that I read.  It also benefits the use of a Javascript debugger.  Chrome, for example, will not allow you to set breakpoints on a page if it doesn’t see Javascript included on the page.

There are a couple of takeaways from this:
  1.        You must order your Javascript includes avoiding forward references.
  2.        You have to live with an enormous number of global variables.

JQuery Mobile

The technology I had the most difficulty with was JQuery Mobile (JQM).  The technology (including JQuery itself) has been going through many rapid revisions.  And there is the fundamental fact that JQM loads a document into the browser’s DOM and manipulates that one DOM thereafter.  This means that you get one chance to set up your event handlers.

Let me backtrack and try to re-express myself.  For the longest time I could not get my JQM page events to fire properly.  My stackoverflow searches resulted in conflicting information:  “use ‘bind’ on the pageinit event.”  “No use ‘on’ event.”  “Sorry you’re both wrong use ‘delegate’.”  No matter what I tried the JQM event never fired off my handler code.

Then I realized that the DOM is created exactly once by JQM and just updated when new pages are loaded via AJAX (really HJAX here).  The “binding” code that worked for me is shown below.

$(document).delegate('#index', 'pageinit', function() {
  console.log('#index: pageinit');
  // local event handlers
  $('#play').on('click', function() {
    console.log('play clicked');
    startGame();
  });
});

This breakthrough got me off the dime so I could learn the JQM widgets and events.  The most confusing event is one of the most important – the ‘click’ event.  Due to the nature of clicking using a mouse versus tapping on a touch sensitive screen, JQM differentiates separate events: ‘tap,’ ‘click,’ and ‘vclick.’  I started with ‘click’ but found it introduces an annoying 300 ms delay which isn’t good for rapid play.  So I switched to ‘tap’ which has no delay by occasionally has its own unwanted side-effects (ghost clicks).  ‘vclick’ wasn’t any improvement so I left the implementation with ‘tap.’  I finally learned that 'tap' works fine as long as you immediately stopped event propagation.

// event handlers
  
$("#score-ok-btn").tap (function(e) {
  e.preventDefault();
  gamePauseAudio();
  $.mobile.changePage('index.html');
});

Another surprise from JQM is that when you manipulate one of its widgets you must explicitly tell JQM to refresh its display of the widget.

$('#num-probs').val(game.countProblems).slider('refresh');

There were tons of stackoverflow questions asking, “Why doesn’t my updated widget show the update?”  Answer: “you didn’t refresh it.”

PhoneGap

As I mentioned in a previous blog PhoneGap gives you free packaging of your browser application and some level of Javascript access to native device APIs.

I thought I could live without any need for device-specific API but that Android hardware “back” button was a source of much aggravation.  If the user clicked in the middle of a game the entire game state would be invalid and many Javascript errors would occur.

So the back button became my nemesis as it has been forever for web developers.  I thought of several approaches:
  1. Disable the back button
  2. Manipulate the browser’s stack of “back” pages
  3. Catch every page transition and only allow the transitions for a “normal” game
  4. Detect when the hardware back button was pressed
Well #1 is prohibited.  #2 is difficult given the DOM APIs available.  #3 requires a lot of careful programming and is very brittle.  #4 is supported by PhoneGap.  After exploring #1 through #3, I found A PhoneGap API (see the Events API)  that solved the problem completely.  When the hardware back button is pressed on Android (iOS doesn’t have this) then just jump to the application homepage.  Thank you, PhoneGap!

PhoneGap also does the packaging and in this area it encourages you to use Adobe’s PhoneGap build service.  I did not use this approach for a couple of reasons:
  1. It costs money (there is a limited free plan)
  2. You need to package, deploy, and test your app on real devices before a release build.
The build service drives off the application’s config.xml file.  I discovered more documentation on config.xml at Adobe’s build site than I did at W3 Consortium (there’s a minor standard for widget packaging) and at the PhoneGap site.

It is not clear to me if the PhoneGap CLI tools process config.xml the same as the PhoneGap build service.

Summary

There’s a lot of technologies involve here.  JQuery Mobile keeps its promise for great looking portable UIs across mobile clients (Javascript too).  And PhoneGap delivers in its packaging for specific platforms.

Other postings:



Phonegap Diaries: Tools

Introduction

Twentyfour Challenge evolved from a native Android application written in Java using the Android SDK within Eclipse to a PhoneGap application where DreamWeaver (DW) is the main development tool.

This article explains the tools used to create the new, portable version of Twentyfour Challenge.

Tools

PhoneGap (2.9.6)

PhoneGap has two main functions:
  •          Provide javascript access to device specific APIs
  •          Provide packaging for targeted platforms

STS (2.9.2-RELEASE)

Springsource Tool Suite (STS) is a distribution of Eclipse from Springsource.  After the Android Development Kit (ADK ) is installed it is used to tweak the Android configuration files and generate the final package.  It also allows you to configure Android Virtual Devices (Android phone emulators) for testing.

Theoretically Eclipse is not needed as PhoneGap's Command Line Interface (CLI) does all of the work needed to produce a package, but that’s just in theory.

XCODE (4.6.3)

XCODE is the primary OS X and iOS development tool.  Its role is similar to that of STS but for targeting iOS platforms.  The iOS platforms include iPhone and iPad (all hardware variants).

DreamWeaver (CS6)

Although not strictly required, DreamWeaver is the best WYSIWYG tool for html/css web site creation.  A PhoneGap application is basically a web site running off the file system on the target platform

Additional Tools

These additional tools were used for special purpose tasks during the development project:
  •          Eclipse Javascript Project plugin
  •          Google jsTestDriver plugin for Eclipse
  •          Eclipse Groovy plugin
  •          iPhone and Android emulators
  •          Google Chrome developer tools
  •          Ripple emulator (a Chrome extension)
  •          Gimp
  •          Subversion 

Eclipse comes bundled with the Javascript plugin which gives IDE support for Javascript programming.  And the support is surprising good in terms of syntax error checking and autocompletion.   The one thing that’s missing is the ability to “Run as javascript project…”  (a search shows that there is a plugin to do this.  It involves running Rhino on the JVM).

Google has a code project called jsTestDriver that allows the development of unit tests for javascript code.  jsTestDriver  can be run from the command line, but there is also an Eclipse plugin that you can download and configure.  I regard unit testing as essential for the complex Javascript library that I developed for Twentyfour Challenge.

I used the Eclipse Groovy plugin to develop a groovy script that translates the 24 problem files from xml to json.  I did not want to do this by hand, and I knew that Groovy was ideal for such a translation.

The primary development tools (Android SDK and XCODE) deliver the phone emulators.  When these are launched from the IDE you can see output (console.log output) during testing.

The best productivity tools that I used were the developer tools within Google Chrome.  The only trick is that you must launch Chrome such that you can link to files residing on the file system.  This requires launching Chrome as follows:

open -a 'Google Chrome' --args --allow-file-access-from-files

The Ripple emulator was a late addition to the list.  It emulates the PhoneGap device specific API calls that your application makes.

Gimp is an open source tool that competes against Adobe Photoshop.  Since I had paid (educational discount here) for Adobe DreamWeaver, I didn’t want to pay for Photoshop.  Besides I’m not a graphics artist and can get by with Gimp.

Subversion is your good old version control software.  Use git if that’s your favorite.

Tools Not Used

I had the opportunity to use some cloud-based tools, but I choose not to use them.  They include the Adobe PhoneGap Build service and a testing service like SauceLabs.

I figured I had to use the emulators anyway so why hassle with cloud-based services that can potentially lead to monthly service fees.

Summary

That is a long list of tools.  I can't say that I've mastered them all.  You no longer use Eclipse and XCODE as editors and the parts that you do use like configuring Android Virtual Devices or code signing in XCODE are full of extremely frustrating dialogs.

All of the tools are all free with the exception of DreamWeaver.

"Wait!" I hear you say, "what about JQuery Mobile?"  I consider JQM a library and will discuss that in the Technologies posting.

Other postings:





Phonegap Diaries: Intro to 24 Challenge

Introduction

In order to get started in mobile development I appropriated a popular math game called "24" (I call mine "Twentyfour Challenge". Google play. iTunes store) and turned it into a native Android application (this was very unoriginal as there are many versions of this game out there).

Doing this required climbing a steep learning curve as there is a vast, new API to learn.  But at least I could program in Java using the familiar Eclipse IDE.  I released my app to Google Play store last December (2012).

But wouldn't it be great to re-write Twentyfour Challenge as a portable HTML5 / javascript application?  I decided to do this in the summer (2013).  I also decided to write a summary of my experience doing this re-write.  I call these the "PhoneGap Diaries." 

Here are the topics covered:


Friday, June 14, 2013

Don't Stand So Close to Me


I have this recurrent dream. A hot, female undergraduate is asking me what she has to do to boost her grade at the end of the semester. We're alone -- older male teacher and young female student. There's even background music to this scene and it's "Don't stand so close to me" by The Police. But I am getting ahead of myself. Let's start at the beginning of the semester.

The C++ course was not what I wanted to teach. But the assistant dean asked me just that, and it's best for an adjunct teacher to never say "no" to a course offering. So I find that there are 24 students enrolled including one female. This heavy imbalance is not unusual as the computer industry is male-dominated. Since it was the Spring semester I could count on most of the students being in their early twenties. For some reason the older, and frequently ex-military, students take my class in the Fall. I can't explain why the older students appear in the Fall, while the younger students come out in the Spring, but an attitude difference is readily apparent. The younger students just treat their college courses like high school courses as in "what is the least amount of work I can do to get a good grade?" The older students want to learn something in order to get a job.

This Spring my male dominated roster showed a wide range of programming skills. Some were decent programmers already, while others were unprepared having bluffed their way through the prerequisite courses. Most were in the middle.

In the decent programming skills group was Vince who proclaimed out loud the first class that he had eight years of programming experience. This programming veteran looked like a caricature right out of Mad Magazine having a pimple-laced face and wildly angle teeth. He talked boastfully about all of his experience setting up servers and compiling open source programs with his custom changes. The trouble was that Vince just did not want to listen to my lectures and do my assignments.

Also in this decent programmer group was Dan. Now Dan is my all-time favorite student. But it's not because he worked the hardest or got the best grades. It's because Dan always listened to my lectures and he always nodded in agreement to whatever I said. I would look around the classroom and see that students were either looking at me with no expression or staring at their computer screens. Dan was the one student I could count on to be paying attention and nodding affirmatively at all times. What a way to send positive energy back to the teacher.

Let me use Ross as an example of one of the bluffers in the class. Ross always came in about 15 minutes late to class. Since I make all of my announcements at the beginning of class this means that he never heard a single announcement. He would do the least amount of work possible, yet was always seeking extra credit for anything and everything. I had to continually extend the deadlines for quizzes and assignments for him because he never turned anything in on time.

The solo female, Amanda, was definitely in her early twenties. She kept to herself and browsed the internet while I was lecturing. I can always tell when a student is on Facebook or doing e-mail. The student's face is just locked on the screen with fingers tapping on the keyboard. They are definitely not paying attention to me. Why should they? My years of programming expertise just can't make up for my monotone voice. And if you’re not into programming, this stuff is boring.

I know I can do something about this. I can use the teacher control software to put my screen on all of the students' computers. I don't do this for a couple of reasons. It would piss them off so that they hate me more. Or, they would just switch to their smartphones and continue to ignore me.

Well the middle of the semester comes around and I give my open-book midterm exam. I think it's really easy, but then again I know this stuff inside-out. I'm amazed at how poorly some of my best students do on the midterm. Did they coast because it's an open-book exam? Did they just fail to study? I'll never know.

As the course drags on I notice that Amanda hasn't showed up for weeks. She hasn't dropped the course but she's behaving like she has. I send an e-mail to her as I would for any student who's acting like he/she is done with the course. No reply.

Well it's a week before finals and I finally scan the student's grades. I can see that Amanda is at the bottom having done about half of the assignments and half of the on-line quizzes. To my surprise she sends me an e-mail the same day and says she wants to meet me during my office hours. I agree and set a time for us to meet.

She shows up wearing exercise clothes: skin-tight nylon stuff that shows off every curve in her very curvy body. She sits opposite to me and says "Is there anything, I mean anything, I can do for extra credit?"

Now I'm getting nervous for a couple of reasons. One is that another adjunct might walk into the shared office where we are alone. The other is that I'm not exactly sure what she's willing to do for "extra credit."

So I say, "Amanda, did you ever hear of Riemann's zeta function? It's a pretty simple polynomial function but it's amazingly complex when its domain is the complex number system."

Amanda looks at me with utter non-comprehension as if I were speaking Greek to her. Greek, that's funny because the zeta function is stated with many symbols from the Greek alphabet.

"Well the zeta function expands to an infinite polynomial and like any polynomial we're interested in where there are zero values."

Now Amanda has started to lick her lips and blink her eyes to try to distract me, but I'm getting excited because I think I'm explaining the zeta function so well.

"Mathematicians have found many of the non-trivial zeros of the zeta function and since the domain is complex numbers the zeros have a real and an imaginary part. For all of the non-trivial zeros found thus far it's true that the real part is equal to 1/2. Isn't that amazing?"

Now Amanda is looking at me with serious confusion in her eyes like, "What the hell is this guy talking about? He must be hopeless."

"Okay, of all the non-trivial zeros found thus far the real part is equal to 1/2 -- but is this true for all possible non-trivial zeros? The assertion to the positive is called the Riemann Hypothesis and it hasn't been proven or disproven for over 150 years. What do you think?'

Amanda answers, "I think I don't understand. Besides what does this have to do with getting extra credit for the course?"

"I understand your confusion. I didn’t make clear the distinction between trivial and non-trivial zeros. The trivial zeros turn out to be all of the negative even integers like -2, -4, -6, etc. That's a consequence of the fact that zeta value of the quantity one minus s (e.g. z(1-s)) equals a value that has the sine function as a multiplicative factor and the value of that sine function is zero precisely at those negative even integers."

Amanda says, "I still don't understand. What can I do?"

"Well I was thinking that if you contributed to solving the Riemann Hypothesis, even a small contribution such as a tangential theorem, then I couldn't help but give you an A for the course."

Amanda left without a word.

I call out after her, "Did I say something wrong?" And she didn't ever stand close to me.

Tuesday, April 30, 2013

My Second Sprint Triathlon

Glutton for punishment or dedicated athlete? I won't know until my sports obituary is written, if it ever is. Anyway I completed my second UMLY Sprint Triathlon last Sunday in 1 hour 35 minutes and 55 seconds -- a four minute improvement over 2012.

2012 2013
Swim 13:00 13:07
Transition 1 5:27 5:20
Bike 44:17 41:44
Transition 2 2:38 2:33
Run 34:38 33:12
Total 1:40:00 1:35:55


The best way to contrast this year with last year is what I did not do while training.

2012 2013
Taught at 2 locations Taught at 1 location
Trained for 4 months* Trained for 2 months
Worked at Vanguard
Argued with my boss**

*The intense training left me irritable at work.
**My boss was himself an irritation.

I bought a new bike (GT Tachyon 3.0) and while shopping I was amazed by all of the categories of bikes there are (road, fitness, hybrid, mountain, comfort, etc.) let alone the various brands. I bought a fitness bike which has straight handlebars because I hate the curved handlebars that force you to bend over. The new bike worked great as I did not dismount once and pedaled up two very steep hills.

I started the 5 km run same as last year. My legs and buttocks were tied in knots and I had no desire to run. But again I recited the runner's mantra "put left foot in front of right foot, put right foot in front of left foot, repeat" and finished the race.

So in 2013 I improved my time over the previous year by 4%. If I keep this up for the next 25 years I will finish in no time!

Kudos to the Y and all of the volunteers who made this an amazing event. The Y closed the 50 m outdoor pool to get it warmed up (literally) for the race. The signage over the 13 mile course was excellent. And the cheering was motivating.