Set up PhoneGap with Xcode 4(.0.2)

I had to set up PhoneGap on Xcode 4 yesterday and found many confusing, wrong, or just outdated pages describing how to do it.  I think they fixed some things in PhoneGap 1.0.0, so the install is much simpler than what these pages were saying.  So here is my version which worked for me:

  1. Download and install PhoneGap 1.0.0 on your mac.  Get it here.  This downloads a ZIP file.  Open it up and run the DMG file installation in the iOS directory.  The instructions I saw said to have Xcode closed at this point, which I did.
  2. Open Xcode and create your new PhoneGap project.  This will set up everything except the www directory.

    New Phonegap Project in Xcode

    New Phonegap Project in Xcode

  3. In Finder, navigate to your project (mine is in my home directory under ‘Xcode projects’).  Copy the www directory from <Macintosh HD>/Users/Shared/PhoneGap/Frameworks/PhoneGap.framework/ and paste it into your project in the same directory as the *.xcodeproj file (i.e., your project’s root directory)
  4. In Xcode, right click on the top-most project header (the blue-ish project header block that contains the entire project) and select “Add Files to <your project name>”.  Find and select the www directory that you just placed in your project, and make sure to change the “Folders” radio button to “Create folder references for any added folders”.  Press Add.  Your project should look like this:

    Final Project in Xcode

    Final Project in Xcode

That’s it.  Select the correct simlulator or iOS device scheme at the top of the project window (next to the RUN/STOP buttons), press RUN and the project should build and start up with the “PhoneGap works!” message.  Now you can continue doing whatever you were planning in the www directory.
UPDATE: there is a specific page for this on phone gap that I had not seen… go to it here.  There are still a lot of pages out there that have bad Xcode 4 info on them though!

Having one iframe watch for other iframes to load.

This is an issue that I thought was going to be straight forward using the jQuery ready function, but i could not get it to work.

The problem is simple: I want to watch a couple of iframes load and then do something once they are all done.

The “when they are all done” part is simple with jQuery Deferred objects.  A really good, quick tutorial on those is here.  Basically, I can pass however many Deferred objects I want to the jQuery.when( ... )  command.  When all of them “resolve” (i.e., when the are done doing whatever they need to do), the when command will continue with some “success” function or functions.  There are also options for when one or more Deferred objects fail, etc.  Read the tutorial… it’s good.  I created a javascript object that encapsulates the Deferred object and my method of resolving the object.  So I just needed to create one per frame I wanted to watch and feed them into the jQuery.when() function.

So for the “watch a couple of iframes” part I want to resolve my Deferred objects, instantiated in iframe A, based on iframes B, C, and D finishing loading.  I assumed this was a simple something like:

jQuery(top.B.document).ready( function() { ... resolve my deferred object ... } );

however, this did not work!  It did not matter that I put top.B.document (this is a path from top down to the frame, and then referencing the frames document), the call seemed to work on my local iframe’s document (iframe A in this example). I couldn’t find any information on this online, so if anyone knows more about it i’d love to hear it.

The solution:

I could have gone into each iframe and placed a document ready function that set a flag, and then read that flag from the iframe that is watching, but I wanted to keep this functionality clean and encapsulated in my object that was also handling the Deferred object.  I wanted to write it once — not X number of times.  Also, I know someone will mention “why are you using iframes at all?  use Ajax and blah blah blah”  I know, but you have to work with what you’re given sometimes… so i’m using iframes.

The solution I came up with is this (most of the Deferred object stuff is left out):

// Constructor
function MyIframeWatcherObject( contextPath ) {
...
// Get the path to the iframe we're watching.
this.contextPathToUse = contextPath || null;
...
{

MyIframeWatcherObject.prototype.resolveOnDOMloaded = function( ) {
	// Re-eval contextDocument each time because it is lost when page reloads.
	var contextDocument = document; //default
	try {
            if ( this.contextPathToUse )
		contextDocument = eval(this.contextPathToUse + '.document');
	} catch ( err ) {
		// Do nothing, use default as contextDocument as fallback for now..
                // Add error handling...
	}
	if ( contextDocument.readyState === 'complete' ) {
            deferredObject.resolve();
        } else {
            var self = this;
            setTimeout( MyIframeWatcherObject.prototype.resolveOnDOMloaded.call( self ), 100 );
        }

}

First, I resolve the contextPath that was passed in to get its document.  I do this each time because if I resolve it in the constructor and store it, I lose it if the page begins to reload again (it becomes undefined).  Then I check the readyState on the document and determine if I should resolve the Deferred object now, or set up another timer.  The setTimeout function is best here so that I am only setting up one more trigger each time and don’t have to worry about tracking it like I would with setInterval.  John Resig has a great tutorial on timers here — definitely a good read if you are not aware of how they function.

I’m not completely thrilled with this solution, but it works.  Please offer another way of doing it if you know one!

UPDATE: just an additional note. The document.readyState property looked like it was a cross-browser solution based on my quick google search — otherwise I would not have considered it. If you know differently, or know of bugs with this method, please let me know. Also, the opposite state of document.readyState == 'complete' is document.readyState == 'loading'.


Nice, simple tutorial on REST

I found a nice tutorial on REST by Dr. M Elkstein so i wanted to post it here:  http://rest.elkstein.org/


HTML5 Canvas: scrolling background and selecting/dragging shapes

I have been wanting to do this for a while and just had a chance to mess around with it this week.  I also had more motivation after spending Saturday in an “Designing (for) Interactions” workshop by Dan Mall, and hosted by RefreshPGH.  The key concepts were HTML5, CSS3, some jQuery, and generally getting some good experience on how people in the real world design web sites.  ( I really liked the boilerplate website, font squirrel, and of course A List Apart articles! )

Anyway, the thing I have been wanting to mess around with is the canvas.  I have recently been working on some mobile application prototypes and I am getting familiar with some of the components that exist there.  I wanted to see if I could put together a canvas demo to replicate a ScrollView, as well as being able to throw stuff in and manipulate it.  So here’s my example,with a little explanation.  It is a little hacked together because I put it together pretty quickly, so don’t grade on neatness and optimization —  many of the functions and comments are still very much what Simon Sarris wrote and I pieced things in around his code.  There are also bits and pieces of example code used from multiple places, like here.

The Details…

I started out with the code that Simon Sarris wrote for selectable shapes in a canvas.  After looking and understanding what he was doing, I refactored the code to be object oriented so it was more expandable.  My Goal: Understand the code well enough that I can edit it, make it expandable, and experiment with creating the “ScrollView” effect that I see on mobile devices.

Here is the canvas tag I used:

<canvas id="canvas_clickAndDragOO" width="400" height="300" style="border: 1px black solid;">
   This text is displayed if your browser does not support HTML5 Canvas.
</canvas>

The manipulation of the shapes is exactly how Simon wrote it, so check out his page for that explanation.  The main thing I added was the scrollable content.

Key Points:

  • I have two main things in the javascript:  a Canvas class and Shapes.  The shapes are pretty basic, so the Canvas class is the most interesting.  It maintains two canvas elements: one for the content and one for the view.  The content canvas is never added to the view and is only maintained behind the scenes as a javascript variable.  Everything is written to that content canvas and the context drawImage method is used to send a section of it to the viewable canvas.
  • To make the view ‘scroll,’ an X and Y value are maintained to specify the coordinates of the top left corner of the viewable canvas on the content canvas.  When the background of the canvas is clicked and dragged, this X and Y value are updated.  The draw method simply reacts to these new values and sends an new section of the content canvas out to the viewable canvas.  The viewable canvas is simply a window to a section of the content canvas.

The “content canvas” (hidden) is automatically created twice the size of the “viewable canvas” for this demo, but this and other things are configurable if you look at the Canvas object in the code.  Just include this in a webpage via a script tag and it should work with the canvas above.  (UPDATE: I pasted this here so it could be read and copied easier)

UPDATE 2:  This code doesn’t work on < IE8 using the excanvas.js library because that library does not support the getImageData function!  I would have to find a way around that in order for it to be backwards compatible.  Also, older IE browsers do not support the pageX and pageY properties on the mouse events. This issue can be solved quickly by looking here (search the page for “pageX”).

UPDATE 3: I cannot run a demo on this wordpress site, so here is a link to a zip file demo.  Unzip it and open index.html in your browser. This is on my new site … same blog, but i’m yet to redirect everything there…

/*
 * My object oriented version of click and drag
 *
 */

function Canvas( data ) {
  data = data || {};
  var self = this;

  this.canvasID = data.canvasID || 'canvas';
  this.viewableCanvas = document.getElementById(this.canvasID);
  this.vctx = data.canvasContext || this.viewableCanvas.getContext('2d');
  // set our events. Up and down are for dragging,
  // double click is for making new boxes
  this.viewableCanvas.onmousedown = function(e){ Canvas.prototype.mouseDownAction.call( self, e ) };
  this.viewableCanvas.onmouseup = function(e){ Canvas.prototype.mouseUpAction.call( self, e ) };
  this.viewableCanvas.onmouseout = function(e){ Canvas.prototype.mouseUpAction.call( self, e ) };
  this.viewableCanvas.ondblclick = function(e){ Canvas.prototype.mouseDblClickAction.call( self, e ) };

  this.isValid = Canvas.IS_INVALID;

  this.canvasContentObjectsList = [];

  // we use a content canvas to draw individual shapes.  This is larger than the viewable canvas.  
  // only a section of this is passed to the viewable canvas
  var contentCanvasHeight = data.contentCanvasHeight || this.viewableCanvas.height * 2;
  if (contentCanvasHeight < this.viewableCanvas.height) { contentCanvasHeight = this.viewableCanvas.height }
  var contentCanvasWidth = data.contentCanvasWidth || this.viewableCanvas.width * 2;
  if (contentCanvasWidth < this.viewableCanvas.width) { contentCanvasWidth = this.viewableCanvas.width }
  this.contentCanvas = document.createElement('canvas');
  this.contentCanvas.height = contentCanvasHeight;
  this.contentCanvas.width = contentCanvasWidth;
  this.cctx = this.contentCanvas.getContext('2d'); // content context
  // These X and Y values are the top left corner of the "viewable window" of this content canvas
  this.ccViewX = Math.max( (contentCanvasWidth/2) - (this.viewableCanvas.width/2), 0 );
  this.ccViewY = Math.max( (contentCanvasHeight/2) - (this.viewableCanvas.height/2), 0 );

  // Max values for the ccView X and Y vals
  this.ccViewXMax = this.cctx.canvas.width - this.vctx.canvas.width;
  this.ccViewYMax = this.cctx.canvas.height - this.vctx.canvas.height;

  this.isContentObjectDragAction = false;
  this.isContentCanvasDragAction = false;

  // the X and Y coordinate for when the mousedown event is triggered
  this.contentCanvasDragStartX = 0;
  this.contentCanvasDragStartY = 0;

    //fixes a problem where double clicking causes text to get selected on the canvas
  this.viewableCanvas.onselectstart = function () { return false; }

  // fixes mouse co-ordinate problems when there's a border or padding
  // see getMouse for more detail
  this.stylePaddingLeft = 0;
  this.stylePaddingTop = 0;
  this.styleBorderLeft = 0;
  this.styleBorderTop = 0;
  if (document.defaultView && document.defaultView.getComputedStyle) {
    this.stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(this.viewableCanvas, null)['paddingLeft'], 10)      || 0;
    this.stylePaddingTop  = parseInt(document.defaultView.getComputedStyle(this.viewableCanvas, null)['paddingTop'], 10)       || 0;
    this.styleBorderLeft  = parseInt(document.defaultView.getComputedStyle(this.viewableCanvas, null)['borderLeftWidth'], 10)  || 0;
    this.styleBorderTop   = parseInt(document.defaultView.getComputedStyle(this.viewableCanvas, null)['borderTopWidth'], 10)   || 0;
  }

// The selection color and width. Right now we have a red selection with a small width
  this.selectedColor = data.selectedColor || '#CC0000';
  this.selectedWidth = data.selectedwidth || 2;

  // since we can drag from anywhere in a node
  // instead of just its x/y corner, we need to save
  // the offset of the mouse when we start dragging.
  this.offsetx = this.ccViewX;
  this.offsety = this.ccViewY;

  this.currentlySelectedContentObject = null;

    // make draw() fire every INTERVAL milliseconds
  setInterval(function() { Canvas.prototype.draw.call( self ) }, 1000/(data.interval?data.interval:40) );
}
// static members
Canvas.IS_VALID = true;
Canvas.IS_INVALID = false;

// create a random number between two ints, inclusive
Canvas.randomFromTo = function( from, to ) {
  return Math.floor(Math.random() * (to - from + 1) + from);
}

//wipes the canvas context
Canvas.prototype.clear = function( ctx ) {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

// While draw is called as often as the INTERVAL variable demands,
// It only ever does something if the canvas gets invalidated by our code
Canvas.prototype.draw = function( ) {
  if ( !this.isValid && this.cctx ) {
    //Canvas.prototype.clear.call( this, ctx );
    this.clear( this.cctx );

    // Add stuff you want drawn in the background all the time here
    //Draw a grid to assist in seeing the background scroll
    this.drawGrid();

    // draw all boxes
    var l = this.canvasContentObjectsList.length;
    for (var i = 0; i < l; i++) {
      this.canvasContentObjectsList[i].drawshape({
        ctx: this.cctx
      });
    }

    // draw selection
    // right now this is just a stroke along the edge of the selected box
    var selectedObj = this.currentlySelectedContentObject;
    if (selectedObj != null) {
      selectedObj.highlightBorder({
        ctx: this.cctx,
        selectedColor: this.selectedColor,
        selectedWidth: this.selectedWidth
      });
    }

    // copy section of content canvas out to the viewable canvas
    try {
      this.clear( this.vctx );
      this.vctx.drawImage(
        this.cctx.canvas,
        this.ccViewX,
        this.ccViewY,
        this.viewableCanvas.width,
        this.viewableCanvas.height,
        0,
        0,
        this.viewableCanvas.width,
        this.viewableCanvas.height
      )
    } catch(e) {
      // Do nothing.  a draw error may occur because we are updating this canvas
      // before the cctx.canvas is done drawing.
    }

    // Add stuff you want drawn on top all the time here

    this.isValid = Canvas.IS_VALID;
  }
}

// draw grid lines, but only on the part visible
Canvas.prototype.drawGrid = function( data ) {

  // Draw gridlines to help with scrolling
  for (var x = (this.ccViewX + 0.5); x < (this.ccViewX + this.vctx.canvas.width); x += 40) {
    this.cctx.moveTo(x, 0);
    this.cctx.lineTo(x, this.ccViewY + this.vctx.canvas.height);
  }
  for (var y = (this.ccViewY + 0.5); y < (this.ccViewY + this.vctx.canvas.height); y += 40) {
    this.cctx.moveTo(0, y);
    this.cctx.lineTo(this.ccViewX + this.vctx.canvas.width, y);
  }
  this.cctx.strokeStyle = "#eee";
  this.cctx.stroke();
}

// Sets mx,my to the mouse position relative to the canvas
// unfortunately this can be tricky, we have to worry about padding and borders
Canvas.prototype.getMouseCoordinates = function(e) {
      var element = this.viewableCanvas, offsetX = 0, offsetY = 0;

      if (element.offsetParent) {
        do {
          offsetX += element.offsetLeft;
          offsetY += element.offsetTop;
        } while ((element = element.offsetParent));
      }

      // Add padding and border style widths to offset
      offsetX += this.stylePaddingLeft;
      offsetY += this.stylePaddingTop;

      offsetX += this.styleBorderLeft;
      offsetY += this.styleBorderTop;

      var mx = e.pageX - offsetX + this.ccViewX;
      var my = e.pageY - offsetY + this.ccViewY;

      // These are the mouse coordinates on the VIEWABLE CANVAS
      return {
        mouseX: mx,
        mouseY: my
      };
}

// Happens when the mouse is clicked in the canvas
Canvas.prototype.mouseDownAction = function(e){

  var self = this;
  var mouseMoveFunction = function(e){ Canvas.prototype.mouseMoveAction.call( self, e ) };

  var mouseCoords = this.getMouseCoordinates(e);
  //Canvas.prototype.clear.call( this, ctx );
  this.clear( this.cctx );
  var l = this.canvasContentObjectsList.length;
  for (var i = l-1; i >= 0; i--) {
    // draw shape onto ghost context
      this.canvasContentObjectsList[i].drawshape({
        ctx: this.cctx,
        fill: 'black'
      });

    // get image data at the mouse x,y pixel
    var imageData = this.cctx.getImageData(mouseCoords.mouseX, mouseCoords.mouseY, 1, 1);
    //var index = (mouseCoords.mouseX + mouseCoords.mouseY * imageData.width) * 4;

    // if the mouse pixel exists, select and break
    if (imageData.data[3] > 0) {
      this.currentlySelectedContentObject = this.canvasContentObjectsList[i];
      this.offsetx = mouseCoords.mouseX - this.currentlySelectedContentObject.x;
      this.offsety = mouseCoords.mouseY - this.currentlySelectedContentObject.y;
      this.currentlySelectedContentObject.x = mouseCoords.mouseX - this.offsetx;
      this.currentlySelectedContentObject.y = mouseCoords.mouseY - this.offsety;
      this.isContentObjectDragAction = true;
      this.viewableCanvas.onmousemove = mouseMoveFunction;
      this.isValid = Canvas.IS_INVALID;
      //Canvas.prototype.clear.call( this, ctx );
      this.clear( this.cctx );
      return;
    }
  }
  // Register a drag action for the whole canvas
  if ( !this.isContentCanvasDragAction ) {
    this.contentCanvasDragStartX = mouseCoords.mouseX;
    this.contentCanvasDragStartY = mouseCoords.mouseY;
    this.originalCCViewX = this.ccViewX;
    this.originalCCViewY = this.ccViewY;
  }
  this.isContentCanvasDragAction = true;
  this.viewableCanvas.onmousemove = mouseMoveFunction;
  // havent returned means we have selected nothing
  this.currentlySelectedContentObject = null;
  // clear the ghost canvas for next time
  //Canvas.prototype.clear.call( this, ctx );
  this.clear( this.cctx );
  // invalidate because we might need the selection border to disappear
  this.isValid = Canvas.IS_INVALID;
}

// Happens when the mouse is moving inside the canvas
Canvas.prototype.mouseMoveAction = function(e){
  var mouseCoords = null;

  if ( this.isContentObjectDragAction ){
    mouseCoords = this.getMouseCoordinates(e);

    this.currentlySelectedContentObject.x = mouseCoords.mouseX - this.offsetx;
    this.currentlySelectedContentObject.y = mouseCoords.mouseY - this.offsety;   

    // something is changing position so we better invalidate the canvas!
    this.isValid = Canvas.IS_INVALID;
  }

  if ( this.isContentCanvasDragAction ) {
    mouseCoords = this.getMouseCoordinates(e);

    xChange = (mouseCoords.mouseX - this.contentCanvasDragStartX);
    yChange = (mouseCoords.mouseY - this.contentCanvasDragStartY);

    // Must move 30 pixels before scrolling.
    if (Math.abs(xChange) > 30 || Math.abs(yChange) > 30) {
      var newX = this.originalCCViewX - xChange;
      newX = newX < 0 ? 0 : newX;
      newX = newX > this.ccViewXMax ? this.ccViewXMax : newX;
      this.ccViewX = newX;

      var newY = this.originalCCViewY - yChange;
      newY = newY < 0 ? 0 : newY;
      newY = newY > this.ccViewYMax ? this.ccViewYMax : newY;
      this.ccViewY = newY;

      this.isValid = Canvas.IS_INVALID;
    }
  }
}

Canvas.prototype.mouseUpAction = function(){
  this.isContentObjectDragAction = false;
  this.isContentCanvasDragAction = false;
  this.viewableCanvas.onmousemove = null;
}

Canvas.prototype.addContentObject = function( obj ) {
  // Verify that this is the correct object type so we have X and Y coordinates

  this.canvasContentObjectsList.push( obj );
  this.isValid = Canvas.IS_INVALID;
}

// adds a new node
Canvas.prototype.mouseDblClickAction = function(e) {
  var mouseCoords = this.getMouseCoordinates(e);
  var randomColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

  switch( Canvas.randomFromTo( 1, 3 ) ) {
    case 1:
      this.addContentObject( new Circle({
          x: mouseCoords.mouseX,
          y: mouseCoords.mouseY,
          r: Canvas.randomFromTo( 20, 50 ),
          fill: randomColor
        })
      );
      break;
    case 2:
      this.addContentObject( new Rectangle({
          x: mouseCoords.mouseX,
          y: mouseCoords.mouseY,
          w: Canvas.randomFromTo( 20, 100 ),
          h: Canvas.randomFromTo( 20, 100 ),
          fill: randomColor
        })
      );
      break;
    case 3:
    default:
      this.addContentObject( new Triangle({
          x: mouseCoords.mouseX,
          y: mouseCoords.mouseY,
          w: Canvas.randomFromTo( 20, 100 ),
          h: Canvas.randomFromTo( 20, 100 ),
          fill: randomColor
        })
      );
      break;
  }
}

/***********************************************************
 * Shape super class
 *
 ***********************************************************/

function Shape( data ) {
  data = data || {};

  this.shape = data.shape || 'Shape';
  this.shapeID = data.id || 'Shape';

  this.fill = data.fill || '#444444';

  this.x = data.x;
  this.y = data.y;
}

// Draws a single shape to a single context
// draw() will call this with the normal canvas
// myDown will call this with the ghost canvas
Shape.prototype.drawshape = function( data ) {
    if (!data) return;

  // fill can be overridded if passed in
  data.ctx.fillStyle = data.fill || this.fill;

  // subclass specific
}

Shape.prototype.highlightBorder = function( data ) {
  // Handle the basic, standard highlight things here.
  if (!data) return;

  data.ctx.strokeStyle = data.selectedColor;
  data.ctx.lineWidth = data.selectedWidth;
}

/***********************************************************
 * Rectangle super class
 *
 ***********************************************************/

// Create subclass and reassign constructor to self.
Rectangle.prototype = new Shape();
Rectangle.prototype.constructor = Rectangle;
function Rectangle( data ) {
  data = data || {};

  Shape.call( this, data );

  this.w = data.w;
  this.h = data.h;
}

// Draws a single shape to a single context
// draw() will call this with the normal canvas
// myDown will call this with the ghost canvas
Rectangle.prototype.drawshape = function( data ) {
  Shape.prototype.drawshape.call(this, data); 

  // We can skip the drawing of elements that have moved off the screen:
  if (this.x > data.ctx.canvas.width || this.y > data.ctx.canvas.height) return;
  if (this.x + this.w < 0 || this.y + this.h < 0) return;

  data.ctx.fillRect(this.x,this.y,this.w,this.h);
}

Rectangle.prototype.highlightBorder = function( data ) {
  Shape.prototype.highlightBorder.call(this, data);
  data.ctx.strokeRect(this.x,this.y,this.w,this.h);
}

/***********************************************************
 * Circle super class
 *
 ***********************************************************/

// Create subclass and reassign constructor to self.
Circle.prototype = new Shape();
Circle.prototype.constructor = Circle;
function Circle( data ) {
  data = data || {};

  Shape.call( this, data );

  this.r = data.r; //radius
}

// Draws a single shape to a single context
// draw() will call this with the normal canvas
// myDown will call this with the ghost canvas
Circle.prototype.drawshape = function( data ) {
  Shape.prototype.drawshape.call(this, data); 

  // We can skip the drawing of elements that have moved off the screen:
  if (this.x > data.ctx.canvas.width || this.y > data.ctx.canvas.height) return;
  if (this.x + this.r < 0 || this.y + this.r < 0) return;

  this.drawCircle( data );
}

Circle.prototype.highlightBorder = function( data ) {
  Shape.prototype.highlightBorder.call(this, data); 

  data['borderOnly'] = true;
  this.drawCircle( data );
}

Circle.prototype.drawCircle = function( data ) {
    // Draw a circle using the arc function.
  data.ctx.beginPath();

  // Arguments: x, y, radius, start angle, end angle, anticlockwise
  data.ctx.arc(this.x, this.y, this.r, 0, 360, false);
  if ( !data['borderOnly'] ) {
    data.ctx.fill();
  } else {
    data.ctx.stroke();
  }

  data.ctx.closePath();
}

/***********************************************************
 * Triangle super class
 *
 ***********************************************************/

// Create subclass and reassign constructor to self.
Triangle.prototype = new Shape();
Triangle.prototype.constructor = Triangle;
function Triangle( data ) {
  data = data || {};

  Shape.call( this, data );

  this.w = data.w;
  this.h = data.h;
}

// Draws a single shape to a single context
// draw() will call this with the normal canvas
// myDown will call this with the ghost canvas
Triangle.prototype.drawshape = function( data ) {
  Shape.prototype.drawshape.call(this, data); 

  // We can skip the drawing of elements that have moved off the screen:
  if (this.x > data.ctx.canvas.width || this.y > data.ctx.canvas.height) return;
  if (this.x + this.w < 0 || this.y + this.h < 0) return;

  this.drawTriangle( data );
}

Triangle.prototype.highlightBorder = function( data ) {
  Shape.prototype.highlightBorder.call(this, data);
  data['borderOnly'] = true;
  this.drawTriangle( data );
}

Triangle.prototype.drawTriangle = function( data ) {
  data.ctx.beginPath();
  // Start from the top-left point.
  data.ctx.moveTo( this.x, this.y - (this.h / 2) ); // give the (x,y) coordinates
  data.ctx.lineTo( this.x + (this.w / 2), this.y + (this.h / 2) );
  data.ctx.lineTo( this.x - (this.w / 2), this.y + (this.h / 2) );
  data.ctx.lineTo( this.x, this.y - (this.h / 2) );

  // Done! Now fill the shape, and draw the stroke.
  // Note: your shape will not be visible until you call any of the two methods.
  if ( !data['borderOnly'] ) {
    data.ctx.fill();
  } else {
    data.ctx.stroke();
  }
  data.ctx.closePath();
}

// start it up!
window.onload = function(){
  var OO_canvas = new Canvas( { canvasID: 'canvas_clickAndDragOO' });

  var r1 = new Rectangle({
    x: 800,
    y: 700,
    w: 40,
    h: 70,
    fill: '#FFC02B'
  });
  OO_canvas.addContentObject( r1 );

  var r2 = new Rectangle({
    x: 780,
    y: 780,
    w: 70,
    h: 40,
    fill: '#2BB8FF'
  });
  OO_canvas.addContentObject( r2 );

  var t1 = new Triangle({
    x: 700,
    y: 600,
    w: 70,
    h: 40,
    fill: '#900'
  });
  OO_canvas.addContentObject( t1 );

  var t2 = new Triangle({
    x: 900,
    y: 600,
    w: 70,
    h: 40,
    fill: '#009'
  });
  OO_canvas.addContentObject( t2 );

  var c1 = new Circle({
    x: 675,
    y: 730,
    r: 30,
    fill: '#459'
  });
  OO_canvas.addContentObject( c1 );

  var c2 = new Circle({
    x: 950,
    y: 730,
    r: 30,
    fill: '#954'
  });
  OO_canvas.addContentObject( c2 );
};

Apache POI – Formatting of ‘General’ data extracted from Excel

I just fixed an issue that has to do with pulling data out of excel using the Apache POI framework into Java and having the data’s format change along the way. It is not a particularly difficult issue, but when researching it I found that there were a couple of other posts on it that didn’t really solve it, or solved it in a round-about way. So my solution is here:

The issue I ran into was that there were cells in Excel that were meant to be strings but had the default Excel cell format of “General.” If a normal string was in one of the cells in this column, then it would be correctly read into the Java code as a string. However, if a value was like ‘123123123,’ it would be read in as an HSSFCell.CELL_TYPE_NUMERIC and would convert to a string in scientific notation. These needed to be read in exactly as there were seen in the spreadsheet.

Other solutions I saw included additional reformatting once the data was inside Java, but that seemed too dirty to me. I would have to make assumptions on what the user put into the spreadsheet. There should be a way to pull the data from the Excel file and receive a string that looks exactly like what is shown in Excel.

A quick solution to this would be to change the formatting of the cell in Excel to ‘Text’ so that the fields were always designated correctly. But, in my case, I cannot always control what is in the Excel file. A user might change the formatting to whatever they want, but my system expects a String. So this was not a solution.

What I can control is the java code, of course. So after some digging I found two keys that would help me solve this issue.  If I am trying to convert a HSSFCell.CELL_TYPE_NUMERIC value to a string, I need to use these two things:

  1. I can get the format of the cell that is being used by Excel with cell.getCellStyle( ).getDataFormat( ). This returns a short.  The Excel format for “General” is 0 and the format for Scientific Notation is 11 (I found this through debugging, but a table exists at least here in the ‘Value’ column).  So I know if the user really wanted scientific notation, or if the value was just formatted like that when passed to me.
  2. Once I know the user did not mean for the value to be in scientific notation, I can check the string for the existence of an “E,” and if it exists I will pull the string from Excel using Excel’s formatting instead of my own.  I do this with value = new HSSFDataFormatter().formatCellValue( cell ).  This converts the cell to a string using the Excel cell format pattern instead of trying to reformat the numeric value in the HSSFCell in Java.
I could simply use this formatCellValue all of the time instead of even checking I suppose, but i’m doing some other custom formatting as well so this is treated as a special case.
So this is the solution I ended up using.  The key is to check the format that is set up in Excel, and then use it directly if it produces a cleaner result in the Java code.  Hope that helps someone.

I’m not maintaining this blog here so commenting is closed… Please see this same post on my new site to ask questions: http://mpickell.com/blog/2011/06/03/apache-poi-formatting-of-data-extracted-from-excel/


jQuery plugin: working scrollbar on left side of div

I’ve been building JSF views and creating custom components for a while and one issue we worked on was making scrollable tables, where the header and footer stay stationary and the data scrolls.

I’m still cleaning this up, but the general idea is that I wrapped the table in DIVs, which are set up to scroll vertically or horizontally based on the dynamic content of the table. This seems to be the only solution that is cross-browser, and it uses jQuery to dissect the table and move the header and footer so that the scrolling works correctly. Once I finalize that, i’ll post it.

But one thing was missing: the content of the tables sometimes pushes the table off the right side of the view, and the horizontal scrollbar appears. At this point, the vertical scrollbar is way off to the right and pretty much makes the table useless. So I wanted to move the vertical scrollbar to the left side, and I had trouble finding a cross-browser solution … until now.

I just found a jQuery plugin written by Brian Reavis at his website: 3rd Route. I tested it out and it worked immediately. The only thing i had to do to it was swap out all of the ‘$’ for ‘jQuery’ because of my use of the jQuery.noConflict() flag. I originally found it via stackoverflow, but the version on the website looks like it was cleaned up to enable chaining.

I tried other things, like multiple versions of style="direction:trl", but these felt messy when i read about them, and did not work when I implemented them.

Thanks Brian!

Update: I ended up doing a lot of changes because of some issues i found:

  • For very large tables, this code was really slow in IE.  I narrowed it down to the jQuery ‘append’ function and refactored the plugin to not use it at all
  • The original copied all components into the poser div.  I removed all of that and the poser div is basically now just the scrollbar.  Something major was required for using the plugin with JSF, because it was causing duplicate ID issues.  I decided to get rid of all of the extra components instead of just renaming the IDs.
  • I created a second version that has the scrollbar on both sides
  • I added a unique identifier class so that multiple instances could be on the same page.
  • I changed how the scroll updating worked, but the old way wasn’t broken so it wasn’t really an improvement.

So, based on Brian’s original design and implementation, here is what I am using now:

/**
 * jQuery plugin to add a scrollbar to the left side of a div.  It does this by
 * creating a false div on the left side of the table, and then having that div's scroll
 * position set on the original div every scroll event.
 * 
 * @link edited from http://thirdroute.com/css-js-left-vertical-scrollbars/, but heavily changed from the original version.
 */
jQuery.fn.leftAndRightScrollBar = function(){
	var items = jQuery(this);
	
	var randomString = function() {
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
		var string_length = 8;
		var randomstring = '';
		for (var i=0; i<string_length; i++) {
			var rnum = Math.floor(Math.random() * chars.length);
			randomstring += chars.substring(rnum,rnum+1);
		}
		return randomstring;
	}

	jQuery(function(){
		items.each(function(){
			// create unique classes for targeting the poser div
			var poserTargetingClass = randomString();
			
			var e = jQuery(this);
			var contentHeight = e.children('table:first').height();
			var content = e.html();
			var ie = !jQuery.support.boxModel;
			var w = e[ie?'innerWidth':'width'](), h = e[ie?'innerHeight':'height']();
			
			//calculate paddings
			var pad = {};
			jQuery(['top', 'right', 'bottom', 'left']).each(function(i, side){
				pad[side] = parseInt(e.css('padding-' + side).replace('px',''));
			});
			//detect scrollbar width
			var xfill = jQuery('<div class="xFill">').css({margin:0, padding:0, height:'1px'});
			e.append(xfill);
			var contentWidth = xfill.width();
			var scrollerWidth = e.innerWidth() - contentWidth - pad.left - pad.right;
			e.css('padding', '0');
			e.children('.xFill').remove();
			
			var poserHeight = h - pad.top - pad.bottom;
			var poser = jQuery('<div class="leftAndRightScrollPoser '+poserTargetingClass+'">')
				// create a div that forces height without copying the content to do it.
				.html('<div style="visibility:hidden;height:'+contentHeight+'px">.</div>')
				.css('overflow','auto')
				.height(poserHeight+(ie?pad.top+pad.bottom:0))
				.width(scrollerWidth-(ie?0:pad.left*2)) // only as wide as the scrollbar.
			;
			
			e
				.css({
					width: w+(ie?0:scrollerWidth)-(ie?0:pad.right+pad.left),
					height: h-(ie?0:pad.bottom+pad.top),
					marginTop: -poserHeight-pad.top*2,
					marginLeft: scrollerWidth
				})
				.css('overflow-y', 'auto')
				.css('overflow-x', 'hidden')
			;
				
			jQuery(['top', 'right', 'bottom', 'left']).each(function(i, side){
				 poser.css('padding-'+side, pad[side]);
				 e.css('padding-'+side, pad[side]);
			});
			poser.insertBefore(e);
			
			var hRatio = (e.innerHeight()+pad.bottom) / poser.innerHeight();
			// Set up scrolling update events
			jQuery("." + poserTargetingClass).scroll(function(){e.scrollTop(poser.scrollTop()*hRatio)});
			e.scroll(function(){poser.scrollTop(e.scrollTop()*hRatio)});
		});
	});
	return items;
};


/**
 * jQuery plugin to move the scrollbar to the left side of a div -- no right scrollbar
 * @link http://thirdroute.com/css-js-left-vertical-scrollbars/, but heavily changed from the original version.
 */
jQuery.fn.leftScrollbar = function(){
	var items = jQuery(this);
	
	var randomString = function() {
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
		var string_length = 8;
		var randomstring = '';
		for (var i=0; i<string_length; i++) {
			var rnum = Math.floor(Math.random() * chars.length);
			randomstring += chars.substring(rnum,rnum+1);
		}
		return randomstring;
	}
	
	jQuery(function(){
		items.each(function(){
			// create unique classes for targeting the poser div
			var poserTargetingClass = randomString();
			
			var e = jQuery(this);
			var content = e.html();
			var contentHeight = e.children('table:first').height();
			var ie = !jQuery.support.boxModel;
			var w = e[ie?'innerWidth':'width'](), h = e[ie?'innerHeight':'height']();
			//calculate paddings
			var pad = {};
			jQuery(['top', 'right', 'bottom', 'left']).each(function(i, side){
				pad[side] = parseInt(e.css('padding-' + side).replace('px',''));
			});
			//detect scrollbar width
			var xfill = jQuery('<div>').css({margin:0, padding:0, height:'1px'});
			e.append(xfill);
			var contentWidth = xfill.width();
			var scrollerWidth = e.innerWidth() - contentWidth - pad.left - pad.right;
			e.css('padding', '0');
			e.children('.xFill').remove();
			
			var poserHeight = h - pad.top - pad.bottom;
			var poser = jQuery('<div class="leftScrollPoser '+poserTargetingClass+'">')
				.html('<div style="visibility:hidden;height:'+contentHeight+'px">.</div>')
				.css('overflow','auto')
				.height(poserHeight+(ie?pad.top+pad.bottom:0))
				.width(scrollerWidth-(ie?0:pad.left*2)) // only as wide as the scrollbar
			;
			
			e
				.css({
					width: w/*-scrollerWidth*/-(ie?0:pad.right+pad.left),
					height: h-(ie?0:pad.bottom+pad.top),
					overflow: 'hidden',
					marginTop: -poserHeight-pad.top*2,
					marginLeft: scrollerWidth
				});
				
			jQuery(['top', 'right', 'bottom', 'left']).each(function(i, side){
				 poser.css('padding-'+side, pad[side]);
				 e.css('padding-'+side, pad[side]);
			});
			poser.insertBefore(e);
			
			var hRatio = (e.innerHeight()+pad.bottom) / poser.innerHeight();
			// Set up scrolling update events
			jQuery("." + poserTargetingClass).scroll(function(){e.scrollTop(poser.scrollTop()*hRatio)});
			e.scroll(function(){poser.scrollTop(e.scrollTop()*hRatio)}); // so mouse wheel scrolls table
		});
	});
	return items;
};


Browser cache refreshing for CSS and Javascript

After reading an article on it, and having an issue at work concerning it, I put together a script that should keep CSS and JS files refreshed at a configured interval.  I’d like to get comments on it, or just make it available if needed:

Here’s the script, I stored it in a separate JS file and called it into my webpage ( a jsp page) with a script element:

/**
* killCache.js
*
* Small js script that allows for appending a "code" to URLs of CSS or JS files (or
* anything that uses a LINK element) in order to force the browser to update from the
* files and not from cache.
* /

/**
* Round a value to a given interval.
*
* For example:
* (1) if the value is 4 and the interval is 10, then the result will be 0.
* (2) if the value is 755.3 and the interval is 100, the result will be 800.
*
* @param value the current value to check and round
* @param interval the interval to round the value to
* @return the rounded value
*/
function roundTo(value, interval) {
// round the value to the nearest interval
value /= interval;
value = Math.round(value);
return value * interval;
}

/**
* Create a string 'code' that changes every INTERVAL.  this code can be appended to CSS or JS files
* that change in order to make sure the user is always getting the correct version and not a cached version.
*
* @return a string code that changes every INTERVAL so that some files are not cached.
*/
function getRefreshCode() {
var currentTime = new Date();
var intervalToUse = 30; // round minutes to nearest 30 minute interval
var updateInterval = roundTo(currentTime.getMinutes(), intervalToUse);

return updateInterval + "_" + currentTime.getHours() + "_" + currentTime.getDay();
}

/**
* Create a link element in the header where the href also contains a dynamic
* string that forces a periodic update of cache
*/
function addUpdatingLinkToHead(rel, type, href, title) {
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');

if (rel != null) { link.rel = rel; }
link.type = type;
link.href = href + "?" + getRefreshCode(); // refresh code is added here.
if (title != null) { link.title = title; }

head.appendChild(link);
}

/**
* Create a script element in the header where the href also contains a dynamic
* string that forces a periodic update of cache
*/
function addUpdatingScriptToHead(type, src) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');

script.type = type;
script.src = src + "?" + getRefreshCode(); // refresh code is added here.

head.appendChild(script);
}

and then I the script itself, and my CSS file to the web page like this:

<!-- Small js file that creates CSS links & js scripts and forces them to update occasionally -->
<script src="/js/killCache.js" type="text/javascript"></script>
<script type="text/javascript">
  addUpdatingLinkToHead("stylesheet", "text/css", "/theme/cssFile1.css", "Style");
  addUpdatingLinkToHead("stylesheet", "text/css", "/theme/cssFile2.css", "Style");
</script>