Dart: CSS3 Slider Carousel

The slider carousel by html5rocks now comes with an example in dart. I may have loaded to many  images into the single page, might take a few seconds to load. The source code can be found on github. Dart provides a simpler way to deal with client side programming, cleaner syntax and simple access to the DOM. Go Dart!

screenshot

Dart: Updated Dartium builds for Linux and Mac

Following the similar posts as before, you can get the latest Dartium builds for Mac OSX and 32bit Linux here. My public is can be found on pgp.mit.edu. Please contact me if you have any issues, only providing these until Dartium hits the prime time. Keep in mind that nothing is guaranteed to work at this point… but some stuff does.

wget http://dl.dropbox.com/u/33138127/dartium_macosx/Chromium.app.tar.gz
wget http://dl.dropbox.com/u/33138127/dartium_macosx/Chromium.app.tar.gz.sig
wget http://dl.dropbox.com/u/33138127/dartium_macosx/Chromium.app.tar.gz.md5
wget http://dl.dropbox.com/u/33138127/dartium_macosx/README.txt
gpg --verify Chromium.app.tar.gz.sig Chromium.app.tar.gz
md5sum -c Chromium.app.tar.gz.md5
wget http://gsdview.appspot.com/dart-editor-archive-continuous/latest/DartBuild-linux.gtk.x86.zip
wget http://dl.dropbox.com/u/33138127/dartium/dartium-linux-32bit-Release.tar.gz
wget http://dl.dropbox.com/u/33138127/dartium/dartium-linux-32bit-Release.tar.gz.sig
wget http://dl.dropbox.com/u/33138127/dartium/dartium-linux-32bit-Release.tar.gz.md5
wget http://dl.dropbox.com/u/33138127/dartium/README.txt
gpg --verify dartium-linux-32bit-Release.tar.gz.sig dartium-linux-32bit-Release.tar.gz
md5sum -c dartium-linux-32bit-Release.tar.gz.md5

Dart: Web terminal sample

I’ve always been impressed by the css/html5/javascript web terminals that show off the filesystem API. Now Dart has a sample web terminal with minimal implementation.

webterminal

Simply add your command implementations to the Terminal.dart by adding commands to the CMDS list and providing functions to the matching switch statement.

cmds

switch

With in the next day or so the dart-web-terminal should include an example with filesystem API in dart.

Dart: dart:builtin

dart:builtin are the runtime libraries available to the DartVM. They provide some of the more system level API you would expect such as streams I/O, filesystem I/O, basic TCP socket I/O, platform information, native process invocation.  Most of these class implementations do call “native”, which from the point of view of the DartVM means invoking native VM code. “native” tells the VM to look up in a list for the entry that maps to the following argument after “native”.

_DirectoryNative

nativedirectory.png

While Dart is still Alpha these builtin may not be written in stone, so try not to depend on them too much. They can and do provide you with some neat access to native functionality you would commonly need when written shell/system applications.

By including #import(‘dart:builtin’); you can view the builtin dart files from DartEditor. Currently the DartEditor might show  warnings when including this module but runtime should not be affected. The truth of the matter is, if you explicitly include ‘dart:builtin’ or not, it is still available to you from implicit inclusion in the DartVM.

dartbuiltin

The following should give an idea of what built in objects are accessible and how they may be used. The examples should not be considered best practices, just an idea of how you could use them and that they exist. The code is taken from a sample that can be found on Github

Directory

    Directory d;
    if (l.length >= 2) {
      d = new Directory(l[1]);
    } else {
      d = new Directory(".");
    }
    d.dirHandler = (var dir) {
      print("${dir}");
    };
    d.fileHandler = (var file) {
      print("${file}");
    };
    d.list(true);

File

    File f = new File(l[0]);
    if (!f.existsSync()) {
      print("Error: file does not exist");
      return;
    }
    RandomAccessFile r = f.openSync(FileMode.READ);
    int length = r.lengthSync();
    List buffer = new List(length);
    int readLength = r.readListSync(buffer, 0, length);
    r.close();
    String s = new String.fromCharCodes(buffer);
    print(s);

ChunkedInputStream

    ChunkedInputStream chunkedInputStream = new ChunkedInputStream(f.openInputStream(), 16);
    List c = chunkedInputStream.read();
    while(c!=null) {
      StringBuffer sb = new StringBuffer();
      c.forEach((int b) {
        sb.add("0x");
        if (b.toRadixString(16).length == 1) {
          sb.add("0");
        }
        sb.add(b.toRadixString(16));
        sb.add(" ");
      });
      print(sb.toString());
      c = chunkedInputStream.read();
    }

InputStream
OutputStream

    File src = new File(arg[1]);
    File dest = new File(arg[2]);
    var srcStream = src.openInputStream();
    var destStream = dest.openOutputStream();
    destStream.write(srcStream.read());
    srcStream.close();
    destStream.close();

StringInputStream
DynamicListInputStream
ListInputStream
ListOutputStream

Platform

 Platform p = new Platform();
 print('{"operatingSystem":${p.operatingSystem()},"numberOfProcessors":${p.numberOfProcessors()},"pathSeparator":${p.pathSeparator()}}');

Process

    Process ps = new Process.start('ps', []);
    StringBuffer messages = new StringBuffer();
    ps.exitHandler = (int status) {
      ps.close();
      print(messages.toString());
    };
    ps.stdout.dataHandler = () => _readAll(ps.stdout, messages);
    ps.stderr.dataHandler = () => _readAll(ps.stderr, messages);

ServerSocket

    // initialize the server
    serverSocket = new ServerSocket(host, 0, 5);
    if (serverSocket == null) {
      throw "can't get server socket";
    }
    serverSocket.connectionHandler = onConnect;
    print("accepting connections on ${host}:${serverSocket.port}");

Socket

    sendSocket = new Socket(host, serverSocket.port);
    if (sendSocket == null) {
      throw "can't get send socket";
    }
    // send first 4 bytes immediately
    for (int i = 0; i < 4; i++) {
      sendByte();
    }
    // send next 4 bytes slowly
    new Timer.repeating((Timer t) {
      sendByte();
      if (bytesSent == bytesTotal) {
        sendSocket.close();
        t.cancel();
        print("finished sending");
      }
    }, 500);

SocketInputStream
SocketOutputStream

Timer

<pre>    if (l.length >= 2) {
      try {
        milliSeconds = (Math.parseInt(l[1]).abs()*milliSeconds);
      } catch (BadNumberFormatException ex) {}
    }
    timer = new Timer((var t) {
      print("\nTime elapsed on Timer");
    }, milliSeconds);

Dartium Mac OSX Build rev 117836

For those interested in trying Dartium on MacOSX, here is a build of Dartium from Dart’s bleeding_edge. I have just tested it enough to run hello world at the moment. I’d like to get feed back on how it runs for others if possible. 

NewImage

wget http://dl.dropbox.com/u/33138127/dartium_macosx/Chromium.app.tar.gz
wget http://dl.dropbox.com/u/33138127/dartium_macosx/Chromium.app.tar.gz.md5
wget http://dl.dropbox.com/u/33138127/dartium_macosx/README.txt
md5sum -c Chromium.app.tar.gz.md5

It might be best to refer to this previous post for any additional information.

Dart: Throwing Darts from CouchDB

CouchDB provides an excellent NOSQL database with simple REST API. Continuing on with the odds and ends in Dart, I’d like to show how one could interface with CouchDB in Dart. Following the “Getting started with Python” I was able to stub out a simple wrapper implementation in no time. At some point a full wrapper should be done, I’ll possible look into it in the coming months.

CouchBase provides full standalone community build, best option if you don’t want to deal with building and deploying on your Mac. Pairing that up with XAMPP and you’ll be able to write the client side that communicates to the apache web server which then proxies to CouchDB. After installing XAMPP two files need to be edited to ease the local deployment.
XAMPP/etc/http.conf - Add the ProxyPass configuration.
XAMPP/etc/extra/httpd-userdir.conf - Add the user directory to point to the default dart folder location.
Httpconf
Fire up CouchDB and Apache, then open chrome http://127.0.0.1/couchdb and you should see the following.
Localhost
From here we can use XMLHttpRequest provided in the dart:html library to make requests to the Apache web server which proxy to CouchDB. One issue I ran into was DOMException INVALID_STATE_ERR when trying to set the headers. You must call open() before your able to call setRequestHeader().
 // Basic http methods
  getHttp(var uri) {
    XMLHttpRequest c = connect();
    c.open('GET', uri, false);
    c.setRequestHeader('Accept', 'application/json');
    c.send();
    return c.responseText;
  }

  postHttp(var uri, var body) {
    XMLHttpRequest c = connect();
    c.open('POST', uri, false);
    c.setRequestHeader('Content-type', 'application/json');
    c.send(body);
    return c.responseText;
  }

  putHttp(var uri, [var body]) {
    XMLHttpRequest c = connect();
    c.open('PUT', uri, false);
    if (body is String && body.length > 0) {
      c.setRequestHeader('Content-type', 'application/json');
      c.send(body);
    } else {
      c.send();
    }

    return c.responseText;
  }

  deleteHttp(var uri) {
    XMLHttpRequest c = connect();
    c.open('DELETE', uri, false);
    c.send();
    return c.responseText;
  }
Domexception
From there stubbing out a simple interface for dart with default implementation was easy.
Couchdb
The CouchDBWrapperImpl does wrapping for calling to the CouchDB using the default keyword helps to hide the implementation from the interface in a factory type way.
Couchdbimpl
Opening up chrome to http://127.0.0.1/<username&gt; provides access into the users dart directory.
Fileview
Clicking on CouchDBExample.html should run the sample code.
Demo
The interfacing with CouchDB was simple and quick, a more elegant solution would be a full client implementation that lets you modify objects more indirectly.  Sample code on github.

Dart: Using prefix for #import

Using “prefix” is great for managing how your application references libraries in Dart. At the moment Dart is still in alpha so this exact method or style may change at some later date. From the Language Specification (0.06) Libraries have a very simple definition.

A library consists of (a possibly empty) set of imports, and a set of top level
declarations. A top level declaration is either a class (7), an interface (8), a type
declaration, a function (6) or a variable declaration (5).

Lets dive in and create one main application and one cipher application that will be a library.

Now if we #import CipherLib from filesystem path into our MainApplication both main functions should conflict.

Why this happens is clearly defined in the specification.

Imports assume a global namespace of libraries (at least per isolate). They also assume the library is in control, rather than the other way around. It is a compile-time error if a name N is introduced into the library scope of a library A, and either: N is declared by A, OR Another import introduces N into the scope of A. This implies that it is a load-time error for a library to import itself, as the names of its members will be duplicated.

The MainAppication can be adjusted by adding the prefix parameter to the #import declaration. Now from the prefixed name we can call the main method.

From this point lets add another library, will call it XORCipher which will call its library “CipherLib”. The XORCipher and CaesarCipher will have libraries named “CipherLib”, both have functions that have the same name but take different parameters. Now we shall run into a problem that could be presented when using others libraries or code, we have conflicting names in the global namespace of our main application.

The way we resolve this is by adding prefix to one or both libraries and call them from the fully qualified names.

#import('../CaesarCipher/CaesarCipher.dart', prefix:"Caesar");
#import('../XORCipher/XORCipher.dart', prefix:"XOR");

void main() {
  String s = "HELLOWORLD";
  print("${s}");
  
  s = XOR.EncryptDecrypt(s);
  print("After encrypt XOR ${s}");
  s = XOR.EncryptDecrypt(s);
  print("After decrypt XOR ${s}");
 
  s = Caesar.EncryptDecrypt(s, true);
  print("After encrypt Caesar ${s}");
  s = Caesar.EncryptDecrypt(s, false);
  print("After decrypt Caesar ${s}");
}

Another way to encapsulate source code using libraries is to use the #source declaration in a #library and then to #import the library into your application. From the language specifications:

An include directive specifics a URI where a Dart compilation unit that should be incorporated into the current library may be found. A compilation unit is a sequence of top level declarations. Compiling an include directive of the form #source(s); causes the Dart system to attempt to compile the contents of the URI that is the value of s. The top level declarations at that URI are then compiled by the Dart compiler in the scope of the current library. It is a compile-time error if the contents of the URI are not a valid compilation unit. It is a compile-time error if s is not a compile-time constant.

An example of this type of library can be seen in HashLib/hashlib.dart:

#library('hashlib');

#source('hasher.dart');
#source('hasherimpl.dart');
#source('aphash.dart');
#source('bkdrhash.dart');
#source('dekhash.dart');
#source('djbhash.dart');
#source('elfhash.dart');
#source('jshash.dart');
#source('pjwhash.dart');
#source('rshash.dart');
#source('sdbmhash.dart');
#source('nullhash.dart');
#source('bphash.dart');
#source('fnvhash.dart');

Another great example of this can be seen in John Evans LUCA UI Framework unit test code. He needed access to some internal dom objects but wanted to preserve the ability to use the elegantly designed html library.

 
#import('dart:html');
#import('dart:dom', prefix:'dom');
#import('../unit_test_framework/UnitTestFramework.dart');
#import('../core/LUCA_UI_Framework.dart');

Its not uncommon to run into instances where two libraries or source files may define classes, interfaces, functions, type definitions that have similar names in other libraries or source files. The best way to work in these types of situations is to add a prefix where your #import are. A very common one that people run into is with “html”, Node and Element class. So individuals wanting to create some type of search or sorting might also want to use the Node name, best answer would be to prefix “html” or your own library code. After your able to reference the library by its fully qualified name, instead of assuming it was globally included. This does feel similar to the using alias in C#, but with a feeling of inversion of control to the library.

References:
Sample code dart-using-prefix-example
Language specification