May 07

Mac OS X – HTMLEncoder Dashboard Widget

Filed under: Playground | Taged as: | Comments Off

The latest release of Mac OS X comes with an new feature: the Dashboard. It provides an environment for miniprograms to handle some useful but low-level tasks.These so called Widgets can easily be coded with standard HTML , CSS and some Java Script.

The Encoder Widget is made up of a small interface for encoding HTML entites into their appropriate representation. It contains two textfields: one for the input to encode and one for displaying the result. It further offers some Widget typical functions like a backside with information and the recommended transition between front and back.

As Java Script is not capable of doing the encoding in a convenient way on it’s own, this process is done by a Python script. It uses the htmlentitydefs module and combines a regular expressions with the entitydefs dictionary to translate entities in a string. The entity to encode is provided as an command line argument and the result is printed on stdout.

#!/usr/bin/python

import htmlentitydefs
import re, string, sys

pattern = re.compile(r"[&><"x80-xff]+")

entity_map = {}

for i in range(256):
entity_map[chr(i)] = "
&#%d;" % i

for entity, char in htmlentitydefs.entitydefs.items():
if entity_map.has_key(char):
entity_map[char] = "&%s;" % entity

def escape_entity(m, get=entity_map.get):
return string.join(map(get, m.group()), "")

def escape(string):
return pattern.sub(escape_entity, string)

print escape(sys.argv[1])

The interesting and dull part of the Widget is the communication between Java Script and the Python encoder. The widget object – an Apple extension for Widgets – has a special method that allows to run scripts on the command line and retrieve their results. This result is simply placed in an HTML textifield. The following snippets shows this step:

if (window.widget){
var result = widget.system("/usr/bin/python encoder.py '" + value + "'", null).outputString;
document.getElementById("output").value = result;
}

So the Widget rolls out the logic to a full featured scripting language like Python and Java Script simply cares about the eventhandling and the management of the Widget itself. This seems to be a nice way of creating small but very functional programms with a neat seperation of logic and layout.

The Widget is still in version 0.5 due to some problems dealing with german special chars on the Mac command line.

Download the Mac OS X HTML Encoder Widget. Read more on the topic at developer.apple.com

Comments are closed.