2012年5月28日月曜日

WebSocket client with Dart, WebSocket server with Go

ちょっと前の話になるけど、5/12に開催されたDartのハッカソンに参加して、そこでWebSocketを用いてウェブアプリをつくるチームに参加した。自分はここで公開してるSVGアニメーション用のコードがあったので、それを用いたアプリを作ってきた。

その場ではサーバーもクライアントもDartで書いたんだけど、個人的にはサーバーサイドはGoで書きたかったので改めてGoで書きなおしてみた。ちなみにハッカソンではGithubを使って開発したので、それを自分のところへForkして拡張してる。場所はここね。

server.go

基本的にはmanageClientという関数がクライアントに関するリソースを管理するアクターで、serveClient内での各クライアントとのやりとりはすべてこのmanageClientに対して転送される。例えば新規にクライアントがつながってきた場合はAddClientRequestがserveClientからmanageClientに対して送られ、クライアント一覧に相当するmapにクライアントとの接続が格納される。

ちなみにちょっと苦労したのがscriptやらCSSやらをGoのhttpサーバー経由でどうやってホストするのか、という点。それは色々調べたところhttp.ServeFile()という関数を使うとファイルに対するリクエストは大体いい感じに処理してくれることがわかったので、下のコードはそれを採用している

package main

import (
 "code.google.com/p/go.net/websocket"
 "net/http"
 "fmt"
)

type RequestType int
type ResponseType int

var (
 requestQueue = make(chan Request)
 responseQueue = make(chan Response)
)

const (
 // Request
 GENERATE_CLIENT_ID RequestType = 0
 ADD_CLIENT RequestType = 1
 REMOVE_CLIENT RequestType = 2
 BROADCAST RequestType = 3

 // Response
 CLIENT_ID ResponseType = 0
)

type RequestParameter struct {
 clientID int
 Connection *websocket.Conn
}

type DisplayParameter struct {
 Remark string
 Duration string
 Path string
 Rotate string
}

type Request interface {
 Type() RequestType
 ClientID() int
 Process(clientList map[int]*websocket.Conn, queue chan Response, currentClientID *int) map[int]*websocket.Conn
}

type GenerateClientIDRequest struct {
 RequestParameter
}

type BroadcastRequest struct {
 RequestParameter
 DisplayParameter
}

type AddClientRequest struct {
 RequestParameter
}

type RemoveClientRequest struct {
 RequestParameter
}

type Response interface {
 Type() ResponseType
}

type GenerateClientIDResponse struct {
 ClientID int
}

func (gcr GenerateClientIDResponse) Type() ResponseType {
 return CLIENT_ID
}

func (gcm GenerateClientIDRequest) ClientID() int {
 return gcm.clientID
}

func (gcm GenerateClientIDRequest) Type() RequestType {
 return GENERATE_CLIENT_ID
}

func (gcm GenerateClientIDRequest) Process(clientList map[int]*websocket.Conn, queue chan Response, currentClientID *int) map[int]*websocket.Conn {
 res := GenerateClientIDResponse {
  *currentClientID,
 }
 queue <- res
 // proceed to next id
 *currentClientID++
 return clientList
}



func (acm AddClientRequest) ClientID() int {
 return acm.clientID
}

func (acm AddClientRequest) Type() RequestType {
 return ADD_CLIENT
}

func (acm AddClientRequest) Process(clientList map[int]*websocket.Conn, queue chan Response, currentClientID *int) map[int]*websocket.Conn {
 clientList[acm.clientID] = acm.Connection
 fmt.Printf("Added client. %d clients existing.\n", len(clientList))
 return clientList
}

func (bm BroadcastRequest) ClientID() int {
 return bm.clientID
}

func (bm BroadcastRequest) Type() RequestType {
 return BROADCAST
}

func (bm BroadcastRequest) Process(clientList map[int]*websocket.Conn, queue chan Response, currentClientID *int) map[int]*websocket.Conn  {
 // send a text message serialized as JSON.
 for id, client  := range clientList {
  fmt.Printf("Sending to %d\n", id)
  err := websocket.JSON.Send(client, bm.DisplayParameter)
  if err != nil {
   fmt.Printf("error: %s\n",err)
   // remove client
   delete(clientList, id)
  }
 }
 fmt.Println("Broadcasted")
 return clientList
}

func (rcm RemoveClientRequest) ClientID() int {
 return rcm.clientID
}

func (rcm RemoveClientRequest) Type() RequestType {
 return REMOVE_CLIENT
}

func (rcm RemoveClientRequest) Process(clientList map[int]*websocket.Conn, queue chan Response, currentClientID *int) map[int]*websocket.Conn  {
 // remove client
 delete(clientList, rcm.clientID)
 fmt.Printf("Removed client ID:%d. %d left\n", rcm.clientID, len(clientList))
 return clientList
}

/**
  * Message loop for the client manager
  */
func manageClient(reqQueue chan Request, resQueue chan Response) {
 var currentClientID int = 0
 clientList := make(map[int]*websocket.Conn, 0)
 fmt.Println("Entering client manage loop")
 for {
  select {
  case msg := <- reqQueue:
   fmt.Printf("client:%d type:%d\n", msg.ClientID(), msg.Type())
   clientList = msg.Process(clientList, resQueue, &currentClientID)
  }
 }
}

/**
  * Get a new client ID from the client manager
  */
func generateClientID(reqQueue chan Request, resQueue chan Response)  int {
 msg := GenerateClientIDRequest {}
 reqQueue <- msg
 res := <- resQueue
 v, _ := res.(GenerateClientIDResponse)
 return v.ClientID
}

/**
  * Function that serves each client
  */
func serveClient(ws *websocket.Conn, reqQueue chan Request, resQueue chan Response) {
 id := generateClientID(reqQueue, resQueue)
 defer func() {
  // remove client when exiting
  msg := RemoveClientRequest {
   RequestParameter {
    id,
    ws,
   },
  }
  reqQueue <- msg
 }()

 // add client first
 msg := AddClientRequest {
  RequestParameter {
   id,
   ws,
  },
 }
 reqQueue <- msg
 fmt.Println("Entering receive loop")
 for {
  var param DisplayParameter
  err := websocket.JSON.Receive(ws, &param)
  if err != nil {
   fmt.Printf("receive error: %s\n",err)
   break
  }
  fmt.Printf("recv:%#v\n", param)

  // broadcast received message
  msg := BroadcastRequest {
   RequestParameter {
    id,
    ws,
   },
   param,
  }
  reqQueue <- msg
 }
}

/**
  * Handler for the websocket json server
  */
func echoJsonServer(ws *websocket.Conn) {
 fmt.Printf("jsonServer %#v\n", ws.Config())
 serveClient(ws, requestQueue, responseQueue)
}

/**
  * Serve all files (html, dart, css)
  */
func mainServer(w http.ResponseWriter, req *http.Request) {
 path := req.URL.Path[1:]
 fmt.Printf("path: %s\n",path)
 http.ServeFile(w, req, path)
}

func main() {
 // start an actor that processes requests from every client
 go manageClient(requestQueue, responseQueue)

 // setup the handlers
 http.Handle("/echo", websocket.Handler(echoJsonServer))
 http.HandleFunc("/", mainServer)
 fmt.Println("serving...")
 port := 8080
 err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
 if err != nil {
  panic("ListenAndServer: " + err.Error())
 }
}

client.dart

クライアント側で実行されるDartのコードが以下。いままでのサンプルと違うのは、他のクライアントとポスト内容を共有するためポストボタンをクリックしたら即websocketで内容を送っているところ。実際の表示処理はサーバー側からブロードキャストされてきたメッセージに対してon.messageのハンドラで実行することになる。

#import("dart:html");
#import("dart:json");
#import("RemarkDisplayer.dart");
#import("SVGRemarkDisplayer.dart");
#import("Unit.dart");

void main() {
    // initialize displayers
    final int MAX_NUMBER_OF_REMARKS = 15;
    final int MAX_SPEED = 100;
    var displayer = new SVGRemarkDisplayer();
    displayer.initialize("#stage", MAX_NUMBER_OF_REMARKS);

    // create websocket and add handlers
    WebSocket webSocket = new WebSocket("ws://localhost:8080/echo");
    Element status = document.query("#statusArea");
    webSocket.on.message.add((event) {
            // display remark with given parameters
            var message = event.data;
            Map map = JSON.parse(message);
            DisplayParameter param = new DisplayParameter.map(map);
            displayer.display(param);
        });

    // connect post button with websocket
    TextAreaElement textNode = document.query("#remarkText");
    TextAreaElement pathNode = document.query("#pathString");
    Element postButton = document.query("#postRemark");
    InputElement speedNode = document.query("#displaySpeed");
    InputElement rotateNode = document.query("#rotateRemark");
    postButton.on.click.add((Event e) {
        String message = textNode.value;
        String path = pathNode.value;

        bool rotate = rotateNode.checked;
        var num = speedNode.valueAsNumber;
        var duration = (MAX_SPEED - num.toInt()) * 100;
        var param = new DisplayParameter(message, duration, Unit.Millisecond, path, rotate);
        String paramJson = JSON.stringify(param.toMap());
        webSocket.send(paramJson);
    });
}

感想

Dartで書いたときと比べてGo版はかなりコード量が増えた気がする。大半はmanageClientとどういったメッセージをやりとりするかの定義なので、アクターモデルをやるからにはしょうがないのかもしれない。ただやっぱり厳密に書こうとするとアクターモデルはめんどう。もっと規模が大きくなればアクターモデルの恩恵がわかる、かも?

サーバー側の出力例

サーバー側をビルド・実行して、上記のDartクライアントからGoogleのアスキーアートをPostした場合の出力が下のログ。参考に掲載しておく。

$ go build server.go 
$ ./server 
serving...
Entering client manage loop
path: 
jsonServer &websocket.Config{Location:(*url.URL)(0x188abd80), Origin:(*url.URL)(0x188abdc0), Protocol:[]string(nil), Version:13, TlsConfig:(*tls.Config)(nil), handshakeData:map[string]string(nil)}
client:0 type:0
Entering receive loop
client:0 type:1
Added client. 1 clients existing.
path: favicon.ico
recv:main.DisplayParameter{Remark:"\u3000\u3000\u3000\u3000_,,,,._\u3000\u3000\u3000\u3000\u3000 \u3000 \u3000 \u3000 \u3000 \u3000 \u3000 、-r\n\u3000 \u3000,.','\" ̄`,ゝ\u3000_,,,_\u3000\u3000 _,,,_\u3000\u3000 _,,,,__,. | |\u3000 _,,,,,_\n\u3000\u3000{ {\u3000\u3000 ,___\u3000,'r⌒!゙! ,'r⌒!゙! ,.'r⌒!.!\"| l ,.'r_,,.>〉\n\u3000\u3000ゝヽ、\u3000~]|\u3000ゞ_,.'ノ\u3000ゞ_,.'ノ\u3000ゞ__,.'ノ\u3000| l {,ヽ、__,.\n\u3000\u3000\u3000`ー-‐'\"\u3000\u3000 ~\u3000\u3000\u3000 ~\u3000\u3000〃 `゙,ヽ ̄` `゙'''\"\n\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000 ゙=、_,.〃 ", Duration:"5000&ms", Path:"M10,150 A15 15 180 0 1 70 140 A15 25 180 0 0 130 130 A15 55 180 0 1 190 120 A15 10 170 0 1 10 150", Rotate:"false"}
client:0 type:3
Sending to 0
Broadcasted

2012年5月4日金曜日

SVG Animation in Dartium

ブラウザ上で何らかのアニメーションをさせようとした場合、選択肢が色々ある。以前はCSS3を使ったし、他にもCanvasを使ったりSVGを使ったりスクリプトベースのアニメーション(要素の位置を定期的に更新する等)もやろうと思えばできる。今回はそのなかでもSVGを用いたアニメーションをDartでやってみた。

SVGでアニメーションする理由

SVGでアニメーションさせようとした理由は主に表現の簡単さから。

SVGはxmlの一種なので、マークアップの形で比較的簡単に文字列を回転させたり指定されたパスの上を通るようなアニメーションを記述することができる。Canvasやスクリプトベースのアニメーションのように1フレームごとにちょっとずつ処理をする、といった下回りを記述する必要もなく、アニメーションの定義だけ書けばあとはブラウザがよろしくやってくれるのはかなり楽。加えてアニメーションの描画に関してもすべてブラウザ側に委託されているので、ブラウザがかしこく描画してくれさえすれば人間が細々チューニングする必要もない。

DartでSVGアニメーション

dartからSVGアニメーションさせようとした場合はいくつか落とし穴があって、そのなかでも一番大きい穴はDartium側のバグだったんだけど、とりあえずうまくいったのでサンプルを示す。

html

まえつくったCSS3のアニメーションとほぼ同等の動きをSVGで再現したつもり。一点違うのがスライダーで速度の調整をできるようにした点。ちなみに、bodyの閉じタグの前に入ってるscriptは現状のDartiumのバグを回避するためのもの。

<!doctype html>
<head>
    <meta charset="utf-8">
    <title>dartlang test</title>
    <link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="./css/client.css" />
</head>
<body>
    <script type="application/dart"  src="./script/svgtest.dart"></script>
    <div class="navbar">
        <div class="navbar-inner">
            <div class="container">
                <a class="brand" href="#">dartlang test</a>
            </div>
        </div>
    </div>
    
    <div class="container-fluid">
        <div class="row-fluid" >
            <div class="span4">
                <textarea class="input-xxlarge" rows="23" id="remarkText">
        ___|二ニー-、、;:;:;:;:;:;:;:;:;:;:;:;:;:;:;:;:;:;:|;::;:;:;:;:;:;:;:;:;:;:;:;:l
        /rヽ三三三三三─‐-- 、;:;:;:;:;:;:;:|;:;:;:;:;:;:;:;:;:;:;:;:;:;l
        ',i ,-三三三三三、   _,.ニ、ー-、!;: -‐二 ̄彡′
        ',、、ヾ三三'" ̄ ̄   `ー‐"    ヾ-'"  .〉′
        ヽ ヽヾ三,'    :::..,. -‐- 、     _,,..-‐、、,'
         `ー',ミミ     ::.弋ラ''ー、   i'"ィ'之フ l
         /:l lミミ     ::::.. 二フ´   l ヽ、.ノ ,'     
      ,.-‐フ:::::| |,ミ             l      /       
     /r‐'":::::::::| |ヾ        /__.   l    /      
 _,. -‐"i .|::::::::::::::::::',.',. \        ⌒ヽ、,ノ   /ヽ,_             
"    l ヽ:::::::::::::::::ヽヽ. \   _,_,.、〃  /l |    ___,. -、
     ',\\:::::::::::::::ヽ\  \  、. ̄⌒" ̄/:::::| |    ( ヽ-ゝ _i,.>-t--、
     \\\;::::::::::::\\  `、.__  ̄´ ̄/::::::::::l |    `''''フく _,. -ゝ┴-r-、
       ヽ \`ー-、::::::ヽ ヽ    ̄フフ::::::::::::::ノ ./   ,.-''"´ / ̄,./´ ゝ_'ヲ
          `ー-二'‐┴┴、__/‐'‐´二ー'".ノ   / _,. く  / ゝ_/ ̄|
               ̄`ー─--─‐''" ̄      / にニ'/,.、-t‐┴―'''''ヽ
                              /  /  .(_ヽ-'__,.⊥--t-⊥,,_
                              /  /  /   ̄   )  ノ__'-ノ
                             /      /    ゝニ--‐、‐   |
                            /           /‐<_   ヽ  |ヽ </textarea>

                <!-- setting panel -->
                <div class="setting">
                    <ul>
                        <li>
                            <label>Display speed</label>
                            <input type="range"  min="0" max="99" value="50" step="1" id="displaySpeed">
                        </li>
                    </ul>
                    <button class="btn-primary" id="postRemark" type="button">Post</button>
                </div>
            </div>

            <div class="span8 offset4">
                <div id="stage">
                </div>
            </div>
        </div>
    </div>
    <!-- workaround for SVG animation bug http://code.google.com/p/dart/issues/detail?id=2856 -->
    <script>navigator.webkitStartDart()</script>
</body>
</html>

svgtest.dart

mainにあたる部分。ここでは別のファイルに定義されているクラスを生成して、あとはボタンのハンドラに表示処理をつなげている。

#import("dart:html");
#import("RemarkDisplayer.dart");
#import("SVGRemarkDisplayer.dart");
#import("Unit.dart");

void main() {
    final int MAX_NUMBER_OF_REMARKS = 10;
    final int MAX_SPEED = 100;

    var displayer = new SVGRemarkDisplayer();
    displayer.initialize("#stage", MAX_NUMBER_OF_REMARKS);

    var postButton = document.query("#postRemark");
    InputElement speed = document.query("#displaySpeed");
    TextAreaElement textNode = document.query("#remarkText");
    postButton.on.click.add((Event e) {
            var num = speed.valueAsNumber;
            var duration = (MAX_SPEED - num.toInt()) * 100;
            var param = new DisplayParameter(textNode.value, duration, Unit.Millisecond);
            displayer.display(param);
    });
}

SVGRemarkDisplayer.dart

SVGでの表示処理を行うクラス。initializeで各文字列の親にあたるg要素を生成しておいて、実際に表示を行うdisplayでは渡された文字列をtspanで複数行に分解して、アニメーションをくっつけて表示している。アニメーション自体は左から右に要素を移動させる単純なもの。スライダーによって指定された秒数でアニメーションの速度を調整することができる。

#library("SVGRemarkDisplayer");
#import("dart:html");
#import("RemarkDisplayer.dart");

/**
 * Class that displays remarks via SVG
 */
class SVGRemarkDisplayer implements RemarkDisplayer {
    SVGRemarkDisplayer() {
        _remarkList = new List<SVGElement>();
        _currentRemark = 0;
        _numberOfRemarks = 0;
    }

    /**
     * Create remark nodes under the tag with the given ID
     */
    void initialize(String stageID, int numberOfRemarks) {
        _numberOfRemarks = numberOfRemarks;
        var stage = document.query(stageID);

        var svg = new SVGSVGElement();
        for (int i=0; i<numberOfRemarks; i++) {
            SVGGElement g = new SVGElement.svg("<g></g>");
            _remarkList.add(g);
            svg.nodes.add(g);
        }

       stage.nodes.add(svg);
       _root = svg;
    }

    /**
     * Display given remark at the current node
     */
    void display(DisplayParameter parameter) {
        var node = _remarkList[_currentRemark];

        // delete any nodes we already have
        node.nodes.clear();

        // convert text to svg
        var lines = parameter.remark.split("\n");
        SVGTextElement text = new SVGElement.svg("<text font-family='IPA モナーPゴシック' y='300'></text>");
        for (int i=0; i<lines.length; i++) {
            var line = lines[i];
            SVGTSpanElement span = new SVGElement.svg("<tspan x='0' dy='15'>${line}</tspan>");
            text.nodes.add(span);
        }
        
        node.nodes.add(text);
        var duration = "${parameter.duration}${parameter.durationUnit.toString()}";
        SVGAnimationElement animation
            = new SVGElement.svg("<animateTransform attributeName='transform' type='translate' from='0' to='1300' dur='${duration}' fill='freeze' begin='indefinite' />");
        node.nodes.add(animation);
        animation.beginElement();

        // proceed to next remark
        _currentRemark++;
        if (_currentRemark >= _numberOfRemarks) {
            _currentRemark = 0;
        }
    }

    int _numberOfRemarks;
    List<SVGElement> _remarkList;
    int _currentRemark;
    SVGSVGElement _root;
}

RemarkDisplayer.dart

文字列の表示をつかさどるクラスのインタフェース定義。CSS3を使ってアニメーションするクラスの方(今回は未使用)もおなじインタフェースを実装している。

#library("RemarkDisplayer");
#import("dart:html");
#import("Unit.dart");

/**
 * Parameter for displaying
 */
class DisplayParameter {
    DisplayParameter(this.remark, this.duration, this.durationUnit);
    String remark;
    int duration;
    Unit durationUnit;
}

/**
 * Class that manages remark display
 */
interface RemarkDisplayer {
    /**
     * Display given remark
     */
    void display(DisplayParameter param);
}

Unit.dart

表示単位を隠蔽するためのクラス。本当はenumを使用したいものの、現状のdartにはenumが無いためconstつきコンストラクタで代用している。

#library("Unit");

/**
  * Unit for animation
  */
class Unit {
    const Unit(int id) : _id = id;

    String toString() {
        switch (_id)
        {
        case PixelID:
            return "px";
        case MillisecID:
            return "ms";
        default:
            return "px";
        }
    }

    final int _id;

    static final int PixelID = 0;
    static final int MillisecID = 100;
    static final Pixel = const Unit(PixelID);
    static final Millisecond = const Unit(MillisecID);
}

結果

PostをクリックするとSVGアニメーションが左から右へ流れる。またスライダーを左に寄せるとゆっくり、右に寄せると速いアニメーションで表示することができる。

2012年2月21日火曜日

Playing with Dartium part 2

ひき続きDartiumでお遊び。今回はIsolateを試してみた。が、結論から言うと目論みははずれてうまくいなかったです。

Isolate

Dartはつねにシングルスレッドで実行される(仕様書にも"Dart code is always single threaded."て書いてある)んだけど、何らかの処理を並行して実行したい場合というのが出てくる。他の言語だったらスレッドなりの出番なんだけど、dartではIsolateという仕組みを使うみたい。

Isolate自体はスレッドのようなものだと考えれば良くて(実際にスレッドをつくるかどうかはIsolateの設定次第)、使いかたはIsolateクラスをextendしてmain関数を定義するだけ。まあその辺の作法の詳細はドキュメントかサンプルを参照。

RemarkDisplayerIsolate

ということで前回つくったRemarkDisplayerをIsolate化して使おうと思ったんだけど、その過程でちょっと予想外なエラーにぶちあったった。Dartiumごとクラッシュしたのでログだけ載せる。

Unhandled exception:
DOM access is not enabled in this isolate
 0. Function: 'Utils.window' url: '/mnt/data/b/build/slave/dartium-lucid64-inc/build/src/dart/client/dom/src/native_DOMImplementation.dart' line:20 col:3
 1. Function: '::get:window' url: '/mnt/data/b/build/slave/dartium-lucid64-inc/build/src/dart/client/dom/src/native_GlobalProperties.dart' line:6 col:36
 ...

IsolateからはDOMに触れないって話。エラーメッセージ読むかぎりだと設定で有効化できそうな雰囲気もあるけど、予想ではたぶんできない。C#でGUIを作るときもそうだけど、バックグラウンドのスレッドからは直接UI要素に触らせてくれない場合が多い。

感想

まあとりあえずIsolateの使いかたそのものは何となくわかったのでよしとする。でもIsolate自体はあんまり使いやすくないな…わかりづらい。GoのChannelみたいにPortが双方向だともっとスッキリしてわかりやすいと思うんだけども。

コード

途中で例外飛ぶけど、失敗例としてコードを掲載しておく。

  • RemarkDisplayer.dart
    #library("RemarkDisplayer");
    
    #import("dart:html");
    
    class MessageTypes {
        static final int ERROR = -1;
        static final int OK = 0;
        static final int SETUP = 1;
        static final int INIT = 2;
        static final int DISPLAY = 3;
    }
    
    class DisplayerState {
        static final int SETUP = 1;
        static final int INITIALIZED = 2;
        static final int DISPLAYING = 3;
    }
    
    /**
     * Class that attempted to manipulate DOM in an Isolate.
     */
    class RemarkDisplayerIsolate extends Isolate {
        RemarkDisplayerIsolate() {}
    
        void main() {
            port.receive((message, SendPort replyTo) {
                    dispatch(message, replyTo, port.toSendPort());
            });
        }
    
        void dispatch(var message, SendPort replyTo, SendPort myPort) {
            int action = message['action'];
            var arg = message['arg'];
            switch(action) {
            case MessageTypes.SETUP:
                _displayer = new RemarkDisplayer(arg);
                replyTo.send(DisplayerState.SETUP, myPort);
                break;
            case MessageTypes.INIT:
                _displayer.initialize(arg); // EXCEPTION FIRED HERE
                replyTo.send(DisplayerState.INITIALIZED, myPort);
                break;
            case MessageTypes.DISPLAY:
                _displayer.display(arg);
                replyTo.send(DisplayerState.DISPLAYING, myPort);
                break;
            }
        }
    
        RemarkDisplayer _displayer;
    }
    
    /**
     * Class that manages remark display
     */
    class RemarkDisplayer {
        RemarkDisplayer(int numberOfRemarks) {
            _numberOfRemarks = numberOfRemarks;
            _remarkList = new List<Element>();
            _currentRemark = 0;
        }
        
        /**
         * Create remark nodes under the tag with the given ID
         */
        void initialize(String stageID) {
            var stage = document.query(stageID);
            for (int i=0; i<_numberOfRemarks; i++) {
                var tag = '<pre class="remark" id="remark${i}" draggable="true"/>';
                var elem = new Element.html(tag);
                stage.nodes.add(elem);
                _remarkList.add(elem);
            }
        }
        
        /**
         * Display given remark at the current node
         */
        void display(String remark) {
            var node = _remarkList[_currentRemark];
            var durationMS= 5000;
            node.innerHTML = remark;
            node.style.visibility = "visible";
            node.style.animationName = "fade, hslide";
            node.style.animationDuration = "${durationMS}ms";
            node.style.animationTimingFunction = "linear";
            node.style.animationFillMode = "forwards";
            
            // Replace node with a clone to restart animation
            var newNode = node.clone(true);
            node.replaceWith(newNode);
            _remarkList[_currentRemark] = newNode;
            
            // proceed to next remark
            _currentRemark++;
            if (_currentRemark >= _numberOfRemarks) {
                _currentRemark = 0;
            }
        }
        
        int _numberOfRemarks;
        get numberOfRemarks() => _numberOfRemarks;
        
        List<Element> _remarkList;
        int _currentRemark;
    }
    
  • main.dart
    #library('displayer');
    
    #import("dart:html");
    #import("RemarkDisplayer.dart");
    
    void dispatch(var message, SendPort replyTo, SendPort myPort) {
        switch(message) {
        case DisplayerState.SETUP:
            var msg = { 
                "action" : MessageTypes.INIT,
                "arg" : "#stage"
            };
            replyTo.send(msg, myPort);
            break;
        case DisplayerState.INITIALIZED:
            var msg = { 
                "action" : MessageTypes.DISPLAY,
                "arg" : "adsfasfas"
            };
            replyTo.send(msg, myPort);
            break;
        case DisplayerState.DISPLAYING:
            replyTo.close();
            break;
        }
    }
    
    void main() {
        final int MAX_NUMBER_OF_REMARKS = 10;
        final receivePort = new ReceivePort();
        receivePort.receive((var message, SendPort sendPort) {
                print("received ${message}");
                dispatch(message, sendPort, receivePort.toSendPort());
        });
    
        new RemarkDisplayerIsolate().spawn().then((SendPort sendPort) {
                var msg = { 
                    "action" : MessageTypes.SETUP,
                    "arg" : MAX_NUMBER_OF_REMARKS
                };
                sendPort.send(msg, receivePort.toSendPort());
         });
    }
    

2012年2月19日日曜日

Playing with Dartium

前にjavascriptで書いてた処理をdartに移植してDartiumで動かしてみた。やらんとしていたのはニコニコもどきだけど、書いてる途中にjavascriptに嫌気がさして投げたので色々と中途半端。とりあえず処理の内容は以下。

  1. 特定のid(今回だと"stage")を持つノードにいくつかノードを追加する。
  2. ボタンがクリックされるたびにTextArea内の内容を(最初に追加された)ノードにわりあてて、CSSアニメーションをくっつけて表示する。

完成図

Postをクリックするたびに麻呂がフェードアウトしながら右にスライドしていきます。スバラシイ。

html + dart

dartのコードはclassの使い方を試す意図もあったので、あえてclassにして書いてる。その過程で学んだことを数点書くと以下の通り。

  • Dart Style Guideには従っとけ。
  • 変数名の頭に"_"をつけるとprivateな変数になる。つけないと自動的にpublicになる。
  • intの変数を文字列表現に変換したいような場合は"$value"や"${value}"という書きかた(string interpolation syntax)をすると自動的に文字列変換してくれる。こういう仕様になった事情はDartの言語仕様を見ると書いてあって、抜粋すると以下の通り。

    The string interpolation syntax is designed to be familiar and easy to use, if somewhat awkward to parse. The intent is to encourage its use over alternatives such as s1 + s2. In a dynamically typed language, the use of the + operator requires dynamic dispatch. In contrast, in the case of string interpolation we can statically determine that the string concatenation operation is required, making the operation more efficient. Even more importantly, it helps the system to determine if other uses of + are numeric, helping the implementation speed up those operations. This is especially crucial for a language that must be efficiently compiled into Javascript.

    要するに対象の変数が文字列なのか数字なのかがより明確にできるから、周辺の処理を高速化しやすくなる、という話みたい。

<!doctype html>
<head>
    <meta charset="utf-8">
    <title>dartlang test</title>
    <link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="./css/client.css" />
</head>
<body>
    <script type="application/dart" >
        #import("dart:html");
        /**
          * Class that manages remark display
          */
        class RemarkDisplayer {
            RemarkDisplayer(int numberOfRemarks) {
                _numberOfRemarks = numberOfRemarks;
                _remarkList = new List<Element>();
                _currentRemark = 0;
            }
            
            /**
             * Create remark nodes under the tag with the given ID
             */
            void initialize(String stageID) {
                var stage = document.query(stageID);
                for (int i=0; i<_numberOfRemarks; i++) {
                    var tag = '<pre class="remark" id="remark${i}" draggable="true"/>';
                    var elem = new Element.html(tag);
                    stage.nodes.add(elem);
                    _remarkList.add(elem);
                }
            }

            /**
              * Display given remark at the current node
              */
            void display(String remark) {
                var node = _remarkList[_currentRemark];
                var durationMS= 5000;
                node.innerHTML = remark;
                node.style.visibility = "visible";
                node.style.animationName = "fade, hslide";
                node.style.animationDuration = "${durationMS}ms";
                node.style.animationTimingFunction = "linear";
                node.style.animationFillMode = "forwards";

                // Replace node with a clone to restart animation
                var newNode = node.clone(true);
                node.replaceWith(newNode);
                _remarkList[_currentRemark] = newNode;

                // proceed to next remark
                _currentRemark++;
                if (_currentRemark >= _numberOfRemarks) {
                    _currentRemark = 0;
                }
            }
            
            int _numberOfRemarks;
            get numberOfRemarks() => _numberOfRemarks;

            List<Element> _remarkList;
            int _currentRemark;
        }

        void main() {
            final int MAX_NUMBER_OF_REMARKS = 10;
            var displayer = new RemarkDisplayer(MAX_NUMBER_OF_REMARKS);
            displayer.initialize("#stage");
            var button = document.query("#postRemark");
            TextAreaElement textNode = document.query("#remarkText");
            button.on.click.add((Event e) {
                    displayer.display(textNode.value);
            });
         }
    </script>
    <div class="topbar">
        <div class="fill">
            <div class="container">
                <a class="brand" href="#">dartlang test</a>
            </div>
        </div>
    </div>
    
    <div class="container">
        <div class="content" >
            <form action="">
                <textarea class="xxlarge" rows="23" id="remarkText">
        ___|二ニー-、、;:;:;:;:;:;:;:;:;:;:;:;:;:;:;:;:;:;:|;::;:;:;:;:;:;:;:;:;:;:;:;:l
        /rヽ三三三三三─‐-- 、;:;:;:;:;:;:;:|;:;:;:;:;:;:;:;:;:;:;:;:;:;l
        ',i ,-三三三三三、   _,.ニ、ー-、!;: -‐二 ̄彡′
        ',、、ヾ三三'" ̄ ̄   `ー‐"    ヾ-'"  .〉′
        ヽ ヽヾ三,'    :::..,. -‐- 、     _,,..-‐、、,'
         `ー',ミミ     ::.弋ラ''ー、   i'"ィ'之フ l
         /:l lミミ     ::::.. 二フ´   l ヽ、.ノ ,'     
      ,.-‐フ:::::| |,ミ             l      /       
     /r‐'":::::::::| |ヾ        /__.   l    /      
 _,. -‐"i .|::::::::::::::::::',.',. \        ⌒ヽ、,ノ   /ヽ,_             
"    l ヽ:::::::::::::::::ヽヽ. \   _,_,.、〃  /l |    ___,. -、
     ',\\:::::::::::::::ヽ\  \  、. ̄⌒" ̄/:::::| |    ( ヽ-ゝ _i,.>-t--、
     \\\;::::::::::::\\  `、.__  ̄´ ̄/::::::::::l |    `''''フく _,. -ゝ┴-r-、
       ヽ \`ー-、::::::ヽ ヽ    ̄フフ::::::::::::::ノ ./   ,.-''"´ / ̄,./´ ゝ_'ヲ
          `ー-二'‐┴┴、__/‐'‐´二ー'".ノ   / _,. く  / ゝ_/ ̄|
               ̄`ー─--─‐''" ̄      / にニ'/,.、-t‐┴―'''''ヽ
                              /  /  .(_ヽ-'__,.⊥--t-⊥,,_
                              /  /  /   ̄   )  ノ__'-ノ
                             /      /    ゝニ--‐、‐   |
                            /           /‐<_   ヽ  |ヽ </textarea>
                <button class="btn primary" id="postRemark" type="button">Post</button>
            </form>
        </div>

        <div id="stage"></div>
    </div>
</body>
</html>

css

bootstrapなcssを除き、自分で新たに定義したcssも掲載する。

html, body {
    background-color: #eee;
}
body {
    padding-top: 40px; /* 40px to make the container go all the way to the bottom of the topbar */
}
.container > footer p {
    text-align: center; /* center align it with the container */
}

.remark {
    background : rgba(0,0,0,0); /* transparent background*/
    position: absolute;
    width: auto;
    height: auto;
    font-family: "IPA モナーPゴシック", monospace;
}

/* Fading animation */
@-webkit-keyframes fade {
  0%   { opacity: 1; }
  100% { opacity: 0; }
}

/* vertical scroll animation */
@-webkit-keyframes vslide {
  0%   { -webkit-transform: translateY(0px); }
  100% { -webkit-transform: translateY(100px); }
}

/* horizontal scroll animation */
@-webkit-keyframes hslide {
  0%   { -webkit-transform: translateX(0px); }
  100% { -webkit-transform: translateX(1000px); }
}

感想

classに変数やら処理をまとめて隠蔽できるのは気持ちいいっすね。

2012年2月18日土曜日

Trying Dartium on Ubuntu Linux 11.10

Dartium(DartのVMが搭載されたChromium)のバイナリが公開されたので、早速試してみた。環境は32bitのUbuntu Linux 11.10で、unameは↓ね。

検証環境

$ uname -a
Linux masato-xubuntu 3.0.0-16-generic-pae #28-Ubuntu SMP Fri Jan 27 19:24:01 UTC 2012 i686 i686 i386 GNU/Linux

環境構築

バイナリを用意してくれたおかげで非常に簡単。

  1. 適切なバイナリを落としてくる。今回はこれを使用。dartium-lucid64.zipとかいう名前だから一瞬64bitじゃないとダメかと思ったけど、32bit OSでも普通に動いてる
  2. zip解凍してDartium起動する。zip解凍すると色々でてくるけど、重要なのはchromeだけ。ファイラーからだとchromeが共有ライブラリに見えて実行できなかったけど、普通にコマンドラインから起動すれば問題なかった。
  3. chromiumの情報を確認する。"chrome://version/"というURLを打つと色々情報が見れる。そこにDartVMという項目が出てればちゃんとDartiumが動いてるはず。自分が落としてきたのは下の表示だった。

コード書く

こことかこことかこの辺を参考にしながら書いてみた。コツがつかめれば実際のリファレンスの方をみるといいかも。特にdart:htmlのElementは良く読むべし。

<!doctype html>
<head>
    <meta charset="utf-8">
    <title>dartlang test</title>

    <link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="./css/client.css" />
</head>
<body>
    <script type="application/dart">
    #import("dart:html");
    void main() {
        var msg = "Testing dart!";
        window.alert(msg);
        print(msg);
        Element btn = document.query('#button');
        btn.on.click.add((Event e) {
            Element stage = document.query('#stage');
            stage.innerHTML = "OMGOMGOMGOMG";
        });
    }
    </script>
    <div class="topbar">
        <div class="fill">
            <div class="container">
                <a class="brand" href="#">dartlang test</a>
            </div>
        </div>
    </div>
    
    <div class="container">
        <div id="stage">AAAAAAAAAAAAAAAAAAAA</div>
        <div id="button">Click ME!</div>
    </div>
</body>
</html>

やってることはわりと単純。

  1. window.alertでアラートウィンドウにメッセージを出力する
  2. printでデバッグメッセージを出力する
  3. buttonというidを持つ要素のクリックハンドラでstageというidを持つ要素の中身を書きかえる

コードを埋めこんだhtmlができたら、あとは普通にDartiumで表示する。もし構文に何らかのエラーがあった場合はデベロッパーツールのConsoleに表示されるから見るといい。画像は上がクリック前、下がクリック後。

型チェック

ドキュメントにも書いてあるけど、Dartiumの実行時に環境変数を設定してやるとDartの型チェック機能を有効化できる

$ DART_FLAGS='--enable_type_checks --enable_asserts' ../lib/dartium-lucid64-inc-4350.4350/chrome &

この状態で意図的に型エラーが出るソースに書きかえた(Event eのところをint eにした)ところ、ちゃんとエラーが検出された。

感想

  • バイナリのおかげでかなり簡単にDartが試せる。
  • Consoleにエラーが出るからデバッグはまあまあやりやすい。まあこれはjavascriptでも一緒だけど。
  • 型チェックは常にONでもいいかも。

2012年2月11日土曜日

Trying "dart:io" with dart

ブラウザ側の処理を書くためちょっと試しにjavascriptを書こうとしてたものの、そのあまりに気持ちわるい言語仕様に挫折してしまった。Coffee Scriptも試したけどやっぱり文法が受けつけなかったので、早々にdartを試してみることにした。

dart:io

dartはブラウザの中だけじゃなく普通のスクリプト言語的にも実行できるようなので、ちょっと前に追加されたというioライブラリでちょろっと書いてみた。環境の構築方法はこの辺を参照。APIリファレンスを見るかぎり〜Syncていう同期的に実行する関数と非同期的に実行する関数の二種類があるみたい。Sync無しの関数がデフォルトっぽいので、ひとまず全て非同期で書いてる。

#import('dart:io');

void onOpen(RandomAccessFile opened) {
    opened.closeHandler = () => print("Closed stream");
    opened.errorHandler = (err) => print(err);
    opened.noPendingWriteHandler = () => opened.close();
    print("Writing to stream");
    opened.writeString("aardvark\n");
}

void main() {
    var name = "./aardvark";
    var f = new File(name);
    print("Attempting to write "+f.name);
    f.existsHandler = (bool b) {
        if (b) {
            print(f.name+" already exists!");
        } else {
            print(f.name + " doesn't exist...");
            f.openHandler = onOpen;
            f.open(FileMode.WRITE);
        }
    };
    f.exists();
}

"=>"記号で関数を定義するのはC#で慣れてるからどってことない。それより全て非同期で書こうとするとハンドラーだらけで変な感じ。

実行結果

$ dart --enable_type_checks test.dart
Attempting to write ./aardvark
./aardvark doesn't exist...
Writing to stream
Closed stream
$ dart --enable_type_checks test.dart
Attempting to write ./aardvark
./aardvark already exists!
$ cat aardvark 
aardvark
$ 

実行結果は期待通り。ついでに"--enable_type_checks"オプション型チェックを試してみた(existsHandlerの引数をbool bじゃなくてint bにしてみた)ところ、下のような結果になった。

$ dart --enable_type_checks test.dart
Attempting to write ./aardvark
Unhandled exception:
'dart:io': Failed type check: line 1888 pos 31: type '(int) => Dynamic' is not assignable to type '(bool) => void' of 'handler'.
 0. Function: '_File@14117cc4.set:existsHandler' url: 'dart:io' line:1888 col:31
 1. Function: '::main' url: '/home/masato/dart/test/test.dart' line:15 col:21

"--enable_type_checks"無しで実行すると何も言わないので、一応ちゃんと動いてるみたい。

まとめ

javascriptよりはるかにまっとうな言語なので早く普及してください。ちなみにsynonym.dartlang.orgにはjavascriptとdartを比較した色々な例が出てて、javascriptがいかに気持ち悪い言語かが良くわかる。

2011年12月10日土曜日

Using Kensington Expert Mouse with Ubuntu 11.10

自宅ではKensington Expert Mouseを使ってるんだけど、普段左手でマウスを使うようにしてるのでボタンのマップをいじる必要がある。それで結構前に色々調べた結果、以下のコマンドをやれば理想的なボタン配置(左上:右クリック、右上:右クリック、左下:ミドルクリック、右下:左クリック、反時計回りスクロール:下降、時計回りスクロール:上昇)になることまではわかった。

/usr/bin/xinput set-button-map "Kensington      Kensington Expert Mouse" 2 3 1 5 4 3 3 3 3 3 3 3

あとはこれを~/.xinitrcに記述して起動時に適切なボタンにマップされるところまでは良かった。

USB抜きさしすると初期化される

ただこのやり方には一つ穴があって、マウスをUSBから抜きさしすると適用したマップが初期化されてしまう、というもの。当時のUbuntuはHALを無くすとかなんとかでハードウェアまわりのソフトウェア環境がゴタゴタしてて、色々調べたけどいまいちこの問題を解消する方法がわからなかった。で、昨日久しぶりに調べてみたらあっさり解決したのでここにメモっておく。

  1. lsusbコマンドを実行して、Kensingtonマウスの項目にあたる部分をひかえておく。
    $ lsusb
    ...
    Bus 004 Device 008: ID 047d:1020 Kensington Expert Mouse Trackball
    ...
    
  2. /usr/share/X11/xorg.conf.d/90-kensington-expert.confというファイルを作り、中身を以下のように書く。 IdentifierとMatchUSBIDはlsusbで出力されたものを使う。
    Section "InputClass"
            Identifier      "Kensington Expert Mouse Trackball"
            MatchUSBID      "047d:1020"
            Option "ButtonMapping" "2 3 1 5 4 3 3 3 3 3 3 3"
    EndSection
    
  3. 一旦ログアウトして、再度ログインする。

以上おしまい。もっと早く調べておけば良かった。