cgack

Web Developer. JavaScript Enthusiast. Scientist from Earth.

Remote Debugging Tools

Recently I have been working on some mobile content for a couple of my personal projects. And since working on the front-end of these projects involves spending some quality time with developer tools, I have also been spending some quality time utilizing a few different remote debugging tools. In the last few years the remote debugging tool category of software has grown rapidly which makes deciding on the best tool, somewhat similar to finding your favorite dev tools setup in your browser of choice. Just as some folks prefer debugging their front-end with Firebug, Opera Dragonfly, or Chrome Developer Tools (WebKit Inspector), there is now a similarly robust selection for remote debugging for mobile devices.

Built by Remy Sharp, JsConsole.com is perhaps the simplest and most accessible tool for remote debugging. Simply include the remote.js file in your html,

<script src="http://jsconsole.com/remote.js?IDENTIFIER"></script>

navigate to jsconsole.com, “:listen”, and you now have access to your remote device. Works splendedly, but doesn’t have all the bells and wistles that come along with the advancing browser dev tools. I use this tool a ton for remote debugging work, especially since it works across browsers on my mobile device. Another tool that I have utilized and is quite popular due to its association with PhoneGap, is Weinre or WebKit Inspector Remote. With this you simply run a server locally that will allow you to debug remotely utilizing a set of the WebKit Inspector toolset (Google Chrome, Safari) - provided you supply a target.js script in your source. Again this is not a full set of the tools which are normally available to a Chrome Dev Tools, Firebug, Dragonfly user, but is quite adequate and useful on multiple target browsers. I rarely utilize Weinre, but many developers find it a critical part of their workflow.

Opera Dragonfly has a great remote debugging experience baked into their tools. One simply tells Opera Desktop to initiate a remote listening session, then Opera Mobile “opera:debug”, and you can inspect your remote page in Dragonfly. Honestly, I have limited experience here, because I rarely utilize Dragonfly, even though the tools are quite robust.

So what is my go to remote debugging tool today? Chrome. I am most comfortable with the Chrome Dev Tools in all my other debugging for a number of reasons including the continuous insertion of handy new features. So once I upgraded my phone to Android 4 (Ice Cream Sandwich) - which is required to utilize Chrome For Android - I have been happily utilizing the full suite of Developer Tools in Chrome to inspect my mobile app on my Android device. Again, the best solution for me because I can utilize the same toolset for desktop or mobile debugging. Its pretty simple to setup, just get your Android device set up for usb debugging in both the Android settings and Chrome settings, then (via the Android SDK) setup a debug bridge that will forward your console to a port of your choosing allowing you to open localhost:9222 which shows all your tabs open on your phone, ready for inspection. Start listening on that port using a script like this in your terminal:

adb forward tcp:9222 localabstract:chrome_devtools_remote

Rather than go through my terminal command history to find the command and possibly change the port, I aliased the command in my .bashrc file so anytime I hook up my phone I can type cremote 9222 in the terminal and inspect away

function cremote() {
    adb forward tcp:$@ localabstract:chrome_devtools_remote
}

From there its on to your browser to find and inspect away to your hearts content. This remote debugging space is growing quickly, the upcoming version of many toolset have this capability built in directly, things like jsBin (v3), jsfiddle, Firefox dev tools, Adobe Shadow, Trigger.io’s remote inspector, and many others I’m sure are all available, or will be available to utilize as a remote debugger. So the developer wins in the end with a host of choices to choose from so they can find that which fits their needs and workflow.

DeviceOrientation Events

The Mozilla Dev Derby is a pretty cool thing. Developers from around the world can openly add any demo to the site, and if their demo lines up with the prescribed derby for the month, they are automatically entered to win a prize (t-shirt, cool bag, android device). I decided I would enter again for the January 2012 derby based on Orientation. I made two demos.

catch

The first one called “Catch” which you are attempting to catch a randomly generated ball in the shortest amount of time possible. I have personally found it incredibly addicting to get the perfect game, or at least my best attempt at it and I even wrote the source code. What I learned in developing this app was a couple of things. One, there isn’t a ton of documentation on the web about the DeviceOrientationEvent. Two, its pretty straightforward to detect the orientation and utilize it to move an object. Here is the basic of my app:

 /*orientation stuffs*/
var initOrientation = function() {
    var count = 0, gam = 0, bet = 0;
    if (window.DeviceOrientationEvent) {
        window.addEventListener("deviceorientation", function(e) {
            //gamma = left to right
            //beta = front back
            //alpha = compass dir
            count = count + 1;
            gam += e.gamma;
            bet += e.beta;

            if (count === 0 || count % 10 === 0) {
                orientationYo(gam, bet);
                gam = 0;
                bet = 0;
            }
        }, false);
    }
};

//handle orientation
var orientationYo = function(ltr, ftb) {
    coor.x = coor.x + ltr;
    coor.y = coor.y + ftb;
    if (!gameState.victory && gameState.playing) {
        tgt.move(coor);   
    }
};

so that handles the detection of the orientation event, next I simply added the move call to my target (tgt) which looks like this:

var tgt = {
    isDrawing: false,
    collided: false,
    start: function(coordinates) {
        this.drawIt(coordinates);
        this.isDrawing = true;
    },
    drawIt: function (coordinates) {
        ctx.clearRect(0, 0, canvasWidth, canvasHeight);
        ctx.fillStyle = b2_color;
        ctx.beginPath();
        ctx.arc(coordinates.x, coordinates.y, 25, 0, Math.PI * 2, true);
        ctx.fill();
    },
    move: function(coordinates) {
        if (this.isDrawing) {
          this.checkBounds(coordinates);
          this.drawIt(coordinates);
        }
    },
    finish: function(coordinates) {
        this.isDrawing = false;
        ctx.lineTo(coordinates.x, coordinates.y);
        ctx.stroke();
        ctx.closePath();                
    },
    checkBounds: function(coordinates) {
         if (coordinates.y > bound.y2) {
            coordinates.y = bound.y2;
          } else if (coordinates.y < bound.y1) {
            coordinates.y = bound.y1;
          } else if (coordinates.x > bound.x2) {
            coordinates.x = bound.x2;
          } else if (coordinates.x < bound.x1) {
            coordinates.x = bound.x1;
          }
    }
};

collision detection is handled by my randomly placed bouncing ball, which detects when the target ball moves into its path:

checkObjectCollisions: function() {
    var imgData = ctx.getImageData(this.position.x + this.velocity.x1, this.position.y + this.velocity.x2, r, r),
        pix = imgData.data;
    for (i = 0, n = pix.length; i < n; i += 4) {
        if (pix[i] !== 0) {
            this.collided = true;
            if (Math.abs(this.velocity.x1) > Math.abs(this.velocity.x2)){
                this.velocity.x1 = -this.velocity.x1 * drag;
            } else {
                this.velocity.x2 = -this.velocity.x2 * drag;
            }
            break;
        } else {
            this.collided = false;
        }
    }
}

I am pretty happy with the game, its clean and works nicely. You can check it out here

compass

The other is a simple web compass where I utilize the DeviceOrientationEvent to get the cardinal direction your phone or device is facing. There are two cool (in my opinion) things that happened here. One is that to me it seems the device orientation event as defined states that the DeviceOrientationEvent.alpha ranges from 0 to 360 which to me is a 361 degree circle. The second is that I was able to utilize the offline caching capabilities of the modern web to make the compass available to a device event when not connected to the internet. This is done in minimal lines of code. The HTML and JavaScript are as follows:

<!-- This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this file,
You can obtain one at http://mozilla.org/MPL/2.0/.  -->

<!DOCTYPE html>
<html manifest="compass.appcache">
<head>
<meta charset=utf-8 />
<title>Cardinal Direction Compass</title>
<style>
  .pointer {
    height: 0;
    width: 0;
    border-left: 3em solid transparent;
    border-right: 3em solid transparent;
    border-bottom: 12em solid black;
    margin: -10px 0 0 -40px;
    top: 40%;
    left: 50%;
    position: absolute;
  }
  .n {
    top: 20%;
    left:50%;
    position:absolute;
    font:8em Helvetica;
    margin: 0 0 0 -40px;
  }
  </style>
  <script src="js/jquery.js"></script>
</head>
<body>
  <div class="n">N<br><br><br><br>S</div>
  <div class="pointer"></div>
<script>
        $(document).ready(function() {

          var rotate = function (deg) {  
              $(".n").css({ "-moz-transform": "rotate(0deg)"});
              $(".n").css({ "-moz-transform": "rotate(" + deg + "deg)"});

              $(".n").css({ "-o-transform": "rotate(0deg)"});
              $(".n").css({ "-o-transform": "rotate(" + deg + "deg)"});

              $(".n").css({ "-ms-transform": "rotate(0deg)"});
              $(".n").css({ "-ms-transform": "rotate(" + deg + "deg)"});

              $(".n").css({ "-webkit-transform": "rotate(0deg)"});
              $(".n").css({ "-webkit-transform": "rotate(" + deg + "deg)"});

              $(".n").css({ "transform": "rotate(0deg)"});
              $(".n").css({ "transform": "rotate(" + deg + "deg)"});
          };
          if (window.DeviceOrientationEvent) {
            window.addEventListener("deviceorientation", function (e) {
              rotate(360 - e.alpha);
            }, false);
          }

        });
        </script>
  </body>
</html>

The final point I’d like to make is that due to what I thought was minimal documentation, I participated in a Mozilla Doc Sprint last weekend to update the Documentation surrounding the DeviceOrientationEvent. Doing my part in the web development community was both rewarding and a learning experience. I encourage anyone to try it out as well.

Widget

I have lately been looking to become more involed with open source projects and for starters I have been looking at jQuery UI and jQuery Mobile. Both are amazing projects and share many of the same characteristics in their code. This is because in both cases, the majority of the functionality is inherited from the jQuery UI widget factory. If I’m going to become involved in this project I should understand how this works, so the following is my breakdown of the code as I understand it.

The widget factory looks like the following:

$.widget = function( name, base, prototype ) {
    var namespace = name.split( "." )[ 0 ],
        fullName;
    name = name.split( "." )[ 1 ];
    fullName = namespace + "-" + name;

    if ( !prototype ) {
        prototype = base;
        base = $.Widget;
    }

    // create selector for plugin
    $.expr[ ":" ][ fullName ] = function( elem ) {
        return !!$.data( elem, name );
    };

    /* OTHER STUFF */
}

I’ll get to the stuff in a second, but lets see what we’ve already learned here. First I see that widget can take up to three arguments (name, base, prototype), and example might be something like

$.widget("cg.awesomewidget, "ui.button", { /*...*/})

here name or “cg.awesomewidget” becomes the namespace and fullname so in my example I have namespaced it to “cg” with a fullname of “cg-awesomewidget”. I also see that we check if prototype is provided, if it is not we assume that we are not inheriting from a named widget, set the base parameter to prototype and set the base to the main $.Widget base object. Okay that sounds more messy than it is. Lets try to rephrase. The base is an optional parameter telling the widget factory we want to inherit from a known widget. In my example above its “ui.button”. If that parameter is not provided it simply pulls from the base $.Widget. So we know that any widget will carry the prototype base of $.Widget for starters. Now, what about this prototype? This is the base object literal that the widget makes its prototype. Sweet right? The next fun fact is that our widget gets its very own shiny new custom selector $(“:cg-awesomewidget”).

Next the object is constructed via the jQuery.extend() method as follows:

$[ namespace ] = $[ namespace ] || {};
// create the constructor using $.extend() so we can carry over any
// static properties stored on the existing constructor (if there is one)
$[ namespace ][ name ] = $.extend( function( options, element ) {
    // allow instantiation without "new" keyword
    if ( !this._createWidget ) {
        return new $[ namespace ][ name ]( options, element );
    }

    // allow instantiation without initializing for simple inheritance
    // must use "new" keyword (the code above always passes args)
    if ( arguments.length ) {
        this._createWidget( options, element );
    }
}, $[ namespace ][ name ], { version: prototype.version } );

here the $[ namespace ][ name ] object is merged together with the prototype.version into the existing constructor as described in the comments. Then the options are passed along to the base. Again this is done via jQuery extend.

var basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );

This is followed up with a call to $.each() that checks all the functions of the base and applies those to our new widget.

$.each( prototype, function( prop, value ) {
    if ( $.isFunction( value ) ) {
        prototype[ prop ] = (function() {
            var _super = function() {
                return base.prototype[ prop ].apply( this, arguments );
            };
            var _superApply = function( args ) {
                return base.prototype[ prop ].apply( this, args );
            };
            return function() {
                var __super = this._super,
                    __superApply = this._superApply,
                    returnValue;

                this._super = _super;
                this._superApply = _superApply;

                returnValue = value.apply( this, arguments );

                this._super = __super;
                this._superApply = __superApply;

                return returnValue;
            };
        }());
    }
});

After all of this its time to put it all together. The widget prototype is now set via extend where we extend our basePrototype (widget) merging in the new widget and prototype. The last thing needed is a call to $.widget.bridge() which creates an instance of the object.

$[ namespace ][ name ].prototype = $.widget.extend( basePrototype, {
    namespace: namespace,
    widgetName: name,
    widgetEventPrefix: name,
    widgetBaseClass: fullName
}, prototype );

$.widget.bridge( name, $[ namespace ][ name ] );

That concludes our walkthrough of the jQuery UI widget factory. Fairly amazing when you look at how simple it is to create a widget based on this. A simple example is a look at jquery.ui.tooltip.js

Collision Detection on Canvas

I was toying around with a bouncing ball on an HTML canvas the other day when I wanted to find an easy way to detect collisions. One thing that is easy is validating against the bounds of the canvas. This is done with a simple check on the bounds of the canvas as follows:

//this is a Ball object
if (this.position.y > bound.y2) {
    this.velocity.x2 = -this.velocity.x2 * drag;
    this.position.y = bound.y2;
} else if (this.position.y < bound.y1) {
    this.velocity.x2 = -this.velocity.x2 * drag;
    this.position.y = bound.y1;
}
if (this.position.x < bound.x1) {
    this.velocity.x1 = -this.velocity.x1 * drag;
    this.position.x = bound.x1;
} else {
    if (this.position.x > bound.x2) {
        this.velocity.x1 = -this.velocity.x1 * drag;
        this.position.x = bound.x2;
    }
}

You’ll see that if we get the Ball beyond the bounds of either axis we reverse the velocity vector (and for my example) I augment that vector with some drag. Then I start the Ball off (headed the other direction now) from the start of the boundary. This is straight forward and not too difficult to come up with. The same can be done for other shapes on the canvas which we do not wish for the ball to pass through. These again can be simple if we know the layout and the position of the target walls (think floating boxes). Where this gets to a point where the shapes are not at right angles or the boundaries have become more arbitrary, I no longer want to calculate each possible collision point. I also do not wish to wrap the object into a larger boundary box to utilize for detection. So a more elegant solution can be found. If we, just before moving the ball, simulate the move and have another means for detection we can then change the trajectory of the object and send it sailing away. Here’s what we need. we need a ball sized snapshot of the canvas where we plan to put the ball on the next move. We then iterate through those pixels on the image and find ones that arent the color of our background (in my case non-white). To do this without also seeing the ball as a collided upon object, I’ll clear the canvas of the ball first. Here is the code:

//clear canvas, add shape
context.clearRect(0, 0, canvasWidth, canvasHeight);

context.fillStyle = "rgb(150,150,150)"; //not white
context.beginPath();
context.moveTo(200, 100);
context.lineTo(300, 125);
context.lineTo(250, 175);
context.lineTo(200, 200);
context.lineTo(200, 100);
context.fill();
context.closePath();

//now we check our next move for collision
var imgData = context.getImageData(this.position.x + this.velocity.x1, this.position.y + this.velocity.x2, r, r);
var pix = imgData.data;
for (var i = 0; n = pix.length, i < n; i += 4) {
    //check if we're not on a white pixel
    if (pix[i] != 0) { 
        this.collided = true; 
        //bounce away
        if (Math.abs(this.velocity.x1) > Math.abs(this.velocity.x2)){
            this.velocity.x1 = -this.velocity.x1 * drag;
        } else {
            this.velocity.x2 = -this.velocity.x2 * drag;
        }
        break;
    } else {
        this.collided = false;
    }

}

Thats it! Now we can throw our ball at a target. The demo I have is located at this jsFiddle.

Book Review: The Tangled Web

Browsers are not secure. They won’t ever be invincible to malicious attacks. Browser A does not serve the same set of security mechanisms as Browser B. These points are highlighted in Michal Zalewski’s book “The Tangled Web: A Guide to Securing Modern Web Applications”, but Zalewski, an expert in browser security and author of Google’s Browser Security Handbook, discusses in detail common and known vulnerabilities, providing hints and tips to keep web applications as secure as possible along the way.

The book starts with a relatively exhaustive dissection of the “Anatomy of the Web”, highlighting the history of the web, from HTTP up to Plug-ins such as Flash and Silverlight all while noting some of the varying browser implementations of many common web functionalities. For example when discussing the Content-Disposition Header, Zalewski notes that these headers “are truncated at NUL by Internet Explorer, Firefox, and Chrome but not by Opera or Safari”,

In parts Two and Three of the book, the meat of browser security features are discussed in depth. Highlights include a detailed look at the Same Origin Policy for all aspects of the modern web, including Scripts, XHR, Cookies, and Plugins. Another intriguing look into browser inner workings was the sections on special psuedo urls such as about:, javascript:, and data: and how these can lead to interesting handlings of the origination of the requests across browser implementations. For example about:blank can be navigated to from an Existing non-same-origin page and have its origin inherited from the caller in Firefox, Webkit, and Opera while gaining a unique origin in Internet Explorer.

Perhaps one the most valuable parts of “The Tangled Web” is how Zalewski adds a handy “Security Engineering Cheat Sheet” to the end of each chapter. Having these quick tips at ones fingertips is a remarkable asset and great addition to the book. I could continue to outline the great parts of this book, and tout the security expertise that jumps from the pages, but the most important parts in the book are what each reader takes away. Whether its a small attack vector that a reader picks up on to close a vulnerability in their own web application, or an interesting fact about browser inconsistencies, each reader should gain something from this book. For me, the take away is that as a developer there is no magic bullet and we will always uncover new security holes in our web applications, either from poor programming, or new features of a browser’s implementation. And that our expectations should not be that we have a perfectly impenetrable web, or are capable of producing one. Zalewski puts it like this, “As the complexity of our online interactions approaches that of real life, the odds of designing perfectly secure software are rapidly diminishing”

Canvas, History, LocalStorage and More

A few months ago I entered the August Mozilla Dev Derby, which focused on the History API. I have seen some of the amazing things that the new changes to this interface have been able to make from folks like Facebook and GitHub but I wanted to try something a little different. I had been hacking on a simple drawing canvas and decided that I could leverage the History API to create a more application like experience. Since winning the Derby, I’ve seen my code improved and extended in a later Dev Derby Entry, and I turned it into a sample application for Mozilla’s new App experience. Here’s a peek into the process of creating a drawing demo like the one I created.

Basic Setup

Firstly, we’re going to need to create a canvas. This is pretty straightforward for those who have done this sort of thing before, but for a reminder that can look like the following

    <!DOCTYPE html>
    <html>
    <body>
     <div id="content">
        <canvas id="canvas" height="500" width="500"></canvas>
     </div>
    </body>
    </html>

Now that we have our canvas we can start to initialize it and get ready to roll with the fun features we’d like to demonstrate.

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    img, //more about this later
    blankCanvas = true; //this too

We now need to set it up to allow for drawing. This is done by adding a event listeners to the mouse events we’d like to watch.

window.addEventListener("mousedown", setupDraw, false);
window.addEventListener("mousemove", setupDraw, false);
window.addEventListener("mouseup", setupDraw, false);

You’ll notice the setupDraw function is called on all of these events. This function will grab the coordinates of our pointer (less the offset of our lovely #content div and send those to our draw object.

function setupDraw(event) {
    var cnt = document.getElementById("content"),
        coordinates = {
            x: event.pageX - cnt.offsetLeft,
            y: event.pageY - cnt.offsetTop
          };
    draw[event.type](coordinates);
};

Now time for the drawing I’ll go ahead and let you peek at the source so you can follow along.

var draw = {
    isDrawing: false,
    mousedown: function(coordinates) {
        ctx.beginPath();
        ctx.moveTo(coordinates.x, coordinates.y);
        this.isDrawing = true;
    },
    mousemove: function(coordinates) {
        if (this.isDrawing) {
            ctx.lineTo(coordinates.x, coordinates.y);
            ctx.stroke();
        }
    },
    mouseup: function(coordinates) {
        this.isDrawing = false;
        ctx.lineTo(coordinates.x, coordinates.y);
        ctx.stroke();
        ctx.closePath();
      }
};

You’ll see this object directs to an event type specific function and handles the coordinates parameters which are passed into the object. Following some basic canvas drawing steps for ctx.beginPath() -> ctx.moveTo(x,y) -> ctx.lineTo(x,y) -> ctx.stroke() -> ctx.closePath() we now have the ability to draw with our mouse. The “isDrawing” property is there to let us know to continue our strokes on mousemove. Now that we have an example that allows us to draw, we’ll move forward to make it more interesting by utilizing the History API and LocalStorage.

About the History API

One of the new features in HTML5 (an subject of the Dev Derby) is the additional features of the History API. These are history.pushState(data,title [,url]) and history.replaceState(data, title [,url] ) which are utilized to directly push (or replace) data in the session history. For the purposes of this demo we’ll be using pushState to add data, specifically the image data from the canvas, to the current URL. Now this alone is not enough we will also need to know when the current state changes, which is made accessible to us via the window.onpopstate event. This event fires when the browser gets a new history event. We can inspect the event to see if it contains a state and then load the data (hopefully our image) into the canvas. So to get things wired up correctly, its time to add a function to store the history.

var storeHistory = function () {
    img = canvas.toDataURL("image/png");
    history.pushState({ imageData: img }, "", window.location.href);
};

This grabs the data from the canvas in the form of a “data:image/png…” url. Then we create a new history state by pushing an imageData attribute for later retrieval. Now, before we add the calls to storeHistory to our drawing application, we need to do a bit of preventative maintenance. If we store this data and navigate backward without a reinitialization of the canvas, we will just draw the stored imageData onto the existing image. To us this will look like it isn’t working so we need to add an initialization function to reset our canvas.

var initializeCvs = function () {
    ctx.lineCap = "round";
    ctx.save();
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.restore();
}

Now we can go about the business of storing our history states. The code that follows will store history in two places. The first place it stores is if the canvas is blank it stores that before drawing anything. The second is on the mouseup event after the line is completed. Now our draw object looks like this:

var draw = {
    isDrawing: false,
    mousedown: function(coordinates) {
        if (blankCanvas) { storeHistory(); blankCanvas = false; }
        ctx.beginPath();
        ctx.moveTo(coordinates.x, coordinates.y);
        this.isDrawing = true;
    },
    mousemove: function(coordinates) {
        if (this.isDrawing) {
            ctx.lineTo(coordinates.x, coordinates.y);
            ctx.stroke();
        }
    },
    mouseup: function(coordinates) {
        this.isDrawing = false;
        ctx.lineTo(coordinates.x, coordinates.y);
        ctx.stroke();
        ctx.closePath();
        storeHistory();
    }
};

Awesome, now we have started storing history on the page with each completed line. Now we need to be able to see the results of this work when the history state changes. As I mentioned earlier this is done via the window.onpopstate event. We will examine the imageData of the state (if it exists) and place that image on the canvas as follows:

 window.onpopstate = function (event) {
        if (event.state !== null) {
            img = new Image();
            img.onload =function () {
                ctx.drawImage(img, 0, 0);
            };
            img.src = event.state.imageData;
        }
    };

Splendid, we now have a drawing tool that stores history so we can undo and redo drawings. But wait! What happens if I’m in the middle of a canvas masterpiece and my browser crashes? Lets handle that with localStorage. With localStorage we can store a named item locally independent of our session, so in the event of leaving the page, we can retrieve data from our previous encounter. In this demo I did a simple test of the window.localStorage object to see if we can store data, and then I store the latest image so upon return you’ll at least be able to recover that data. Here are the initializeCanvas and storeHistory functions with this additional feature added:

var initializeCvs = function () {
    ctx.lineCap = "round";
    ctx.save();
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.restore();

    if (window.localStorage) {
        img = new Image();
        img.onload = function () {
            ctx.drawImage(img, 0, 0);
        };
        if (localStorage.curImg) {
            img.src = localStorage.curImg;
            blankCanvas = false;
        }
    }
}

var storeHistory = function () {
    img = canvas.toDataURL("image/png");
    history.pushState({ imageData: img }, "", window.location.href);

    if (window.localStorage) { localStorage.curImg = img; }
};

You can see the full working demo in this jsFiddle.

Moving to Octopress

I have been toying with the idea to move away from blogger to another blogging engine. Since I’ve been doing most of my hacking via Github I have decided to move to Octopress. I have imported most my old posts and hopefully the conversion hasn’t caused too much trouble. The original posts can still be found on my blogger blog

Snakes in the Cloud


I used to think that building web applications in Python for Google’s app engine was reserved for a desktop development environment.  I had hacked a bit on an app or two and used the command line tools to test and publish to the app engine.  Then I discovered CoderBuddy.   CoderBuddy is a one stop shop for building python apps for the app engine.  Once signed in you can create a blank project, or get a head start with one of six template apps.  One template is of course a “hello world” app, but there are a  few other samples including 3 that come with some Django (arguably the go to MVC framework for python web applications).   I tested a couple of the template apps and found them to be quite useful.  The “Adrian Remembers Me” template creates an app that allows users to become members and sign in.   Here is a look at the editor with the main.py file opened for this project:


Each of these templates could be either a good launching point or reference for a new developer looking to quickly create a Python app.  Deploying to the App Engine is just a few clicks away with CoderBuddy.  So I “created” my Adrian Remembers Me app in one click and about two minutes later had my site running on the app engine at http://cgack2-coderbuddy.appspot.com/.  The ease of deploy along with the ability to upload files and download the project as a .zip I will definitely look to CoderBuddy for part if not all of my next project.

Cloud 9 Adds Heroku Support

One of my favorite online IDEs has added support for Heroku.  This is great news as I have enjoyed developing node.js applications in Cloud9 but felt that the main thing it lacked was a method to deploy directly to the cloud.  So I took it for a test run.  I signed in to Cloud 9 and created a simple hello world app, make sure you use the process.env.PORT to listen on so Heroku can deploy it properly.

Commit your changes via the Cloud 9 git interface.Then all you have to do is click the Deploy button in Cloud 9, sign in to Heroku, create your new instance, and deploy. If you haven’t created a package.json or Procfile (needed for Heroku deploy), Cloud 9 will create those for you. My hello world is at http://cheese.herokuapp.com/

Github Goes Ace (and Demos)

A week ago GitHub announced they were incorporating the Ace editor (which powers the Cloud9 IDE).  Since I am a fan of both Cloud9 and GitHub, I gave it a whirl on my GitHub Pages site and was not disappointed.  As advertised one can easily open a file for editing, preview the diff of your changes and commit.  I think it will likely become useful to edit posts when (if) I finally decide to move my blog from here at Blogger to Octopress (just because it looks fun).  For me, this is particularly useful for simple changes like those I have made to my demos and experiments.  Speaking of demos, I had created a simple drawing app using HTML5 canvas for my preschooler which evolved into a demo of the HTML5 History API thanks to a tweet by Christian Heilmann and subsequent read of his blog post.  I decided to use this History API to create the undo/redo functionality that I rely on heavily if i’m trying to draw something in a painting tool.  As a bonus I added a localStorage call that will recreate your last drawing if your browser closes or you are forced to leave the site for a while.  What does that look like:

 I entered the demo in the DevDerby, you can find it here.  I hope you ’like’ it too.  (note: I’ve only really tested my demo on firefox 5, 6, 7, and 8 as well as chrome 13 & 14, so your results may vary if you use a different browser)