Javascript in the commandline

I don’t know for how long a little script has been running on my computer to keep me sane in the Windows driveletter jungle.

These days I work almost exclusively on Windows because frankly it fits my daily usage patterns best… that doesn’t mean it’s a perfect fit, but with a combination of Cygwin and a few dozens other tools as well as a Linux-like directory setup I can retain at least most of my sanity.

One very important tool in the way I organize my system are symlinks or more specifically junctions (they provide roughly the same functionality as Windows symlinks, but Windows doesn’t try to translate them to their target path when an application requests something inside).

For example if you want to find one of my external harddisks you’ll find it under \media\WD2000 which is a junction pointing to the drive’s root folder.

Theoretically you can do this without any junctions by setting that drive as a virtual folder. Problem is: Windows gets confused if you regularly change your external drives. Even more so if TrueCrypt is involved.

So I decided to use the junctions approach and write a little shell script to update the junctions automatically. FSUtil provides all the needed functionality, so it seemed simple enough. At least until I tried to do the necessary string processing using the Windows shell. Urgh. In short: Don’t even try. Whatever you try to do, it won’t work.

Luckily I had a Spidermonkey build at hand (js.exe) and while the Spidermonkey JS shell isn’t intended for shell scripting, it can handle STDIN and STDOUT which is really all you need. js.exe is now also part of XULRunner builds, so you can easily grab it from ftp://ftp.mozilla.org/pub/xulrunner/nightly/

Yes, I could have used dozens of other solutions. SED, WScript: but all of them would have required me to learn their syntax when I didn’t really want to. I just wanted to do string processing and I kinda felt that if I knew probably the best-known language for string processing, I shouldn’t have to learn another one for the same purpose.

What you do if you want to use JS for string processing, is make it part of a pipe chain, like this:

js -e “main=’f1′;” %0|cmd /K|js -e “main=’f2′;” %0|cmd /K

That looks worse than it actually is, it just means:
run js.exe (with main set to f1 and the cmd file loaded as js) output through cmd.exe
send cmd.exe output to js.exe (with main set to f2 and the cmd file loaded as js)
run js.exe (with main set to f2 and the cmd file loaded as js) output through cmd.exe

…you get the idea: You just alternate between js.exe and cmd.exe, each operating on the previous one’s output.

The only real pitfall is that your cmd file is both a cmd file and a js file at the same time, but that’s pretty easy to overcome:

REM = 0; /*
@echo off
cls
[[SHELL_CODE]]
goto :END
REM ; */
[[JS_CODE]]
REM ; /*
:END
REM ; */

Again: it looks worse than it is: You simply use JS comments to make js.exe ignore the shell code (you need a few dummy REM statements as well), while using a mixture of Shell comments and jump statements to make cmd.exe skip over the JS code.

And that’s pretty much it. Other then that you only really need to know that in order to read something from STDIN with js.exe you call readline() until it returns null and print(“foo”) to output “foo\n” (including a newline character).

Throw in something like this and you can call different functions directly;

var lines=[];
var line;
while(null!=(line=readline())) lines.push(line);
this[main](lines);

with
js -e “main='[[function name]]’;” %0

And finally, here’s the script file that I’m using to keep my junctions up to date:
http://www.tapper-ware.net/devel/js/js.shellJunctionUpdates/readyDriveList.js.cmd
It basically checks for a file \.mountpoint on every drive and creates a junction to that drive in the location specified inside the .mountpoint file (liek this: MOUNTPOINT=C:\media\WD2000)

Firefox loading times: beware of FlashGot

A while ago, I was discussing the startup time of Firefox with a few friends and it became apparent that we got very different results: For me, a Firefox cold start took between 0.3 and 0.7 seconds, compared to about 4 seconds for everybody else. All of us had a bunch of Addons installed (12 in my case), so it wasn’t exactly the amount of Addons that was causing it.

After some experimenting we found that in every single case the launch time got down to below one second if FlashGot (which I had deactivated for some reason that I can’t even remember) was disabled.

That doesn’t make FlashGot a bad addon, but you should be aware that startup time increases dramatically.

Current Mozilla Fennec / Firefox Mobile builds on Windows

Aside from my main work machine I own a tiny Acer Netbook. It’s not the best device around with limited processing power and much more importantly, a 1024×600 screen. Using Firefox on it isn’t exactly a joy because you often get horizontal scroll bars and the vertical size of the content is tiny if you have the title bar, the navigation bar and the tabbar open (even with bookmarks-toolbar and menubar disabled).

Some time ago I tried using Fennec and while it’s definitely not perfect, the way zoom and scrolling is handled alone makes it the better alternative for touchpads and tiny screens. In Fennec you drag to scroll (which with your off the mill Synaptics touchpad means double-tap, then move) and double-tap without moving to zoom in on a paragraph (which really is immensely useful if your screen is too small to fit a whole lot of text onto it without making it so tiny that it’s hard to read). Besides, all UI-elements are hidden unless you scroll to them (tabs on the left, settings on the right, location at the top).

When Fennec was first released, there were a couple of Win32 builds available, but apparently support for Windows was dropped with the release of the 1.0 version.

Luckily, you can still use it on Windows, courtesy of Mozilla’s XULRunner platform which Fennec uses internally: Just grab a recent Fennec Linux build, drop in a recent XULRunner build for Windows, edit the application.ini to allow for newer versions of XULRunner and you’re set.

Grab a normal Linux build from
ftp://ftp.mozilla.org/pub/mobile/nightly/latest-mobile-trunk/
(currently that’s fennec-1.1a2pre.en-US.linux-i686.tar.bz2)

And a XULRunner runtime from
ftp://ftp.mozilla.org/pub/xulrunner/nightly/latest-trunk/
(currently that’s xulrunner-1.9.3a4pre.en-US.win32.zip)

Extract the Linux Fennec built somewhere and remove the xulrunner directory.

Then, drop the xulrunner win32 runtime in its place (you can also remove the shell scripts).

Take the xulrunner-stub.exe from the xulrunner directory and drop it into the main Fennec directory. You can name it any way you like (mine is simply called Fennec.exe). You’ll need mozcrt19.dll DLL as well, just copy it along.

If you get an error about XULRunner being the wrong version, just open application.ini in a text editor and change MaxVersion to reflect the version you use.

And that’s it: Now you’ve got the best browser for your main computer and your netbook 🙂

Calling methods in Javascript, without really calling them

Update: I think some people take this a bit too seriously: It’s a fun little experiment: nothing more, nothing less.

Sometimes you’re just lazy. Especially when it comes to typing. And while the round brackets in a function call may not seem like a whole lot of overhead, they do get tiresome if you have to type them over and over again… especially if you don’t think you need them since the function doesn’t return anything and needs no arguments: Something that’s awfully common in object-oriented UI programming.

Surprisingly enough, this isn’t all that difficult to do in Javascript, since a lot of methods are called implicitly… toString is probably the most famous one, but there’s also valueOf that does more or less the same but is called for numeric (and some other) casts.

The simplest way to call it is including a sign:

+myFunction;

which effectively translates to

window.parseFloat(myFunction.valueOf());

so all we need to do is provide a valueOf method that calls the function itself, like so:

Function.prototype.valueOf=function(){this.call(this); return 0;};

and suddenly the plus sing is all that’s needed for our call.

Especially in an object oriented environment you’ll have a lot of these calls, but you’ll have to fix the scope since these methods would be called in the scope of the method itself:

Function.prototype.fix=function(s){var t=this; return function(){ return t.apply(s,arguments); }; };

Using this method in the constructor to overwrite each method with a fixed-scope wrapper solves this:

var Foo=function(){
  this.myMethod=this.myMethod.fix(this);
};

or a bit more automated:

var Foo=function(){
  for(var i in this)
    if(typeof(this[i])=="function")
      this[i]=this[i].fix(this);
};

and finally we end up with this whole example (after a bit of OOP refactoring):

var StandardClass=function(){};
  StandardClass.prototype.initMethods=function(){
    for(var i in this)
      if(typeof(this[i])=="function" && this[i].dontWrap!==true)
        this[i]=this[i].fix(this);
};
StandardClass.prototype.initMethods.dontWrap=true;

Function.prototype.fix=function(s){
  var t=this;
  return function(){
    return t.apply(s,arguments);
  };
};

Function.prototype.valueOf=function(){
  this.call(this);
  return 0;
};

var Foo=function(name){
  this.initMethods();
  this.name=name;
};
Foo.prototype=new StandardClass;

Foo.prototype.showName=function(){
  alert(this.name);
};

Foo.prototype.showNameUpperCase=function(){
  alert(this.name.toUpperCase());
};

var myFoo=new Foo("Hello World");

+myFoo.showName;
+myFoo.showNameUpperCase;

Why it is right for null to be of type object in Javascript

I’m really amazed how many articles you can find about how stupid it is that typeof null returns object in Javascript. Many people feel that this is wrong since null basically means “not currently an object”.

The mistake here is thinking that a variable with type object actually holds an object. It’s a simple mistake to make, but one that will bite you times and times again:

A variable of type object actually means object-pointer. Unlike primitive types which have more less a direct value, these variables don’t actually hold a value itself, just a non-exclusive pointer to an object. That pointer is their value.

That’s also why objects are apparently passed by reference to functions: While they are actually passed by value, the passed value is the pointer.

If you look at it like this, it actually seems kind of bizarre that typeof null could return anything but object. After all it is still a pointer, just a pointer that points nowhere.

HTML Tutorial (in German)

It’s not finished yet, but I’m writing this for a friend to help her with her classes and it might already be useful for others too:

I couldn’t find what I consider a good tutorial on HTML (meaning that it focuses on document structure instead of flashy design), so I started writing my own.

In its current state as it covers HTML, or more precisely XHTML (HTML has too many implicit rules to be an effective learning tool in my oppinion) and everything needed (Unicode, XML, tools, …). However CSS and Javascript are not yet done.

http://www.tapper-ware.net/stable/HTML.Tutorial/index.xhtml

Emulating SVG path animated d attribute with Canvas

This isn’t particularly breathtaking, but I was looking at creating a simple animation without Flash. And seeing as I’m most comfortable with Inkscape as my primary vector graphics editor I figured “Why not just animate the path’s data attribute to interpolate keyframes?”

Sadly, I couldn’t find any browser that supports it yet, but I wasn’t ready to give up my hope of using Inkscape to generate the data… so I looked into using Javascript to animate everything. I eventually moved from using the SVG Dom to Canvas based drawing, but the data comes straight from a SVG document:

http://www.tapper-ware.net/stable/HTML5-animate-path-d/testdata.svg

This isn’t really exciting or breathtaking, just a friendly reminder what we could do if the path d attribute was finally animated 🙂 .

http://www.tapper-ware.net/stable/HTML5-animate-path-d/

GoogleSuggest on PlayStationPortable

Web developers fear the PSP … and with good reason. The NetFront browser is well, how do I put this… “in need of improvements” to the point where it feels intentionally crippled.

Point in case: The support for iFrames. It’s surprisingly good, but for some reason you can’t change an iFrame’s content by setting the src Attribute. One might thing that this is because iFrames are not dynamic, but alas: No.

The reason why setting the src Attribute doesn’t work is because it’s been stripped of its setter which usually causes the document to change. The functionality is still there, you just have to address it differently:

window.frames[0].document.location.replace(newUrl);

What we do here is use the legacy frames API to dive down into the iframe’s content, then do a location.replace inside and voilà.

The net effect is that we can now do AJAX… well kind off: we can load different documents and if these reside on the same domain as the host document, we can let these documents trigger callbacks in our code to deliver data.

This for example, wraps GoogleSuggest in such a callback:

http://www.tapper-ware.net/devel/js/JS-PSPKeyboard/suggestEcho.php?q=moz

Add a few form elements, and you’ve got GoogleSuggest on the PSP (it’s not pretty yet, but it works). Note that this works, but won’t look good on a PC as font sizes are nonsensical and are meant to force the PSP browser to either use the big or the small font.

http://www.tapper-ware.net/devel/js/JS-PSPKeyboard/

Firefox with Direct2D: Speed you can feel

Firefox recently got hardware acceleration in its nightly builds via Vista’s and Win7’s Direct2D acceleration. And with the Layers project promising hardware acceleration across all platforms soon (as well as IE9 also providing hardware acceleration via Direct2D) for the first time there’s a reasonable chance that we will have good performance on all platforms, even default Windows systems with Internet Explorer.

When a Direct2D supporting version of Firefox was first released last year I wrote a stupid little stresstest to see how much performance could be gained and I eventually compiled it into a video. It really does nothing but scale and rotate a bunch of image elements, but apparently the bright colors make people excited.

http://www.tapper-ware.net/stable/web.dom.stresstest.transform/

You can see it running side-by-side in recent versions of Opera, Safari, Chrome and Firefox with and without Direct2D here: