The Games of the Future?

In order to jump start posting more often I’m going to deviate slightly from my technical articles and ramble a bit to get back into the blogging mood. Please bare with me, the next article I write should be back on track.

A sore yet fond subject of my past is video games. Like so many people my age, my past is filled with countless hours of playing video games. Honestly, I remember the happiness and sense of accomplishment I felt from playing games and I have actually built lasting friendships with people I knew only though online personas. However, I stopped “playing games” sometime around 2005, and I’ve since frowned on the subject.

I look back on my gaming history with some resentment because at some point I concluded that I was wasting time. Time that I could spend learning, earning, growing, and doing something of importance. Whatever triggered this I don’t really know. While being “game free” I’ve noticed some things that have disturbed me.

There is a LOT of game playing going on. Not all gameplay is bothers me. Everyone needs some entertainment and games happen naturally in social activities. I mean excessive gameplay. I can’t even completely describe exactly what qualifies as matching this description.

I decided to look at myself to see if my time spent without games has had a positive affect on me. I’m a little biased but I think that things have turned out well for me. Sparing you the details I feel I have a successful challenging job where I feel I can make some kind of impact on the world. Cheesy I know.

But, looking deeper I noticed that my time “without games” was in fact not game-less. Where before I spent time playing games with seemingly no positive impact on my future, I was applying some of the same concepts (experience, points, etc) improving myself. I know you didn’t come here to listen to me talk about myself, so how can I turn this into something constructive? While I was thinking about this I recently came across two presentations that describing a potential future of video games.

Briefly, the idea that appealed to me was that games could be used to improve lives positively. There is an obviously subjective angle to what is considered life improving, but in general there are plenty of things that can be agreed on. Improvements to your health (exercise), being part of a bigger picture (saving energy and gas), and the ability to motivate yourself and do a good job. These are not your traditional video games, but it is taking the addictive desirable qualities of video games and applying those to real life aspects, and that is what appeals to me.

An example that stood out to me was some recent hybrid cars. These new cars give the driver live, accurate feedback about how efficiently they are driving their car. This extra information gives the driver an incentive to improve their driving. Be it to improve milage, save gas, prolong the life of their vehicle, or whatever. The ambition to be the best or be very good, crucial to many areas and notable in video games, is being used for good.

I am seeing this more and more and I’m liking what I see. I really hope that more and more people recognize these concepts and use them for the right reasons. I really hope that the idea of positive activities being games takes off.

The two videos I saw were Jesse Schell “When games invade real live” and Jane Mcgonigal “Gaming can make a better world”. In fact, this page lists 5 videos including both of these meaning the others are likely pretty good too.

Removing Haskell’s Hassle

This goes along with my recent post about my go! script for go. I wrote a similar script for Haskell to overcome a problem I continually had with Haskell’s interpreter.

The problem is that in order to create useful functions to test in the interpreter (ghc) you need to load your file into the interpreter. However, by the time I’ve opened up the interpreter I forgot to open up an editor (via the shell). Still, if I had a document open than linking the two takes a bit of work (mostly drag and drop). I’ve managed to spearhead the issue when I first start the interpreter.

My little script allows me to quick edit a file, or even start a new file, and automatically link up with the interpreter. Its another one of the scripts you can find in my ~/bin:

#!/usr/bin/env ruby
# Author: Joseph Pecoraro
# Date: Wednesday, September 30, 2009
# Description: Simple Haskell Quick Starter

# Defaults
EDITOR = 'mate' # ENV['EDITOR'] for most Unix Guys
HASK_DIR = File.expand_path('~/haskell')

# Determine the File
#  - default to temp.hs
#  - use provided file if exists
#  - create new temp file with given name
file = File.join(HASK_DIR, 'temp.hs');
if ARGV.size > 0
  name = ARGV[0]
  if File.file? name
    file = name
    name += '.hs' unless name =~ /\.hs$/
    file = name

# Work the magic
system "touch #{file}"
system "#{EDITOR} #{file}"
system "ghci #{file}"

Its a nearly perfect replacement of ghci for me. It allows me to focus more on the task at hand rather then getting bogged down and frustrated when I realize I have to stop what I’m doing to link the interpreter to an editor.

For your own use you may want to customize the EDITOR and HASK_DIR variables. As I tend to use TextMate and a folder in my home directory for throw away files (which I can easily clean up eventually). Let me know if you’ve suffered with the same problem, or others when working with Haskell!

Get Go’in a Little Quicker

Even with Finals literally around the corner I couldn’t help but play around a little with “Google’s New Programming Language” go. In case you haven’t heard about go, you can find out everything you need to know at their simple site

I’m not going to talk about what I like/dislike about the language… yet. Instead I’m going to do what everyone else has probably already done. I wrote a simple compiler/link/run shell script which takes its place in my ~/bin:

# Author: Joseph Pecoraro
# Date: Saturday, November 14, 2009
# Description: Compile, Link, and Run a go script.

# Requires a file
if [ ! "$1" ]; then
  echo "usage: go! <filename>"; exit 1

# Use the proper tools for the arch
if [ $GOARCH = "amd64" ]; then
elif [ $GOARCH = "386" ]; then
elif [ $GOARCH = "arm" ]; then
  echo "unsupported GOARCH: $GOARCH"; exit 2

# Strip .go (if its there)
file=`echo $1 | sed -e 's/.go$//'`

# Compile, Link, and Run (break on any error)
$COMPILER "$file.go" && $LINKER -o $file "$file$EXTENSION" && ./$file

Why did I write my own? The others I had seen were inadequate, didn’t work well with tabbing (filename versus executable name), or didn’t even produce a nice executable name at all. For many, you probably won’t need to compile, link, and run a program all at once (especially in a systems language). However, I’ve found that its a great tool to help me learn the language. This is due in some part to go’s quick compilation and linking.

It is really amazing to me that all of the languages that I have gotten comfortable working with have a command line shell. JavaScript, Haskell, and Ruby all have shells where I can make a fool of myself while quickly testing syntax or libraries. Go doesn’t. Its something I really miss. This little script is a simple replacement that brings me a little closer to interactivity.

I tried to make it generic so it could work on any architecture that go currently builds on. I named the script “go!”. Let me know what scripts you’ve built to work with go.

Improving the Web Inspector

There is a better article on the WebKit blog, showing even more features! I really recommend that you check it out and provide feedback!

I haven’t been blogging recently… Instead, for the past 3 months I’ve been “doing” something! I’ve been working on WebKit, the Open Source Rendering Engine behind browsers like Safari and Chrome. More specifically I’ve been working on the Web Inspector. Its been a blast!

In a matter of weeks of working on the Inspector I was able to knock out some simple features that I’ve always wanted. Soon after I introduced some features that required some serious learning and development. I really shouldn’t say “I”, because in actuality the WebKit team has been a tremendous help in teaching me and collaborating with me on the new features. To name a few that have been especially helpful (via their IRC handle because I didn’t ask their permission) xenon, Rik`, pfeldman, bweinstein, bdash, and pmuellr.

So what were the features? Here they are, roughly in the order in which they were added:

Element Attributes (Create + Tab)

Making new element attributes was difficult, sometimes impossible, and undiscoverable. My goal was to get rid of all three of these obstacles. Here goes. Discoverability first. With the new changes, when you hover over an element in the Element’s Tree Outline an ellipsis, or some indicator, appears in the element’s opening tag in the position that the next attribute would go. Double clicking that ellipsis starts editing as though it were a normal attribute. To make things easier, you can tab through attributes and backwards using “shift-tab”. When starting to edit an attribute, when you tab over the end it will start making a new attribute. This way you can quickly make multiple attributes.


CSS Properties (Create + Tab)

The same problem existed for CSS Properties. I added tabbing through CSS properties inside a selector section. Tabbing forward from the last property (or double clicking the empty space if there are no properties) will start creating a new property.

CSS Selectors (Create + Modify)

Yes, you now have the ability to actually add and modify selectors! This is a feature that many designers have been interested in. It is really powerful and quite useful. This will make it easy for designers to hack around inside the Inspector to get the styles just right. Also, as a side note, the way this is handled in the background leaves room for some new features such as exporting CSS for the changes you’ve made. Its certainly an idea being floated around.


CSS Color Representations (Hex + More)

One complaint that showed up time and time again in Twitter was that the Inspector only showed rgb color representations. Many designers wanted the hex representation and had to resort to using Firebug to get that information. Well, we went one step further. You can now represent colors any way you’d like: hex, shorthex, rgb, hsl, or even by its nickname if it has one! For alpha colors you get rgba and hsla. Designers, have at it!


Clicking on the color swatch allows you to cycle through the different representations for just that color. Allowing you to get the different representations that I got in the picture. However, you can set a preference in the gear menu to display all the colors in a particular format.

DOM Storage Updates

The DOM Storage DataGrids now displays live updates. You don’t need to manually refresh every time something changes. Also you can create, edit, and tab through the keys/values. Double click any open space to start creating a new value. Catching on to a theme with my updates? Overall this makes working with DOM Storage just a little more developer friendly.


Natural Sorting of Properties

Who counts “1”, “11”, “12”, “2”, “3”, etc. Certainly nobody I know! So, I implemented a variant of the alphanumerical sorting algorithm for properties when they are displayed in the console. Now you get a much more natural ordering!

Keyboard Shortcuts

Probably not so well known but you can now switch between the different panels of the Inspector with keyboard shortcuts! On the Mac its ⌘[ and ⌘].

Better NodeList Displays

As a developer myself I find the issues that annoy me, and are likely going to annoy other developers, and set out to solve them. One classic problem I had was doing a getElementsByTagName or similar and having the console respond blandly with “NodeList”. Not good enough! NodeLists now display the actual HTML elements in a list just like an Array. Its one of those small details that developers won’t really notice unless its gone, because we expect it.


Resources Interactivity

There were some old feature requests sitting in WebKit’s Bugzilla. They requested opening resources on double click, and adding the ability to drag a resource around like it were a link. I thought they were great ideas!


This was the first feature that required me really digging into WebKit’s source, including touching all platforms. With the help of WebKit developers I eventually added support for viewing all cookie information (secure, httpOnly, etc) and deleting cookies for the Mac. All other platforms were able to display basic cookie information available through document.cookie.


Another developer, bweinstein, just recently landed some really great improvements! He added support for Windows, separated cookies out per domain, and enabled resizable grid columns. Really great work.

Event Listeners

Not having the ability to enumerate the Event Listeners via JavaScript has plagued me, and most likely plenty of other developers, for a very long time. This made viewing Event Listeners an excellent candidate for an Inspector feature.

The implementation as it stands now has some great functionality. There is a new sidebar pane when you inspect an element in the Elements Tree Hierarchy. If the current Node has registered event listeners there is a separate section for each type of event registered (click, mouseover, etc). Within each of these lists is a display of all of the event listeners in the entire event flow for that type. That means you see all the Capturing Event Listeners followed by the Bubbling Event Listeners in the exact order that they execute and on which nodes they are registered.


A few filters will let you customize the list to focus on the entire event flow or just the selected node. This is still a very new feature, one that Firebug doesn’t even have yet. So we are looking for UI improvements and idea on how to improve the feature, but its certainly a cool feature!

JSON Syntax Highlighting

JSON is merely a subset of JavaScript but it wasn’t getting highlighted! A few lines later, the inspector now syntax highlights JSON just like JavaScript.

CSS Syntax Highlighting

The JavaScript syntax highlighter has helped me hundreds of times. Now, hopefully the CSS syntax highlighter will do the same! The colors are very close to Dashcode, they look great, and there is even support for some of the rather complex @import, @media, @font-face, and @variables CSS syntaxes.


Hey, as a birthday gift to myself what could be better then adding some serious styling to those black and white stylesheets? I know what you’re thinking… nothing could be better. Well you’re almost right! With some of the refactoring I did bweinstein was able to apply syntax highlighting to the Elements Tree Hierarchy and got some seriously awesome results. Now the inline scripts and styles are syntax highlighted! These are some really awesome improvements that make working with the Inspector ever more friendly.



To start using any of these features you will need to download the WebKit nightly. Most people think that the nightly overrides their current Safari app. This is not true. The nightly binary is a separate application from Safari, named WebKit. If you just want to try out some of these features you can download the Nightly, and then move it to your trash when you’re done playing with it. No harm, no foul.

These are not nearly all of the new features in the Web Inspector. These are just the ones that I worked on and contributed to. To name some other features there are Scope Bars for the Console and Resources Panel, the ability to view Request and Response HTTP Parameters for Resources (great for debugging AJAX), Resource Status Code indicators, complete Serialization between the inspected page and the inspector, and more.

If you want to contribute feel free to stop by #webkit on Freenode. My handle is JoePeck and I’d be glad to help you out!

mod_rewrite Tutorial on Nettuts

Its been quite a while since I’ve written a blog post. For that I apologize. But, you can be sure that I wasn’t just sitting around! Earlier today, Nettuts published my second tutorial covering URL manipulation with mod_rewrite in Apache’s .htaccess configuration files.

As a reminder to any visitors, if you decide to comment please contribute to the article in some way. I’m not interested in fluff comments. With that said, you can check out the tutorial itself at:

Nettuts Tutorial

You can view the examples here:


And finally you can download the examples (for Apache 2.0) right here. I hope the tutorial will clear up some myths and confusion about mod_rewrite. Cheers.

Web Analytics Taken to the Next Level

I came up with a neat idea the other night. Using localStorage and sessionStorage you could theoretically monitor the number of tabs or windows a visitor has opened for your site. As far as I know, this capability has never before been possible. Well, now it is.

Check out this crude example.

Once you open the monitor, leave that tab/window put. Use the “Spawn Tab” link to create new tabs and windows. The monitor will be notified and display some simple debug. There are 10 second updates per tab/window so that when they close the monitor can detect it. The monitor will detect a close within 15 seconds of the tab/window closing and will display the total time the tab/window plus or minus 10 seconds. Correct values are maintained as the tab/windows browse across pages as long as they stay on the domain! Just about everything you’d want or need.

Again, I mentioned this is rather crude. The fact that the monitor tab remains open is only due to the fact that I wanted to prototype the idea. The majority of the state is stored in localStorage, and each tab/window maintains a single identifier in its sessionStorage to remind the tab/window what id it was while it navigates to multiple pages. Because everything is stored in the storage this system has the capability to become completely distributed. Meaning no “monitor” tab is necessary, and the scripts can determine, and monitor, on their own the existence of all other tabs. Thus, this would be a viable option for the next level of web analytics.

As cool as this is, I don’t think it will provide too much value to the analytics. For the first time webmasters will be able to know how many windows or tabs a visitor opens (and to what pages they open). The webmaster will know more about how its user’s use the website, but I don’t think this statistic will be a game changer. Who knows!

So, how does it work? Very simple. Each tab includes the client.js code to handle updating the localStorage and maintaining its own “tab_id” in sessionStorage. Data it maintains can be whatever you want, I went with some simple information such as its start time, current url, and latest keepalive:

localStorage values

The upkeep for a Tab Client is to restore their session information when you navigate to any new page:

// Create or Restore tab_id
var myTabId =;
if ( myTabId === undefined ) {
  var tabs = localStorage.tabs;
  if ( tabs === undefined ) {
    myTabId = 0;
    localStorage.tabs = "0";
  } else {
    var largest = parseInt( tabs.split(/,/).pop(), 10 );
    myTabId = largest+1;
    localStorage.tabs += "," + myTabId;
  } = myTabId;

And to perform its keepalives:

// Update the Latest Timestamp
function setLatest() {
  var key = 'tab'+myTabId+'_latest';
  localStorage.setItem(key, +(new Date())); 

// Update Status every 10 seconds

I put a few more convenience functions in there to help it update these localStorage keys, and communicate with the monitor which was crudely done through localStorage. That is explained next.

The Tab Monitor as it stands right now receives messages through localStorage’s “storage” event. It also checks all the tab’s “lastest” keepalives to make sure they didn’t pass their 10 second limit. In the case of a tab being closed, it will remove references to that tab and output an approximation of the time the tab was open:

// Listener - receive messages from tabs
window.addEventListener('storage', function(e) {
  if ( e.storageArea === localStorage ) {
    if ( e.key == "tab_msg" ) {
      console.log( e.newValue );
      addMsg( e.newValue ); // Appends to the page

// Purger - clean out tabs that died for 15 seconds
window.setInterval(function() {
  var now = +(new Date()),
      tabs = localStorage.tabs;
  if ( tabs !== undefined ) {
    var toRemove = [], toKeep = [];
    tabs = tabs.split(/,/);
    for (var i=0, len=tabs.length; i<len; i++) {
      var tabId = tabs[i],
          tabLatest = parseInt( localStorage.getItem("tab"+tabId+"_latest") );
      ( (now-tabLatest)>=15000 ? toRemove : toKeep ).push(tabId);
    localStorage.tabs = toKeep.join(',');
    for (var i=0, len=toRemove.length; i<len; i++) {
      var tabId = toRemove[i],
          tabLatest = parseInt( localStorage.getItem("tab"+tabId+"_latest") ),
          tabStart = parseInt( localStorage.getItem("tab"+tabId+"_start") ),
          time = (tabLatest-tabStart)/1000;
      addMsg( "Tab " + tabId + " Closed after " + time + " seconds!" );
}, 5000);

This took a little under an hour to get working. There are still minor issues that I didn’t attempt to resolve. However, if there is interest this could be developed into a completely distributed peer-to-peer communication between tabs/windows on a single domain. However, a little warning. Web Storage is not set in stone. Not all browsers have implemented it and the specification is subject to change at any minute. There has been some rather heated debate on the subject of Web Storage recently, with good reason. All I know is that when its settled, this functionality will continue to exist!

Let me know what you think.

Handling the tab key in a <textarea>

Traversing through input elements with the tab key is important for accessibility reasons. However, every once in a while you come across a situation where traversal isn’t really important. Instead, you want the tab key to actually do something for you. Even still, you may want to do something fancy with the tab key. Wether its replacing it with spaces or something else.

I found an interesting website today that had an interesting idea. You could run some test code on the page to test their library. Their instructions said, “push tab to evaluate the code.” Sure enough you could tell it was working “onblur” for the textarea. The problem with this was that when you pushed tab you lost focus.

I thought about it, and figured you could do a rather simple trick to run some code and refocus on the textarea. It goes a little like this:

window.addEventListener('load', function() {
  var textarea = document.getElementById('txt');
  textarea.addEventListener('keydown', function(e) {
    if (e.keyCode === 9) {
      // operation goes here

Note that to get the actual character you have to get the character from the event. There are many ways to do it, keyCode, charCode, which, even keyIdentifier. You’ll have to mix things up to work across all browsers. Basically 9 is the code for the tab key. So when you get the tab key, it prevents the default behavior and allows you to execute whatever code you want: run some functions, eval some code, display something, ajax request, whatever you want. Simple. I think it would improve a few interfaces. Neat idea to make use of the tab key to perform a function.

You can check out this example of what I mean.