May 24, 2013

Chris Strom

Minor Refactoring under Test in Dart

‹prev | My Chain | next›

Today, I would like to start thinking about how to consolidate some of my Dart code in the ICE Code Editor. I think that it is a bit early to start breaking the sub-menus and dialogs out into Dart classes. So instead, I am going to scavenge the codebase for things that are asking to be removed or consolidated.

One of the first things that asks to come out are styles. I love using method cascades for CSS styles in Dart:
  _openNewProjectDialog() {
var dialog = new Element.html(
'''
<div class=ice-dialog>
<label>Name:<input type="text" size="30"></label>
<button>Save</button>
</div>
'''
);

dialog.style
..position = 'absolute'
..margin = '2px'
..right = '20px'
..top = '45px'
..zIndex = '999';

// ...
}
As much as I like a good method cascade, I am setting the same style for multiple dialogs. In fact, I am setting the same style for sub-menus as well. So, reluctantly, I pull that out into vanilla CSS:
.ice-menu, .ice-dialog {
/* ... */
position: absolute;
margin: 2px;
right: 20px;
top: 45px;
z-index: 999;
}
Sometimes there is no substitution for a low-tech solution.

I clean out a few other minor things and then come across:
  _hideMenu() {
if (query('.ice-menu') == null) return;
query('.ice-menu').remove();
// queryAll('.ice-menu').forEach((e)=> e.remove());
}
I really dislike that conditional. It seems like that queryAll() ought to be equivalent, if not a better solution. Instead of finding one .ice-menu element, it will find them all and remove each. If there are no matching elements, which is what the current conditional is guarding, then the forEach() should be a no-op.

But I commented that out for a reason. Specifically, if I replace the current code with the queryAll() version, I get test failures:
FAIL: project menu lists project names
Expected: List of elements contains match 'My New Project'
but: Element list content was <[☰X, ☰, X, , , , , , , , , , , , , X, , , ]>.
Interestingly, I think that I was relying on coincidence to make the “list project names” feature work. In particular, the way that I opened the project list sub-menu was opening the menu first, then closing the main menu:
  _projectsMenuItem() {
return new Element.html('<li>Projects</li>')
..onClick.listen((e)=> _openProjectsMenu())
..onClick.listen((e)=> _hideMenu());
}
This, and a bunch of other tests, pass if I hide all menus before opening the project menu:
  _projectsMenuItem() {
return new Element.html('<li>Projects</li>')
..onClick.listen((e)=> _hideMenu())
..onClick.listen((e)=> _openProjectsMenu());
}
In the end, the previous conditional-then-remove-the-first-element-in-the-DOM approach was less than robust. So this refactoring / cleanup has helped improve the strength of the codebase. Hopefully it has cleaned enough cruft so that I have a better handle on how to better approach those sub-menus and dialogs. I will get started on that tomorrow.


Day #760

by Chris Strom (noreply@blogger.com) at May 24, 2013 03:59 AM

May 23, 2013

Dartwatch

Win-win for developers and users: Dart @ Google I/O 2013

Win-win for developers and users: Dart @ Google I/O 2013

Google I/O 2013 is now over, and Dart had a pretty good showing, with three Dart talks and a codelab.
Performance was a big theme throughout Google I/O, especially with Chrome and Mobile in mind. Mobile apps running with a touch screen need to be more responsive than ever to create a good user experience (when you're physically touching a widget, you expect it to respond immediately to your touch), and there was lots of discussion about the target 60 fps refresh rate on mobile.

Win 1: Great performance for users.

Lars Bak and Kasper Lund's talk on VM Performance highlighted some of the problems that they face when designing a VM. They've designed VMs in the past (including Hotspot VM and Chrome's V8), and although V8 made great leaps initially (an initial benchmark in Firefox ran at "100" when V8 was being invented. Now, the same benchmark runs at around "~16,000"), the rate of improvement is slow. In order to get the next "leap" in performance, they need to address some of the problems with the actual language (JavaScript). An example given in their talk is that V8 optimizes based upon known executions of a block of code up to that point. If, however, that code changes (such as inserting a new property into the prototype), the optimizer has to back-out the optimizations until it's ready to optimize again. All this has an overhead.

By designing a language that is designed to make it easy to optimize a VM for, Dart's is already ahead of V8 in terms of performance (after only about 2 years of development, compared to 7 years of V8).
enter image description here
Image courtesy Stephen Shankland / cnet
There are (currently broken) instructions on the Dart wiki about building a VM on ARM, and it has to be thought that a long-term goal must be to get the Dart VM (integrated with chrome?) running on Android. This has twin benefits for users: better application performance, and longer battery life (as there is less work done).

By making use of advance chip technologies, such as SIMD (Single Instruction, Multiple Data) the Dart VM is able to leverage the maximum power available. A great demo of this was the 3d demo of monsters - only around 35 were visible with SIMD turned off in the VM (at 60fps), but when SIMD turned on, 60fps was maintained with ~120 monsters.
enter image description here
Image courtesy Stephen Shankland / cnet

Win 2: Great experience for developers.

I also spent some time on the Dart stand in the sandbox talking to web developers about Dart, and went to the Dart codelab. As a developer, it's awesome to be able to leverage Web Components combined with Dart's well known language features (libraries, functional, unsurprising and familiar classes, optional typing), all wrapped up with with great tools such as package management, IDE, Debugger and type checker. Developers that I was talking to at the Dart stand seemed suitably impressed with what Dart currently had to offer (especially as many hadn't looked at it since its initial release).
"It can't really be this easy?"
In the Codelab, which used Web Components to build a multi-file, offline document editor, the other developers sat around me had positive views, with one even saying "It can't really be this easy? - It almost feels like cheating." - Yes, Dart really is productive. Give the codelab a try and see for yourself.

That quote summed up the current state of Dart for me, when I go around doing talks on Dart, and showing Dart to fellow developers, they are often surprised to see the great developer story and productivity gains. When combined with the improved performance of apps with the Dart VM, they start to see how it can help to move web applications on to the next level.

On JavaScript future.

Because Dart also targets JavaScript, any advances made in JavaScript to allow better JavaScript optimizations will also benefit developers and users. Developers still get the same great Dart development story, and users will benefit from increased performance of their JavaScript version of the Dart app. Of course, browsers that contain the Dart VM will likely to continue to remain faster running native Dart than the equivalent JavaScript.

The Sessions from I/O

Images from cnet article "Dart will rescue browsers from JavaScript"

by Chris Buckett (noreply@blogger.com) at May 23, 2013 03:52 PM

Chris Strom

Driving Dart Integration Tests

‹prev | My Chain | next›

The crazy thing about driving things with tests is that stuff gets done. I have been having a good old time playing around with the test suite in the Dart version of the ICE Code Editor. I spent so much time fiddling with the tests that I barely noticed the progress with functionality. Mostly thanks to #pairwithme sessions, the functionality of the ICE Code Editor is really coming along.

Tonight, I take a step back to see how it is working with the new test helpers that I have written over the past two nights when driving new functionality. Thanks to last night's #pairwithme session with Santiago Arias, ICE now lists the currently saved projects in the Projects menu. Tonight I would like to be able to click on old ones to make them active.

I start with a long UI workflow test:
    test("click names to switch between projects", (){
helpers.click('button', text: '☰');
helpers.click('li', text: 'New');

query('input').value = 'Project #1';
helpers.click('button', text: 'Save');

editor.content = 'Code #1';
helpers.click('button', text: '☰');
helpers.click('li', text: 'Save');

helpers.click('button', text: '☰');
helpers.click('li', text: 'New');

query('input').value = 'Project #2';
helpers.click('button', text: 'Save');

editor.content = 'Code #2';
helpers.click('button', text: '☰');
helpers.click('li', text: 'Save');

helpers.click('button', text: '☰');
helpers.click('li', text: 'Projects');
helpers.click('li', text: 'Project #1');

expect(
editor.content,
equals('Code #1')
);
});
This fully exercises the full screen ICE menus by clicking the menu button (the UTF-8 ☰ symbol), then creating a new project, setting the content and saving the project. I do that twice, at which point the content for the second project is still active. I then open the Projects menu and select the first project from the list. The expectation is that the editor content will have changed to “Code #1” the content of the first project.

It is so cool that, thanks to Dart's testing facilities and some simple helpers, the test is so expressive and yet completely functional. The first time I run that test, I get a failure. The exact failure that I had hoped to get to drive this feature:
FAIL: project menu click names to switch between projects
Expected: 'Code #1'
but: was 'Code #2'.
How awesome is that?

Then again, maybe my UI testing expectations are just too low. Perhaps this is really how it ought to be. Regardless, this is reality in the world of Dart and I embrace it by writing the code that implements this. With that bit of smugness fully internalized, I run into all sorts of problems.

The implementation is not too hard:
    _store.forEach((title, data) {
var project = new Element.html('<li>${title}</li>')
..onClick.listen((e)=> _openProject(title))
..onClick.listen((e)=> _hideMenu());

menu.query('ul').children.add(project);
});
For each item in the data store, I create a menu item for the Projects menu. Each project menu item gets a couple of handlers to open the project and hide the menu. The underlying Store class could support opening a project better, but that is not really the problem.

The problem is that, after saving items by clicking the “Save” option from the main menu, I was not closing the main menu. It would stay up causing subsequent tests to fail because the wrong menus were now active.

I could have written this test such that the localStorage store was initialized with projects in place. This would have avoided the save-not-closing-the-menu issue (though I would not have found the bug otherwise) and the subsequent implementation would likely end up exactly the same. But there is something exciting about a test that exercises the full stack in milliseconds. If I had other tests that covered similar ground, I might manually initialize the localStorage, but I really prefer to keep this around.

It turns out to be quite the effort to keep it around. The test continues to fail and is compounded with a problem running these tests solo due to js-interop concerns. Thankfully, tonight's #pairwithme pair, Daniel Gempesaw, helps me through it.

We drive the problem away with another test:
    test("clicking save closes the main menu", (){
helpers.click('button', text: '☰');
helpers.click('li', text: 'Save');

expect(queryAll('li').map((e)=> e.text).toList(), isEmpty);
});
All that is needed to make that pass is a second on-click listener for the “Save” menu item:
  Element get _saveMenuItem {
return new Element.html('<li>Save</li>')
..onClick.listen((e)=> _save())
..onClick.listen((e)=> _hideMenu());
}
With that, not one, but two tests are passing. More importantly, it is now possible to switch between projects in the Dart version of the ICE Code Editor. Yay!


Day #759

by Chris Strom (noreply@blogger.com) at May 23, 2013 03:59 AM

May 22, 2013

Chris Strom

Custom Test Matchers in Dart

‹prev | My Chain | next›

After last night, I have helpered my way to a nice looking Dart test:
    test("clicking the project menu item opens the project dialog", (){
helpers.click('button', text: '☰');
helpers.click('li', text: 'Projects');

expect(
queryAll('div').map((e)=> e.text).toList(),
contains(matches('Saved Projects'))
);
});
That's downright pretty, except… that expect() is, let's face it, plain yucky.

The thing that I am testing is kinda OK. It is a map of the text contents of <div> elements. I could do without the map(), but it's not horrible. The toList() is bothersome. It can be omitted, but it is useful to have around. For instance, if I cause an intentional failure by naming the menu "Saved Code" instead of "Saved Projects", I get a nice error message that gives me an idea of what went wrong:
FAIL: project menu clicking the project menu item opens the project dialog
Expected: contains match 'Saved Projects'
but: was <[☰X
Saved Code
, ☰, X, , , , , , , , , , , , , X, , , ,
Saved Code
]>.
If I omit the toList(), then the object that I am testing is an Iterable. It still passes or fails as desired, but the failure message is less nice:
FAIL: project menu clicking the project menu item opens the project dialog
Expected: contains match 'Saved Projects'
but: was <Instance of 'MappedListIterable':554001401>.
So I leave toList() as a bit of test code ugliness so that I get nicer test code output. I can live with that.

The expected value is not quite as nice. Dart provides a nice matcher for lists: contains(). So in this case I am expecting a list that contains something. That something is anything that matches the string 'Saved Projects'. It works, but it is hard to read.

But hard to read matchers are what custom matchers are for. For this expectation, I may not even need to write an entirely new matcher. Instead, I start by inheriting from CustomMatcher. These nifty little things set a description ("List of elements") and a feature name ("Element list content") in the constructor:
class ElementListMatcher extends CustomMatcher {
ElementListMatcher(matcher) :
super("List of elements", "Element list content", matcher);

featureValueOf(elements) => elements.map((e)=> e.text).toList();
}
I then pick a value to extract from the actual value. If the actual value is a list of elements, then the above extracts the text contents in List form. That is just what I had to do by hand in my test, but all of the ugliness of mapping and converting from an iterable to a list is done in the custom matcher.

I then create a top-level helper that uses this matcher to check the extracted/featured list to see if it contains a match:
elements_contain(Pattern content) =>
new ElementListMatcher(contains(matches(content)));
Those are two pretty simple helpers that let me rewrite my test entirely with helpers as:
    test("clicking the project menu item opens the project dialog", (){
helpers.click('button', text: '☰');
helpers.click('li', text: 'Projects');

expect(
queryAll('div'),
helpers.elements_contain('Saved Projects')
);
});
That is pretty all the way through: I click a button with the menu icon, I click the "Projects" menu item, then I expect one of the <div> tags to contain the text "Saved Projects". Wonderful!

And best of all it works!

If I again intentionally make my test fail, I get:
FAIL: project menu clicking the project menu item opens the project dialog
Expected: List of elements contains match 'Saved Projects'
but: Element list content was <[☰X
Saved Code
, ☰, X, , , , , , , , , , , , , X, , , ,
Saved Code
]>.
That is even more expressive than what I had when I manually extracted a list to test and the test content is easier to read. The use of the helpers prefix from last night is the only remaining noise (and I still think it worth keeping about). All in all, these test matchers are pretty powerful.


Day #758

by Chris Strom (noreply@blogger.com) at May 22, 2013 03:57 AM

Seth Ladd

Watch the video from What's New in Dart from Google I/O 2013

Google I/O was a blast, and Dart had a great time. For posterity, check out the video of my talk with co-presenter Justin Fagnani. We covered what's new across the Dartosphere, including language features, libraries, tools, and ecosystem.



Like what you see? Head on over to dartlang.org to download the SDK and check out our docs and tutorials. You can always find us in our Dartisans G+ community. Stop by and say hi!

by Seth Ladd (noreply@blogger.com) at May 22, 2013 03:41 AM

May 21, 2013

Dartlang

Dart Sessions at Google I/O 2013

Join us at Google I/O 2013 in San Francisco's Moscone Center from May 15 through 17.



This year's conference features numerous events of interest to the Dart community. You can see three Dart presentations, and take part in a Dart code lab. One of the talks, by Dart creators Lars Bak and Kasper Lund, will be streamed live. And all of the talks will be available on video.

If you are at I/O, be sure to stop by at the Dart booth in the Developer Sandbox on the 3rd floor of Moscone Center. You can ask questions of Dart team members who will be available on all three days at the booth, and also at the office hours area nearby.

Here are some details about the talks and the code lab:

Web Languages and VMs: Fast Code is Always in Fashion

Lars Bak, Kasper Lund

A fundamental necessity for innovation within web apps is fast execution speed. This talk will take a deep dive into the machine rooms of both V8 and the Dart VM and explain some of the reasons why a new execution engine is needed for taking the web platform to the next level. Please join us to hear about how programming languages impact the underlying virtual machines, complexity, on-the-fly code generation, and predictable performance.

When: May 16, 10:00AM - 11:00AM PDT Level: Intermediate Track: Chrome & Apps


Come see what's new in Dart with its comprehensive, open-source ecosystem for the modern web developer. Learn how to be more productive with a new language: future-based DOM, package manager, JS-interop, a tree-shaking compiler to JavaScript, SIMD, Web Components, a rich editor, and much more. You'll leave this talk all caught up with Dart and ready to make the web awesome

When: May 16, 12:45PM - 1:25PM PDT Level: Intermediate Track: Chrome & Apps

Dart: HTML of the Future, Today!

Sigmund Cherem, Emily Fortuna

Develop large apps in a structured language and still experience fast Edit/Reload development cycles? Indeed, the prophecy has come true. Get crazy productive with Dart's tools, smooth HTML libraries, cross-browser polyfills, and web components based framework. Come learn how you can easily and quickly develop web apps that work cross-browser on both desktop and mobile platforms. We'll show you how to build modern web apps with Web Components and dynamic data-driven views without having to wait for cumbersome compile cycles. Make a change, hit reload, and boom, it's ready for all modern browsers.

When: May 16, 3:30PM - 4:10PM PDT Level: Intermediate Track: Chrome & Apps


You paid for the whole seat but you'll only need the edge! Get hands-on experience and build declarative, modern mobile web apps with Dart and Web Components. Go from zero to magnificent using Dart's structured language, comprehensive libraries, and lightning-fast dev cycle. Learn how to use the Dart toolchain to deploy and test web apps for tablet, phone, and desktop. Yes, you can!

When: May 17, 9:00AM - 11:00AM PDT Level: Intermediate Track: Chrome & Apps

by Shailen Tuli (noreply@blogger.com) at May 21, 2013 11:29 PM

Strong Dart presence at Google I/O 2013

Google I/O 2013 was a breakout event for Dart. The conference featured three well attended Dart talks, a Dart code lab, and a crowded Dart booth.


Seth Ladd interviews Lars Bak and Kasper Lund about the state of Dart from the floor of Moscone Center. Dart is now running twice as fast as JavaScript on certain benchmarks. The language and the core libraries are stable, and Dart expects to reach 1.0 status in a few months.

Dart sessions at I/O

Google I/O 2013 featured three Dart talks (videos embedded below).

Web Languages and VMs: Fast Code is Always in Fashion

Lars Bak and Kasper Lund dove deep into the internals of V8 and the Dart VM, explaining why the new Dart VM is needed to take the web platform to the next level.




One popular part of their talk was a demo showing Dart's support for SIMD (single instruction, multiple data) processing. SIMD allows for a big performance boost. Without SIMD, their skeletal animation example supported only about 30 monsters (first image, below). With SIMD, that number increased to about 120 (second image).






Dart: HTML of the Future, Today!

Siggi Cherem and Emily Fortuna explained how Dart libraries have simplified the web building experience, and showed how cross-browser polyfills have made web components available for use today.



What's New in Dart: Your First-class Upgrade to Web Development

Justin Fagnani and Seth Ladd provided a whirlwind tour of the Dart platform and updated conference attendees on Dart developments since last I/O.




Dart code lab

The Dart code lab provided a hands-on experience to participants, who built a mobile-friendly web app using Dart and the Web UI framework.

Overflow crowd at the Dart code lab. The number of participants at the code lab increased by over 60% from I/O 2012
You can try the Dart codelab and build a modern app using the Web UI framework.

Dart booth at the Developer Sandbox

The Dart booth at I/O was a busy, bustling place. Conference attendees got to watch cool Dart demos, interact with Dart engineers, and pick up some nice Dart swag!

Shailen Tuli shows the results of benchmarking code in the Dart VM, dart2js, and hand-written JavaScript. The Dart VM won handily, with the JavaScript compiled by dart2js neck and neck with handwritten JavaScript.  


Adobe shows off the Toolkit for Dart

Adobe released the Toolkit for Dart for Adobe Flash Professional at I/O. The toolkit lets designers and animators create assets for HTML5 projects using Dart libraries and supports most of the core animation and illustration capabilities of Flash Professional.

Playing an HTML5 game built with Flash Pro, exported to Dart with the push of a button! 


Dart at the JetBrains booth

An attendee gets a tour of the features available to Dart developers.


I/O news coverage about Dart

Stephen Shankland at CNET prominently covered the talk by Lars Bak and Kasper Lund on VM performance. Here's an excerpt:


John Pavley at the Huffington Post covered Dart in his round up of Google I/O news:

excerpt from huffpo article

To get an even better feel for Dart at Google I/O 2013, look for #io13 #dartlang on Google+

by Shailen Tuli (noreply@blogger.com) at May 21, 2013 11:04 PM

Chris Strom

Dart Test Helpers

‹prev | My Chain | next›

I find myself repeating a lot of the same test actions in my ICE Code Editor test suite. This seems a fine opportunity to explore test helpers in Dart unit tests.

The one in particular that I find myself doing a lot is clicking on element, usually with particular content:
      queryAll('button').
firstWhere((e)=> e.text=='☰').
click();
My first instinct is that the helpers should be a separate library that is imported into my test suite. The main reason is that I can import with an “as” prefix to make it patently obvious where the helper methods live. So, in my main ice_test.dart main test file, I add the import statement:
library ice_test;

import 'package:unittest/unittest.dart';
// ...
import 'helpers.dart' as helpers;
import 'package:ice_code_editor/ice.dart';

main(){
// tests go here...
}
In helpers.dart, I start with a single click() function:
library ice_test_helpers;

import 'dart:html';

void click(String selector, {text}) {
if (text == null) return query(selector).click();

queryAll(selector).
firstWhere((e)=> e.text==text).
click();
}
The click function requires a string selector that will be used to query for elements to click. If no text is specified—if the optional, named parameter text is null—then I query for the first matching selector and click it. If the text parameter is specified, then I query for all matching selectors, find the first that contains the supplied text and click that.

I continue to use the firstWhere() because it will throw an exception if no matching element is found. I may want to bundle that into a new exception that makes it more obvious what has gone wrong in the test, but I leave it for now.

With that, I can change the test that verifies one of the ways to close a menu:
    test("the menu button closes the projects dialog", (){
queryAll('button').
firstWhere((e)=> e.text=='☰').
click();

queryAll('li').
firstWhere((e)=> e.text=='Projects').
click();

queryAll('button').
firstWhere((e)=> e.text=='☰').
click();

expect(
queryAll('div').map((e)=> e.text).toList(),
isNot(contains(matches('Saved Projects')))
);
});
Instead, I can write that as:
    test("the menu button closes the projects dialog", (){
helpers.click('button', text: '☰');
helpers.click('li', text: 'Projects');
helpers.click('button', text: '☰');

expect(
queryAll('div').map((e)=> e.text).toList(),
isNot(contains(matches('Saved Projects')))
);
});
Holy clearer intent Batman! It is much easier to see that this test clicks the menu button, then the Projects menu item, then the menu button again.

I might have omitted the “helpers” prefix from my import statement and thus been able to treat click() as a top-level function. I tend to think that the prefix will aid in long-term maintainability of the test suite as there will never be a question as to the source of the helper function.


Day #757

by Chris Strom (noreply@blogger.com) at May 21, 2013 03:53 AM

May 20, 2013

Dartlang

Notes from May 6th Dart Language Design Meeting

The incomporable Bob Nystrom fills us in on the language design discussions taking place amongst Dart engineers. Here are his notes from the May 6th language meeting:

API maturity annotations

Lars says Dan Grove wants a decision on annotations that denote maturity of source code. For most stuff, Lars thinks we should just annotate the whole library. The place where makes sense is dart:html. In that case, we can make an exception.

I asked if this is a language question, or just a question for people at the level of the language team.

Lars says Dan specifically said for the language.

Everyone agreed this is a good idea for the Dart system. [Gilad later clarified that they all also agree it is not a language issue.]

Lars says everything except dart:html we'll put in the libraries.dart config file. We can show that in the Editor.

[Dan later clarified was that his question was the meta-question to decide if this issue is a language issue or not.]

? operator

Gilad: Can we get rid of it?
Lars: Yes.
Gilad: OK, done.

map literals

Lars asks if everyone likes the new proposal [that Gilad sent to the language team]. Everyone does.

[This is now in the latest published spec. Basically, you can have non-string keys in map literals. Woo!]

exports

Lars says Florian has some issues about exports. Asked if Gilad is talking to him about it.

[This is the same issue about exports that came up on the mailing list recently.]

library names

Gilad says Kasper's proposal looks fine. Given other decisions we've made, it makes things more consistent.

Lars is reluctantly accepting it.

This means it will be a static warning to import multiple libraries with the same name. This is a breaking change so we should let people know it's coming.


As always, view the changelog for the full list of changes, and to get started with the Editor see our tutorial.

by Shailen Tuli (noreply@blogger.com) at May 20, 2013 09:51 PM

May 15, 2013

Dartlang

Adobe's Flash Pro CC Exports to Dart and HTML5


At Google I/O today, Adobe announced their new Toolkit for Dart, a plugin for Flash Professional CC that allows developers to export their animations and games to Dart code and HTML5.



"Adobe is delighted to announce the Toolkit for Dart, an extension that enables web designers and animators to publish their Flash content to Dart." said Tom Barclay, Sr. Product Manager at Adobe. With the Toolkit, developers, designers, and animators can create interactive, animated content inside of Flash Pro and publish to the Dart language and HTML5 APIs. Because Dart compiles to JavaScript, the content runs across modern desktop and mobile browsers without plugins.

Toolkit for Dart supports many of the core animation and drawing capabilities of Flash Pro, including bitmaps, shapes, movie clips, graphic symbols, classic tweens and motion guides, simple buttons, text fields, drop-shadow and glow filters, additive blend mode, single-shape masks, visible and cacheAsBitmap display options, and embedded audio. The Toolkit generates Dart code that represents items on the stage, symbols, images, and sounds in the library.

The Toolkit doesn't translate ActionScript to Dart. Instead, developers write Dart code for the interactive parts of the content. Dart is similar to ActionScript 3: it is a familiar, class-based, object-oriented language with rich core libraries, optional static types, and more.

The extension leverages the StageXL for Dart library to reproduce Flash runtime features. The StageXL library is a complete and robust Flash-like engine for Canvas that is built on top of the Dart programming language. StageXL provides an approachable Flash-like API to build games and other graphically rich content. It is intended for Flash/ActionScript developers who want to migrate their projects as well as their skills to HTML5. Bernhard Pichler, author of StageXL, asks you to "use your creativity to enrich the modern Web."

Adobe plans to contribute the Toolkit to the open source community. The Toolkit for Dart is expected to be available as a Github repo shortly after Flash Professional CC is released on June 17.

by Seth Ladd (noreply@blogger.com) at May 15, 2013 07:30 PM

May 13, 2013

Dartwatch

Lots of new ways to keep up with #dartlang changes

The Dartisans community has grown, with currently >2000 members on the +Dartisans group, and >1500 subscribers to the Dart Weekly newsletter.  Keeping up with the latest changes can be tricky.

Google's Andrei Mouravski has just posted this on the mailing lists:




tl;dr: We have some new discussion groups. Sign up for announce@dartlang.org.
For a quick summary, read the Guidelines section below.


Hello Dartisans!

As our community has grown, so has discussion around Dart, so we have created four new discussion groups, and updated a few others.

New Groups:

announce@dartlang.org : Dart Announcements
This group is for official announcement for the Dart project. This will be product releases, breaking changes, major events, press briefs, and other important messages for the entire Dart community. For now, the group will remain limited to a select group of individuals who manage specific parts of the Dart project.
I recommend signing up for this group today, as it is a low volume way to stay up to date with Dart on a day-to-day level.
---

Note: Replies to announcements in this group should go to dart...@dartlang.org to keep the announce list noise-free, but still provide a forum for discussion.

For the time being, posts to
anno...@dartlang.org will be forwarded to mi...@dartlang.org.
In a few weeks we will remove the forward to misc@dartlang.org to prevent unnecessary duplicate e-mails, so sign up now!



dart-dev@dartlang.org : Dart Core Project and Libraries Development
This is the list to go to if you want to discuss the development of the Dart open source project. As the project continues to grow, it’s important to be able to stay connected with state of the core of Dart itself.

This is a good place to talk about core library APIs, discuss breaking changes, and interact with the Dart engineering team. If you’re thinking of contributing to the Dart project, let us know in this group!

This list will be more technical than some of the other lists, so keep that in mind when subscribing. You should subscribe to this list if you’re interested in keeping up with day to day Dart development and engineering.

---

Note: If your discussion is about a project you’ve created, broad feature requests such as other languages’ features you’d like to see in Dart, the state of the web/JavaScript/html5/etc., news, links, or events, then please post to misc@dartlang.org. See the guidelines below.



html-dev@dartlang.org : Dart DOM/HTML Libraries Development
If you want to keep up with the latest developments to the HTML/DOM libraries, here’s where to go! The libraries in question are: dart:html, dart:svg, dart:web_audio, dart:web_gl, dart:indexed_db, dart:web_sql, and dart:chrome, but it’s possible there will be more. This is the group to follow to hear about changes to DOM bindings.
I recommend signing up for this group, as it is a medium volume way to stay up to date with anything changing in the main DOM libraries. If you build client applications, or just care about the modern web, stay tuned!

editor@dartlang.org : Dart Editor and Plugin Development and Discussion
If you use the Dart Editor to write Dart code, or debug Dart applications, or for any reason at all, this is the group for you. The Editor team loves, probably more than any other team, receiving feedback. This list is a great place to talk about what you want to see in the Editor, and discuss the state of the Dart IDE.

---


Other groups:

Just a reminder about the other groups we have:

misc@dartlang.org : Miscellaneous Discussion
vm-dev@dartlang.org : Dart VM Development
compiler-dev@dartlang.org : dart2js Development
web-ui@dartlang.org : Dart Web UI Package Discussion

The following groups are read-only, as their posts are auto-generated:

commits@dartlang.org : Commits to the Dart Repository
bugs@dartlang.org : Dart Issue Tracker Updates
reviews@dartlang.org : Dart Code Review Updates

---

And just to be clear, here are guidelines for posting to any of the groups:

Guidelines

by Chris Buckett (noreply@blogger.com) at May 13, 2013 12:55 PM

May 10, 2013

Shannon -jj Behrens

Personal: Links to My G+ and Twitter Accounts

If you enjoy my blog posts on Python, Ruby, Dart, etc., and you're looking for a new way to follow me now that Google Reader is going away, here are my Twitter and G+ accounts:

by Shannon Behrens (noreply@blogger.com) at May 10, 2013 06:15 PM

May 08, 2013

Christian Grobmeier

Review: Dart in Action

"Dart in Action" by Chris BuckettRecently I read “Dart in Action” by Chris Buckett. I know Chris from the early days of the Dart language. We both joined the community almost instantly. At the day of Darts arrival, he founded Dartwatch.com and blogs on all aspects of the language. Chris is definitely one of these guys who knows what he writes. After one year, a lot of blog posts, countless e-mails to the Dart mailing lists and doing a lot of other community related things, he finished a book on Dart.

A book? This alone is impressive. Dart is a kind of moving target. There is a lot of man-power behind its development and every day there are a lots of changes to Darts codebase. Dart arrived as a technical preview and as such it was allowed to have breaking changes. Chris was not only confronted with learning a language by looking at its specification and find out about hidden features in the bug trackers; he also had to rewrite whole sections over and over again just because the language changed. A simple example: suddenly the + operator for string concatenations was removed. A more complicated example: the whole library/import thing changed.

Still Chris kept on writing. Finally Dart became more stable in its core, and the book was released. What I got was a book from a dedicated and passionate Dart-developer, who knows the language, its ecosystem and the community from day 1.

The book itself reads like that. It’s a fantastic book which takes you by hand and leads you through the whole world of Dart. With that I mean it doesn’t stop at just explaining some grammar or how to use API $x. Dart is not “only a language”. Dart is a whole ecosystem consisting of language, APIs AND tools. Chris shows from the beginning where you need to look at, like using the Dart Editor or how to deal with third party dependencies.

You almost do not recognize how you get into all these new technologies. While he explains how to write code, he also shows how to debug it or what you can do with it in practice. It is far from boring grammar descriptions or rephrased API docs as one can often find in books. You can work on your program while reading this book. It’s for people like me, who do not want to read through 500 pages with boring examples just to make up something cool after the memorized all of the thousand keywords. This book shows you what you can do, how you do it, and what you should be aware of. It’s easy to connect the books content with your real-life-problems.

The writing style is clear, precise and well balanced. An easy read. The tune is one of a colleague who did find some great new toy to play with and now explains it to you. It is a motivating and inspiring text and very enjoyable. There was not a single chapter which made me bored or drifting away.

The content is a great mix of everything important in Dart.

You will learn about running Dart from the Browser but also how to run it from the shell, maybe when building your backend with Dart. You learn how you can write test driven code. Unit testing with Dart is especially something which I did not know much about before. In the early days of Dart it was not so much a topic, and due to work I did not follow it to closely later. Chris sent me back on track. Now I even know how to do browser testing, which is big win for me.

He explains on how properly to use classes, interfaces and constructors. Also he looks into libraries and shows possibilities here. What I like much is the fact he is also explaining best practices. Not only Darts best practice, but general ones. These are experiences he made maybe from his time as GWT developer. They are very helpful if you just start with your programming career.

In general, the core part of this book feels complete and balanced. There is even a part describing Futures and Completers. Both are heavily used async concepts in todays browser programming world, and with “Dart in Action” it is easy to get into them. Another bonus point is he is explaining how you can test asynchronous code. As this is a very difficult matter, I have not expected that.

The chapters on client development are also very good. One can first find a great introduction into single-page web apps. I wished I would have read this before a long time now. It also gives you a great view how you can actually build your Dart app. If you are coming from the classic approach of maintaining multiple pages, you might find this section very useful. He is also writing on how to use Cookies and Data Storage. Especially the browser db part I found very interesting.

One often asked question is how to interact with JavaScript from Dart and vice versa. You will find an answer in this book. Even more: Chris describes how to make apps for the Chrome web store. With this, you already have enough knowledge to start with your App, integrate it to existing libs and finally deploy it to its final destination. A complete cycle. But there is even more.

The book closes with looking at server side Dart. It’s shown how to interact with Apache CouchDB as data store and how one can serve HTTP requests with Dart. Everybody who is into Node.js knows that it is a great feeling to just use the same language for frontend and backend. Finally he looks into Isolates, one of my favorite topics. Even when I know a lot on Isolates (some kind of multithreading in Dart), I found this is a very competent introduction into it and  I did not regret to have it read.

My conclusion is this a great book. Usually I do not read books on programming languages anymore. They tend to be boring and quickly out of date. But this book is different. It shows you more than just grammar and APIs. It shows you how to move in the Dart world. How you solve things. It’s an enjoyable read from a very competent Dart programmer. If you want to learn Dart you already have the great docs on the website. But if you would like to get even more quickly into Dartlang, then you should definitely look at this book. Despite the language is still evolving, most of its content will be true for a long time. If not, then the author can be found in one of the Dart communities.

You can buy this book on Amazon.com or on Amazon.de (affiliate links).

by Christian Grobmeier at May 08, 2013 12:02 PM

May 07, 2013

Dartwatch

Campaign to use real logging (instead of print) in your libraries and apps

Summary of "Campaign to use real logging in Dart" (via tldr.io)
  • Using print() statements for debugging in your libraries means that everyone gets your print() output.
  • The Dart SDK has a "logging" package built in (that lets you write into a logging framework), but nothing to output those log messages.
  • The "logging_handlers" package adds those missing handlers, letting you output to the console (like print), filesystem (server side), and a webui component.
  • Now you (and I) can control the logging output from different libraries by varying the logging level different libraries.

Stop Using print(msg) start using info(msg)

When you use print(), other users of your code have to see all your internal debug logging (I know I'm guilty of this, too).
The logging_handlers package lets you use proper logging in your client-side or server side Dart application.

Why?

When I use your library (or when you use my library), I want to control the amount of logging output from your debug messages (and, I hope, you want to do the same for my debug messages). By using the Dart logging framework, we can both be happy.

There are two parts involved in logging:

  1. Sending log messages into a logging framework
  2. Outputting the log messages somewhere (eg, to the stdout, a file, the browser).
Dart's print() sort of covers both of these use cases, and the quick'n'dirty alternative described below also does the same thing. It's not the best way, but at least it means that log messages can be output somewhere other than the console (such as a file).

First, some background about logging

Dart's logging pub package, that forms part of the Dart SDK, covers use-case 1, in other words, it lets you send log messages into a logging framework.
This framework lets you attach handlers to that framework that can listen to the stream of log messages.
This package, logging_handlers provides some default handlers that lets you output messages to a variety of locations, in a variety of formats.
At the moment, you can output a log message as a tab delimited String or a JSONableMap, and you can output a log message to the console similar to print(), to a server-side file, or to a client-side web-ui component (or a mixture).

The quickest (and dirtiest) way to replace print()

This is not the best way, but it's certainly better than print().
  1. Add logging_handlers package to pubspec.yaml
  2. import 'package:logging_handlers/logging_handlers_shared.dart';
  3. Use debug(msg)info(msg)warn(msg)error(msg) as appropriate.
  4. Somewhere in your initialization code (start of your unit tests, main() or other initialization code), call startQuickLogging()
For example:
import 'package:logging_handlers/logging_handlers_shared.dart';

main() {
    startQuickLogging();
    info("Hello World");
}
will output to the console:
2013-05-06 16:42:42.593     [INFO]: Quick'n'Dirty logging is enabled.  It's better to do it properly, though.
2013-05-06 16:42:42.604     [INFO]: Hello World
Note: Dart's logging has more fine grained logging levels - the top-level functions above are shorthand for some of these:
             FINEST // highly detailed tracing
             FINER // fairly detailed tracing 
debug(msg) = FINE // tracing information
             CONFIG // static configuration messages
info(msg)  = INFO // informational messages
warn(msg)  = WARNING // potential problems
error(msg) = SEVERE // serious failures
             SHOUT // extra debugging loudness
But see below for better ways that allow users of your code more control over what actually gets output, and let you have finer-grained control over logging.

The a slightly better way (but still a bit quick'n'dirty) to replace print()

Let users of your code filter out your specific log messages by giving your log messages a name. The best name is the name of your library. for example:
library my_library; 
import 'package:logging_handlers/logging_handlers_shared.dart';

class Foo() {
  Foo() {
    debug("Foo is created", "my_library"); // calls debug with your library name
  }
}

main() {
  startQuickLogging();
  new Foo(); 
}
this outputs:
2013-05-06 16:42:42.593     [INFO]: Quick'n'Dirty logging is enabled.  It's better to do it properly, though.
2013-05-06 16:42:42.604 my_library      [FINE]: Foo is created
When you include your library name in your log messages, other users of your code can filter your log messages out (more on that later).

The best way to implement logging in your libraries

Create a Logger instance in your library, and give it the name of your library:
library my_library;
import 'package:logging_handlers/logging_handlers_shared.dart';

final _logger = new Logger("my_library");

class MyClass {
    MyClass() {
       _logger.fine("MyClass created");
    }

    foo() {
      _logger.error("Something bad has happened");
    }
}
You can have as many loggers as you need, and they can be hierarchical (using a . to separate). For example, you might have a top-level logger, and individual loggers for specific classes:
library my_library;
import 'package:logging_handlers/logging_handlers_shared.dart';

final _libraryLogger = new Logger("my_library"); // top level logger

class MyClass {

  // MyClass logger is a child of my_library logger
  static final _logger = new Logger("my_library.MyClass");

  MyClass() {
     MyClass._logger.fine("MyClass created"); // using class logger
  }

  foo() {
    _libraryLogger.error("Something bad has happened"); // using top-level logger
  }
}
When you use hierarchical logging, you (and your code's users) can start to take control over what actually gets output, and to where (such as outputting ALL logging for MyClass, but only WARNING, SEVERE and SHOUT logging for the library).
Now that you've seen how to emit log messages into a framework, let's take a look at how to control where those messages go

Controlling log message output

The code in your classes and libraries don't actually run until you pull them into a Dart application (or unit test) via the top-level main() function.
In the main() function, you need to initialize the logging framework with a logging handler. The simplest version of this is the PrintHandler, which outputs log messages to the console in the same way that print() does.
Let's assume that you've implemented logging using "the best way" which contains your logger name.
// the SDK logging framework
import 'package:logging/logging.dart'; 
// Handlers that are shared between client and server
import 'package:logging_handlers/logging_handlers_shared.dart'; 
// your library, from above...
import 'my_library';

main() {
  Logger.root.onRecord.listen(new PrintHandler()); // default PrintHandler
  var myclass = new MyClass(); // from above - outputs log message
}
If you're on the server-side, and you want to log to a file, the logging_handlers package includes a very simple (synchronous) filesystem log file handler: SyncFileLoggingHandler.
// the SDK logging framework
import 'package:logging/logging.dart'; 
// Handlers that run server-side
import 'package:logging_handlers/server_logging_handlers.dart'; 
// your library, from above...
import 'my_library';

main() {
  Logger.root.onRecord.listen(new SyncFileLoggingHandler("myLogFile.txt")); 
  var myclass = new MyClass(); // from above - outputs log message
}
And if you're on the client side, there's a handy (and incredibly basic) web component<x-loggerui> to output log messages on screen.
In your Web UI enabled application, your HTML will look something like this:
<html>
  <head>
    <!-- import the loggerui component -->
    <link rel="import" href="package:logging_handlers/src/client/loggerui.html">
  </head>

  <body>   
    <!-- other content... -->

    <x-loggerui></x-loggerui>  <!-- Logger widget -->

    <!-- standard app scripts -->
    <script type="application/dart" src="test.dart"></script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>
And in your app's main() function, you call attachXLoggerUi() like this:
import 'package:logging_handlers/browser_logging_handlers.dart';

main() {
  attachXLoggerUi(); // lives in the browser_logging_handlers library
}
The attachXLoggerUi function runs in the next event loop iteration after main (usingTimer.run), so any startup logging won't appear. This is because the web component's themselves aren't available until the next event loop.
Here is a running example:

Attaching multiple handlers
Sometimes, you want to attach multiple handlers. That's fine, because the logging framework uses Streams, so you just need to use asBroadcastStream():
main() {
  var loggerStream = Logger.root.onRecord.asBroadcastStream();
  // attach the PrintHandler and the File logging handler
  loggerStream.listen(new PrintHandler()); 
  loggerStream.listen(new SyncFileLoggingHandler("myLogFile.txt"));       
}
Note At present, the implementations of the client and server handlers are fairly basic, but given time (and your help?), they should get greater functionality. Ideas include: Allowing the x-loggerui to filter based on level.
or creating an async version of the server side logger.

Getting more control over the output

Now you have seen what can be output, let's take a look at how you customize that.
Each of the handlers (LoggerUiSyncFileLoggingHandler and PrintHandler) implement aBaseLoggingHandler interface. These have a LogRecordTransformer instance, that transforms an SDK LogRecord into some other format.
The logging_handlers package contains two transformers that implementLogRecordTransformerStringTransformer and MapTransformer. All three handlers use a default implementation of a StringTransformer, but you can pass an alternative transformer into the constructor of both the PrintHandler or SyncFileLoggingHandler.
StringTransformer
The StringTransformer lets you control the fields that get output, for example:
main() {
  var fileHandler = 
      new SyncFileLoggingHandler("logfile.txt", transformer: new StringTransformer("%m"));
  Logger.root.onRecord.listen(fileHandler); // default 
  var myclass = new MyClass(); // from above - outputs log message
}
The StringTransformer allows formatting strings to specify the output. %m is just the message without all the other information, and replicates the print command.
The full list of formatting strings is shown below:
%p = Outputs LogRecord.level
%m = Outputs LogRecord.message
%n = Outputs the Logger.name
%t = Outputs the timestamp according to the Date Time Format specified
%s = Outputs the logger sequence 
%x = Outputs the exception
%e = Outputs the exception message
The default formatting strings are shown below (with \t for tab separation):
DEFAULT_MESSAGE_FORMAT = "%t\t%n\t[%p]:\t%m";
DEFAULT_EXCEPTION_FORMAT = "\n%e\n%x";
DEFAULT_DATE_TIME_FORMAT = "yyyy.mm.dd HH:mm:ss.SSS Z";
You can customize all of these when you create a logger handler.

Replacing the print() command

Now that you have seen some of the formatting available, let's see how you can actually replace the print() command:
main() {
  // simulate existing print command by only outputting the message
  Logger.root.onRecord.listen(new PrintHandler(messageFormat:"%m")); 
}

Taking control: Logging levels and heirarchical loggers

Let's suppose that you are using my library.
We have your_library and my_library
You don't want to see my logging when you test your library.
How can you control it?
Let's look at some code that outputs logging from your_library but not my_library:
import 'package:my_library/my_library.dart'; // don't want to see logging here
import 'your_library.dart';  // Show logging from this library please :)

import 'package:logging/logging.dart'; 
import 'package:logging_handlers/logging_handlers_shared.dart';

main() {
  hierarchicalLoggingEnabled = true; // set this to true - its part of Logging SDK

  // now control the logging.
  // Turn off all logging first
  Logger.root.level = Level.OFF;
  Logger.root.onRecord.listen(new PrintHandler());

  // create a logger for your library 
  // (there will be a single instance for each logger with the same name)
  // and set the level to ALL
  new Logger("your_library")..level = Level.ALL;

  doSomethingInYourLibrary(); // logging is output to console
  doSomethingInMyLibrary(); // logging is not be output      
}
Now let's use the hierarchy to use different logging for a specific class (assuming that you have a class logger created for your_library.YourClass):
main() {
  hierarchicalLoggingEnabled = true; // set this to true - its part of Logging SDK

  // now control the logging.
  // Turn off all logging first
  Logger.root.level = Level.OFF;
  Logger.root.onRecord.listen(new PrintHandler());

  // create a logger for your library 
  // (there is only a single instance for each logger with the same name)
  // and set the level to ALL
  new Logger("your_library")..level = Level.INFO;
  new Logger("your_library.YourClass")..level = Level.ALL;

  doSomethingInYourLibrary(); // Only INFO logging is output to console
  new YourClass(); // All logging output to the console
  doSomethingInMyLibrary(); // logging is not be output      
}

Quick Reference

Logging best practice
  1. Add logging and logging_handlers to pubspec
  2. Import the logging SDK where you want to write log messages
    import 'package:logging/logging.dart';
  3. Create a logger (or loggers), and use them
    ``` final _libraryLogger = new Logger("my_library");
    doSomething() { _libraryLogger.info("Something is done") }
    class MyClass { final _classLogger = new Logger("my_library.MyClass")
    MyClass() { _classLogger.fine("MyClass is constructed"); } } ```
  4. When you use your library / class, and want to output some logging, create an instance of a LoggingHandler and attach it to the root logger
    ``` import 'package:logging_handlers/logging_handlers_shared.dart'; import 'your_library';
    main() { Logger.root.onRecord.listen(new PrintHandler()); } ```
  5. When you want finer control over what get's output, use hierarchical loggin and set levels
    ``` import 'package:logging_handlers/logging_handlers_shared.dart'; import 'your_library'; import 'package:my_library/my_library.dart';
    main() { Logger.root.onRecord.listen(new PrintHandler()); Logger.root.level = Level.OFF; // log nothing by default new Logger("your_library")..level = Level.ALL; // log all in your library
    } ```
Server handlers are found here:
import 'package:logging_handlers/server_logging_handlers.dart';
Client logging handlers are found here:
import 'package:logging_handlers/browser_logging_handlers.dart';
Web UI component is here:
<link rel="import" href="package:logging_handlers/src/client/loggerui.html">
...
<x-loggerui></x-loggerui>

... 
// and in your script, call:
import 'package:logging/logging.dart'; 
import 'package:logging_handlers/browser_logging_handlers.dart';

main() {
  hierarchicalLoggingEnabled = true;
  attachXLoggerUi();
}

Caveats

The Logger framework (as at M4), has a TODO about logging exceptions. At the moment it doesn't. If you want to log exceptions, add the exception text to the log message.
If you find any problems or errors, then please let me know. This was current as at r21823

by Chris Buckett (noreply@blogger.com) at May 07, 2013 07:17 PM

May 06, 2013

April 30, 2013

Dartwatch

Try out Dart in your browser at http://trydart.dartwatch.com

Now you can try out Dart code snippets in your browser at http://trydart.dartwatch.com.

 Features: 

  •  Link to a shortcode of your Dart snippets 
  •  Embed runnable snippets in your blogs (like below).

At the moment it doesn't support pub packages, dart:io, dart:html, so it's only for trying out dart language snippets. Let me know if you use it, (or if you manage to break it :).

by Chris Buckett (noreply@blogger.com) at April 30, 2013 11:35 AM

April 24, 2013

Seth Ladd

Lazy Load Libraries in Dart

Dart is a statically analyzable language, and its tree-shaking compiler does a good job of eliminating dead code and producing a single, optimized application file. However, sometimes developers need to control when certain libraries are loaded and thus need to control which libraries are included in the main application file. To help, the dart2js compiler, which converts Dart code into JavaScript code, now supports lazy-loaded libraries.



Lazy Load

As an example, consider an application that has many different screens. Some screens are more obscure than others, and aren't required for the application to start. A developer should be able to say "I don't need these screens now, but pull them in when I do need them." This lazy-loading is a common deployment strategy for web apps, because small initial loads means faster application startup.

You can mark a library as "lazy", and the dart2js compiler will output a separate JavaScript file for that library. Note that dart2js still performs tree shaking (aka dead code elimination) across the entire app (technically, across the entire isolate). This means that only the functionality required from the lazy-loaded library will actually be compiled into the separate file.

The lazy-loaded library is still part of the application structure, and must exist and be available to dart2js when the program is compiled. This is not "dynamic loading", per se, because the application must statically import all libraries (lazy or not).

(Note: as of the time of this writing, dart2js emits at most one other JavaScript file. This restriction will be removed and you will be able to emit multiple files for a single application. Please track Dartbug 3940 to learn more.)

DeferredLibrary Example

The main application can mark a library with an @lazy metadata. Then, it declares an instance of DeferredLibrary that points to the outputted JavaScript file.

import 'dart:html';
import 'dart:async';

@lazy
import 'reverser.dart';

const lazy = const DeferredLibrary('reverser', uri: './part.js');

void main() {
  lazy.load().then((_) {
    print('library loaded');
    query("#sample_text_id")
      ..text = "Click me!"
      ..onClick.listen(reverseText);
  });
}

void reverseText(MouseEvent event) {
  query("#sample_text_id").text =
      reverse(query("#sample_text_id").text);
}

Notice how the library doesn't come into existence until after the Future from lazy.load() completes. Only then can you call into the library.

The runtime throws NoSuchMethodError if you try to access functionality from a library that it not yet loaded.

More to come

The lazy-load functionality of dart2js is just the beginning. In the future, you will be able to mark multiple libraries as "lazy", and really control how you deploy and load your web application.

Also, this functionality only currently works with dart2js. Please star Dartbug 10171 if you are interested in seeing the same lazy-loading for the VM and Dartium.

Please try this out, we look forward to your feedback!


(Photo Credit: Marcus Hansson licensed under cc)

by Seth Ladd (noreply@blogger.com) at April 24, 2013 05:47 AM

Dynamically Load Code with Dart

Rejoice! Dartium, a build of Chromium with the Dart VM, can now spawn a new isolate from a URI. This means your Dart apps have a new option for more modular code.

Isolates

In Dart, an isolate is an abstraction for an "isolated memory heap". Isolates do not share memory (variables, statics, etc), they are essentially self-contained applications. Isolates communicate by sending and receiving messages over ports.


Why Isolates Matter

Dart programs are static, in that their shape and structure do not change after they are compiled. A static program is great for optimizations like tree shaking (aka dead code elimination), type-inferencing compilers, and more.

However, modular apps often require a way to dynamically load code. Configurable and modular apps need a way to, at run time, pull in new functionality. If Dart apps have a static structure, how can they dynamically alter their behavior?

Isolates to the rescue! The structure inside of an isolate is static, but a Dart program is free to dynamically load other isolates. This means that libraries can be loaded into isolates at run time.

Your First Isolate

This simple reverser isolate listens on its port, receives messages, reverses them, and send the reversed text back to the sender.

// reverser.dart


import 'dart:isolate';

main() {
  port.receive((msg, SendPort replyTo) {
    var reverse = msg as String;
    var buffer = new StringBuffer();
    for (var i = reverse.length - 1; i >= 0; i--) {
      buffer.write(reverse[i]);
    }
    replyTo.send(buffer.toString());
  });
}

The main application (which itself is an isolate), is responsible for instantiating the reverser isolate. Use the spawnUri() function from dart:isolate to spawn a new isolate from some file.

// main.dart

SendPort reverser;

void main() {
  query("#sample_text_id")
    ..text = "Click me!"
    ..onClick.listen(reverseText);
  
  var serviceFile = 'reverser.dart';
  
  if (identical(1, 1.0)) {  // XXX: horrible hack to detect if we're in JS
    serviceFile = 'reverser.dart.js';
  }
  
  reverser = spawnUri(serviceFile);
}

Notice the horrible hack to detect if this code is running in the Dart VM or JavaScript. I don't know a better way to do it, but I don't recommend this.

When the text from #sample_text_id is clicked, the reverseText function is run:


void reverseText(MouseEvent event) {
  var text = query("#sample_text_id").text;
  reverser.call(text).then((reversed) {
    query("#sample_text_id").text = reversed;
  });
}

Notice how the reverser isolate is sent a message via call(), which returns a Future. When the Future completes, the callback registered with then() is run.

Support

Dartium supports spawnUri since at least version 28.0.1478.0 (194114). Dart2js compiles spawnUri() into a Web worker.

Note that each isolate is its own app, so dart2js must compile the same bootstrap code into each isolate file.

by Seth Ladd (noreply@blogger.com) at April 24, 2013 04:17 AM

April 22, 2013

April 18, 2013

Seth Ladd

6 Dart FAQs - Answered!

Calvin Prewitt wrote some good questions about Dart via G+. It might be hard to find his questions and my answers, so I hoisted them here. Enjoy!

Q) Could you also detail compatibility and which JavaScript APIs are fully or partially supported for Dart2JS production code?

A) All JavaScript APIs supported by Chrome should be available to Dart. See http://www.dartlang.org/articles/improving-the-dom/



Q) It appears Dart is aiming to eventually replace it? The FAQ says it only targets modern browser versions.

A) Dart's aim is to give developers like you a very productive experience, and give your users a very fast experience. Dart targets IE9+, plus the modern versions of Firefox, Chrome, Safari, mobile safari, and Chrome for Android. Basically, modern browsers.



Q) Is there a way to have fine grained control over the JS code like in Closure?

A) Dart2js can emit a single file, plus up to one other lazily loaded library. In the future, we want to give you more control. Here's the bug: https://code.google.com/p/dart/issues/detail?id=10023 Please note, dart2js's output is already smaller thanks to tree-shaking.



Q) I've noticed a lot of similarities to Closure Library. Has some or all of the Closure Library code been ported?

A) I'm unaware of an "official" port from the closure libraries. In general, though, you shouldn't need it. Dart's core libraries are pretty comprehensive. Check out http://api.dartlang.org



Q) Is Dart ready for production use? Specifically for generating JS code. If not, what's missing or where are the sore spots?

A) Dart's M4 release just came out, promising no more breaking changes to the core libs. Hurray! There's still work to do, but the platform just got much more stable. If you see something missing, let us know: http://dartbug.com/new



Q) Finally, where can I help? Closure is nowhere near a productive environment. If Dart is aiming to make building complex web apps easier than working with Closure, I'd like to contribute to that goal.

A) Yes, we're "aiming to hit a productivity and performance bullseye" (groan :) We'd love help. Dart is open source, so check out http://dartbug.com/ and out Github presence athttp://github.com/dart-lang Join our Dartisans community in G+, too

by Seth Ladd (noreply@blogger.com) at April 18, 2013 08:09 PM

April 03, 2013

Adam Coding @ Github

gplus quickstart with dart

Tonights mash-up was taking the gplus-quickstart-dart and wiring it up for server side support. Similar to the gplus-quickstart-java, the client will use the gplus login button to do the OAuth2WebServer flow and send the code over to the server. The server can then verify and make calls on behalf of the client since an ‘offline’ token was requested. This demo just features the server side and what was used to put it together. Yulian Kuncheff has been the primary developer behind fukiya which is an express like framework for dart. The thing I liked most about fukiya was how simple and easy it was to setup URL handlers.

First off, setting up some dependencies.

1
2
3
4
5
6
dependencies:
  google_plus_v1_api: any
  browser: any
  fukiya: '>=0.0.11'
  html5lib: ">=0.4.1 <0.4.2"
  logging: ">=0.4.3+5"

A quick outline of what URLs fukiya handles. Dead simple to setup!

1
2
3
4
5
6
7
8
9
10
11
12
void main() {
  new Fukiya()
  ..get('/', getIndexHandler)
  ..get('/index.html', getIndexHandler)
  ..get('/index', getIndexHandler)
  ..post('/connect', postConnectDataHandler)
  ..get('/people', getPeopleHandler)
  ..post('/disconnect', postDisconnectHandler)
  ..staticFiles('./web')
  ..use(new FukiyaJsonParser())
  ..listen('127.0.0.1', 3333);
}

The index handler is special cause we needed to inject a state token into the page and HTTP session. The state token is then verified on the /connect post. The one-time token helps avoid any Confused_deputy_problems.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void getIndexHandler(FukiyaContext context) {
  // Create a state token. 
  context.request.session["state_token"] = _createStateToken();

  // Readin the index file and add state token into the meta element. 
  var file = new File(INDEX_HTML);
  file.exists().then((bool exists) {
    if (exists) {
      file.readAsString().then((String indexDocument) {
        Document doc = new Document.html(indexDocument);
        Element metaState = new Element.html('<meta name="state_token" content="${context.request.session["state_token"]}">');
        doc.head.children.add(metaState);
        context.response.writeBytes(doc.outerHtml.codeUnits);
        context.response.done.catchError((e) => serverLogger.fine("File Response error: ${e}"));
        context.response.close();
      }, onError: (error) => serverLogger.fine("error = $error"));
    } else {
      context.response.statusCode = 404;
      context.response.close();
    }
  });
}

On the /connect post we will expect a gplus id to be passed to the query parameters and some token data posted. We can then verify the state token and use the token data for accessing the Google APIs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
void postConnectDataHandler(FukiyaContext context) {
  serverLogger.fine("postConnectDataHandler");
  String tokenData = context.request.session.containsKey("access_token") ? context.request.session["access_token"] : null; // TODO: handle missing token
  String stateToken = context.request.session.containsKey("state_token") ? context.request.session["state_token"] : null;
  String queryStateToken = context.request.queryParameters.containsKey("state_token") ? context.request.queryParameters["state_token"] : null;

  // Check if the token already exists for this session. 
  if (tokenData != null) {
    context.send("Current user is already connected.");
    return;
  }

  // Check if any of the needed token values are null or mismatched.
  if (stateToken == null || queryStateToken == null || stateToken != queryStateToken) {
    context.response.statusCode = 401;
    context.send("Invalid state parameter.");
    return;
  }

  // Normally the state would be a one-time use token, however in our
  // simple case, we want a user to be able to connect and disconnect
  // without reloading the page.  Thus, for demonstration, we don't
  // implement this best practice.
  context.request.session.remove("state_token");

  String gPlusId = context.request.queryParameters["gplus_id"];
  StringBuffer sb = new StringBuffer();
  // Read data from request.
  context.request
  .transform(new StringDecoder())
  .listen((data) => sb.write(data), onDone: () {
    serverLogger.fine("context.request.listen.onDone = ${sb.toString()}");
    Map requestData = JSON.parse(sb.toString());

    Map fields = {
              "grant_type": "authorization_code",
              "code": requestData["code"],
              // http://www.riskcompletefailure.com/2013/03/postmessage-oauth-20.html
              "redirect_uri": "postmessage",
              "client_id": CLIENT_ID,
              "client_secret": CLIENT_SECRET
    };

    http.Client _httpClient = new http.Client();
    _httpClient.post(TOKEN_ENDPOINT, fields: fields).then((http.Response response) {
      // At this point we have the token and refresh token.
      var credentials = JSON.parse(response.body);
      _httpClient.close();

      var verifyTokenUrl = '${TOKENINFO_URL}?access_token=${credentials["access_token"]}';
      new http.Client()
      ..get(verifyTokenUrl).then((http.Response response)  {
        serverLogger.fine("response = ${response.body}");

        var verifyResponse = JSON.parse(response.body);
        String userId = verifyResponse.containsKey("user_id") ? verifyResponse["user_id"] : null;
        String accessToken = credentials.containsKey("access_token") ? credentials["access_token"] : null;
        if (userId != null && userId == gPlusId && accessToken != null) {
          context.request.session["access_token"] = accessToken;
          context.send("POST OK");
        } else {
          context.response.statusCode = 401;
          context.send("POST FAILED ${userId} != ${gPlusId}");
        }
      });
    });
  });
}

Now the HTTP session has the full ability to make calls on behalf of the user. The /people method will be called from the client to retrieve the list of visible friends of that user.

1
2
3
4
5
6
7
8
9
10
void getPeopleHandler(FukiyaContext context) {
  String accessToken = context.request.session.containsKey("access_token") ? context.request.session["access_token"] : null;
  SimpleOAuth2 simpleOAuth2 = new SimpleOAuth2()..credentials = new console_auth.Credentials(accessToken);
  plus.Plus plusclient = new plus.Plus(simpleOAuth2);
  plusclient.makeAuthRequests = true;
  plusclient.people.list("me", "visible").then((plus.PeopleFeed people) {
    serverLogger.fine("/people = $people");
    context.send(people.toString());
  });
}

The final responsibility we can bestow upon the server is allowing the client to disconnect by revoking OAuth access.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void postDisconnectHandler(FukiyaContext context) {
  String tokenData = context.request.session.containsKey("access_token") ? context.request.session["access_token"] : null;
  if (tokenData == null) {
    context.response.statusCode = 401;
    context.send("Current user not connected.");
    return;
  }

  final String revokeTokenUrl = "${TOKEN_REVOKE_ENDPOINT}?token=${tokenData}";
  context.request.session.remove("access_token");

  new http.Client()..get(revokeTokenUrl).then((http.Response response) {
    context.request.session["state_token"] = _createStateToken();
    Map data = {
                "state_token": context.request.session["state_token"],
                "message" : "Successfully disconnected."
                };
    context.send(JSON.stringify(data));
  });
}

Thats about it, Happy Dart Hacking! Special thanks to Gerwin Sturm for putting together the original example for client side. Full source code can be found at gplus-quickstart-dart in the server folder. Please replace your own keys cause mine will be removed at some point.

April 03, 2013 02:25 AM

March 22, 2013

Adam Coding @ Github

Dart Multi Touch Canvas With Realtime APIs

Google has made the realtime api available for developers. Realtime api provides operational transformation on strings, lists, maps and custom objects. The application data gets stored on Google Drive and is available from any supported browser. This is going to be the tooling of the future for collaborative applications.

I took some time to see what it would take for implementing a sample realtime application in dart. Also wanted to make sure my sample could run on mobile chrome.

Since realtime api is new, dart bindings don’t really exist. Lucky for us we have js-interop library. The js-interop library provides communications to existing javascript code from dart. I consider this mostly a quick hack to get started with the realtime api until a more native interface exists.

The sample realtime_touch_canvas demonstrates a multi touch canvas surface that updates in realtime with all clients that have the application open.

Most of the heavy lifting is done by rtclient.dart. I ported the code from the javascript version. Its enough code to get started right away but a more structured solution should be done. The main class is RealTimeLoader used for realtime loading.

1
2
3
4
5
  rtl = new RealTimeLoader(clientId: 'CLIENTID.apps.googleusercontent.com', apiKey: 'KEY');
  rtl.start().then((bool isComplete) {
    /* RealTimeLoader has authenticated the application and is ready to load a file */
    loadRealTimeFile(fileId, model.onFileLoaded, model.initializeModel);
  });

model.onFileLoaded and model.initializeModel handle the creating of model data and loading of model data.

In the realtime_touch_canvas, model data was a simple list of json strings. The ticky part here is you need to remember that your working with the realtime api within the javascript vm. So an array needs to be allocated from js-interop.

1
2
3
4
  void _createNewModel(js.Proxy model) {
    var list = model.createList(js.array(_defaultLines));
    model.getRoot().set(_linesName, list);
  }

After the model is created we then get called to load the file. Loading the file for our purposes is binding the collaborative objects. Some tricky things to note here is we are retaining the javascript objects so we can access them after exit of the callback. Also the callbacks have to be wrapped within js-interop js.Callback.many proxy object. The callbacks _linesOnAddValuesChangedEvent and _linesOnRemovedValuesChangedEvent are fired off when the collaborative list object has items added or removed.

1
2
3
4
5
6
7
8
9
10
11
12
  js.Proxy _doc;
  String _linesName = "lines";
  js.Proxy _lines;

  void _bindModel(js.Proxy doc) {
    _doc = doc;
    js.retain(_doc);
    _lines = doc.getModel().getRoot().get(_linesName);
    _lines.addEventListener(gapi.drive.realtime.EventType.VALUES_ADDED, new js.Callback.many(_linesOnAddValuesChangedEvent));
    _lines.addEventListener(gapi.drive.realtime.EventType.VALUES_REMOVED, new js.Callback.many(_linesOnRemovedValuesChangedEvent));
    js.retain(_lines);
  }

When the callback is called the data would be in the javascript virtual machine so we can parse it and store in our native dart code. This is more of a convenience then a must do, that way we can expose plan old dart objects to our other parts of the dart application.

1
2
3
4
5
  void _linesOnAddValuesChangedEvent(addedValue) {
    var insertedLine = _lines.get(addedValue.index);
    var line = new Line.fromJson(insertedLine);
    realtimeTouchCanvas.move(line, line.moveX, line.moveY);
  }

Now when we want to store a line in the application we simply convert it to json and push it into the collaborative list. The little tick here is to make sure we are scoped when accessing the _lines object since it lives in the javascript virtual machine.

1
2
3
4
5
  void addLine(Line line) {
    js.scoped(() {
      _lines.push(line.toJson());
    });
  }

The realtime_touch_canvas is live on github gh-pages and realtime_touch_canvas source is available.

March 22, 2013 01:19 AM

March 14, 2013

Shannon -jj Behrens

Irrduino: A Sprinkler System Built Using Arduino, Android, Google App Engine, Python, and Dart

Cross-posted from Dart News & Updates.



Developers frequently ask me if Dart is ready for the real world. Well, of course, that depends on the application. Check out this short video in which Joe Fernandez and I not only show that Dart can be used in the real world, we also show that it can be used to take the tedium out of watering your lawn!



The Dart code for Lawnville was originally written in January of 2012, a mere three months after Dart was launched as a "technology preview". That was six months before Dart's M1 release, so it's been updated a few times along the way. However, the code really hasn't fundamentally changed that much since the beginning.

Perhaps the most interesting piece of code is the use of a Queue (from the dart:collection library) to schedule watering tasks. You can click on different parts of the lawn, and the droid will fly over and water each section for a short amount of time:

_actionQueue = new Queue();
...
_actionQueue.add({'action': 'water', 'zone': el.id});
...
void _executeActionQueue() {
if (_actionQueue.isEmpty) {
_waitingForTimer = false;
_idle();
} else {
var action = _actionQueue.removeFirst();
_doAction(action);
_waitingForTimer = true;
new Timer(new Duration(milliseconds: TIMER_INTERVAL),
_executeActionQueue);
}
}
A Timer and window.requestAnimationFrame are used to control animations:

void _repositionDroid(int x, int y, [Callback callback = null]) {
x -= (HALF * DROID_WIDTH).toInt();
y -= DROID_HEIGHT;
_droid.src = "/static/images/droid-jetpack-on-front.png";
_droid.style.left = "${x}px";
_droid.style.top = "${y}px";
new Timer(new Duration(milliseconds: REPOSITION_DURATION), () {
if (callback != null) {
callback();
} else {
_droid.src = "/static/images/droid-waiting-front.png";
}
});
}

void _startAnimationLoop() {
_animationStartTime = new DateTime.now().millisecondsSinceEpoch;
window.requestAnimationFrame(_animationLoop);
}

void _animationLoop(int timestamp) {
_animationProgress = timestamp - _animationStartTime;
for (Callback callback in _animationCallbacks.values) {
callback();
}
window.requestAnimationFrame(_animationLoop);
}
An HttpRequest is used to send commands to IrrduinoServer which in turn sends commands to IrrduinoController in order to control the sprinkler system:

void _waterRpc(int zone) {
var req = new HttpRequest();
int secs = (TIMER_INTERVAL * SECS_PER_MS).toInt();
req.open("POST", "/?water-zone=true&zone=${zone}&secs=${secs}", true);
req.onReadyStateChange.listen((Event e) {
if (req.readyState == 4) {
if (req.status == 200) {
window.console.log("Watering was successful");
} else {
window.console.log("Watering was unsuccessful");
}
}
});
req.send();
}
In total, the complete Dart code is about 110 lines long, not counting comments and closing braces.

You might wonder why I chose to use Dart so soon after its release, especially since I wasn't even on the Dart team at the time. I've always gotten a kick out of coding in new languages. At the time, I figured that as long as I could talk to the DOM and make XMLHttpRequests, I could do almost anything. These days, Dart is a lot more useful thanks to the growing selection of pub packages available, but even before these things existed, Dart had enough functionality to help water a lawn ;)

If you want to download the complete source code for Irrduino, you can get it from bit.ly/waterjoeslawn.

by Shannon Behrens (noreply@blogger.com) at March 14, 2013 06:08 PM

March 09, 2013

Adam Coding @ Github

rikulo stream on heroku

Tonights hacking was with stream and heroku. Stream is a Dart web server supporting request routing, filtering, template technology, file-based static resources and MVC design pattern. I just planned on serving static content from heroku using full dart based web server.

First setup the dart build pack

shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
adam@Adams-MacBook-Air:~/dart
$ mkdir stream_todomvc

adam@Adams-MacBook-Air:~/dart/stream_todomvc
$ cd stream_todomvc

adam@Adams-MacBook-Air:~/dart/stream_todomvc
$ heroku create stream-todomvc

adam@Adams-MacBook-Air:~/dart/stream_todomvc
$ heroku config:add BUILDPACK_URL=https://github.com/igrigorik/heroku-buildpack-dart.git

adam@Adams-MacBook-Air:~/dart/stream_todomvc
$ git init

adam@Adams-MacBook-Air:~/dart/stream_todomvc
$ git remote add heroku git@heroku.com:stream-todomvc.git

Creating a new project called stream-todomvc. Going to use the todomvc from the web-ui project as our content for the stream server. First thing that should be done is adding the dependencies to the pubspec.yaml file.

pubspec.yaml
1
2
3
4
5
6
7
name: stream_todomvc
description: A sample WebUI application
dependencies:
  browser: any
  js: any
  web_ui: 0.4.1+7
  stream: 0.5.5+1

Next I simply compied the existing todomvc project out into my stream-todomvc project.

shell
1
2
adam@Adams-MacBook-Air:~/dart/stream_todomvc
$ cp ~/dart/web-ui/example/todomvc/* ./web/

stream intro documentation goes over some basic configurations and settings. I’m just going to use them for now to get something running right away. The key to note when serving code from the web/ folder in dart projects is having the stream server code in web/webapp/. That way stream can find all your resources with little configuration. With very little dart code we can have static web server going.

web/webapp/server.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
library server;

import 'dart:io';
import "package:stream/stream.dart";

void main() {
  var port = Platform.environment.containsKey('PORT') ? int.parse(Platform.environment['PORT']) : 8080;
  var host = '0.0.0.0';
  var streamServer = new StreamServer();
  streamServer
  ..port = port
  ..host = host
  ..start();
}

Since this was a web-ui project we need to have a build.dart file help us with transforming the polyfill web components.

build.dart
1
2
3
4
import 'dart:io';
import 'package:web_ui/component_build.dart';

main() => build(new Options().arguments, ['web/index.html']);

The heroku environment requires a procfile configuration to let the service know the type of commands to run.

Procfile
1
web: ./dart-sdk/bin/dart --package-root=./packages/ web/webapp/server.dart

Next we build all the static data for our webapp to function. This will include calling build.dart and dart2js. The second step of calling dart2js helps with clients that do not have the dartvm built in.

shell
1
2
3
4
5
6
7
8
9
10
11
12
13
adam@Adams-MacBook-Air:~/dart/stream_todomvc
$ pub install
Resolving dependencies...
Dependencies installed!

adam@Adams-MacBook-Air:~/dart/stream_todomvc
$ dart build.dart
Total time spent on web/index.html                           -- 839 ms
Total time                                                   -- 863 ms

adam@Adams-MacBook-Air:~/dart/stream_todomvc
$ dart2js -oweb/out/index.html_bootstrap.dart.js web/out/index.html_bootstrap.dart
Using snapshot /Users/adam/Documents/DartEditor/dart/dart-sdk/lib/_internal/compiler/implementation/dart2js.dart.snapshot

Now everything should be ready for deployment.

shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
adam@Adams-MacBook-Air:~/dart/stream_todomvc
$ git add -a -m "ready for deploy"

adam@Adams-MacBook-Air:~/dart/stream_todomvc
$ git push -v --set-upstream heroku master:master
Pushing to git@heroku.com:stream-todomvc.git
Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 283 bytes, done.
Total 3 (delta 2), reused 0 (delta 0)

-----> Fetching custom git buildpack... done
-----> Dart app detected
-----> Installing Dart VM, build: latest
-----> Copy Dart binaries to app root
-----> Install packages
*** Found pubspec.yaml in .
Resolving dependencies...
Dependencies installed!
Fixed web symlink
-----> Discovering process types
       Procfile declares types -> web

-----> Compiled slug size: 8.9MB
-----> Launching... done, v7
       http://stream-todomvc.herokuapp.com deployed to Heroku

To git@heroku.com:stream-todomvc.git
   042f1f4..b35984b  master -> master
updating local tracking ref 'refs/remotes/heroku/master'

Deploying to heroku in this style is just a good starting point. web-ui and dart in general is still working on a deployment story. The URL for the stream-todomvc will contain out in its location, not very desirable. In the future a buildtool will aid the deployment story for dart.

Check out the live version of stream-todomvc with full source code available at the stream-todomvc github project.

March 09, 2013 03:16 PM

March 05, 2013

Dartcasts.com

Episode 11: An Introduction to DartMocks An introduction to...



Episode 11: An Introduction to DartMocks

An introduction to DartMock - a mock framework for Dart inspired by RSpec.

Learn More

March 05, 2013 12:42 PM

February 28, 2013

Shannon -jj Behrens

Dart on a Chromebook: Success!

I finally have a viable approach to editing Dart directly on a Chromebook running ChromeOS! The usual approach to developing Dart code on a Chromebook is to use Chrome Remote Desktop to connect to another development machine. However, I wanted an approach that would let me develop in Dart while offline, for instance if I'm giving a talk on Dart and my internet connection goes down.

Crouton is a set of scripts based around debootstrap that bundle up into an easy-to-use, Chromium OS-centric Ubuntu chroot generator. Using Crouton, I was able to create a chroot running a basic Ubuntu setup. Within the chroot, I was able to install a JDK and then Dart Editor. Everything works, as you can see in the picture. I can switch back and forth between XFCE and ChromeOS's desktop using a key combination, and everything still runs at native speed since it's just a simple chroot.

I got everything working on my wife's Samsung Series 5 Chromebook running an Intel Atom processor. I have a newer ARM-based Chromebook, but there is currently no ARM port of the Dart VM. I used the 32-bit version of the JDK and the 32-bit version of Dart Editor.

I'm pretty excited that this works because this is one of the few things that was preventing me from fully switching to a Chromebook :) Now, all I need to do is get my hands on a Chromebook Pixel!

by Shannon Behrens (noreply@blogger.com) at February 28, 2013 06:57 AM

February 25, 2013

Trials (and Errors) in Dart

New Dart:io hotness!

It's been a very long time since my last post for which I apologize. I hope to get back into Dart blogging again soon. A recent announcement on the dartlang mailing list got me excited. BREAKING CHANGE: New version of dart:io. I've been waiting for this to finally land in bleeding_edge. As a lot of my work is with command line applications. It's great seeing dart:io finally getting some love.

Now there were a few surprises that cropped up with the new version of the library. I'm going to note a couple of them I've come across so far that I've noticed. I won't get into details about ones covered in the mailing list announcement. There are a number of others that were too small to be covered there. One big thing I noticed was the removal of HttpServer.addRequestHandler as that was a quick and dirty way of setting up the basics of routing in the server. Now all requests are sent to HttpServer.listen. Similarly, server isn't started by creating a new HttpServer instance and then running listen on it, rather use a static method, HttpServer.bind on the HttpServer class which returns a Future which provides the server instance.

All of this is because the dart:io is being converted to Futures and Streams. And it is a change for the best, making the libraries consistent across libraries and API's. This has also made for some changes to some of the other classes in dart:io and just some clean up which makes sense as well.

Lets start with our eventHandler. In the past adding a RequestHandler to the HttpServer would take two arguments. An HttpRequest and an HttpResponse. The first being the request to the server and the latter being the response back from the server to the client. However, I cannot think of a situation where these two objects would not be intertwined. Apparently the dart developers felt the same way. Now, the new version of a requestHandler (see above), only accepts an HttpRequest. The corresponding HttpResponse object is a property of the HttpRequest, and can be accessed like so: HttpResponse res = httpRequest.response;

Also in HttpRequest, the uri property is no longer a string but returns a URI object. As such, the path property of HttpRequest has been removed in favour of: httpRequest.uri.path. Similarly, session is no longer a method but rather returns a full session object directly. This means that it no longer accepts an init callback to preform a specialized initialization of the session but I'm not aware of that functionality being used very frequently.

[Edit:]
One aspect that I neglected to mention earlier is that writing to the HttpResponse stream is a little easier now as well. In the past we would need to use httpResponse.outputStream.write(...) whereas now, we write directly to the httpResponse itself. For example:

var res = httpRequest.response;
res.addString(...);
// Alternatively we can also use add(List data)
// or addStream(Stream> data).
Check out the API for HttpResponse.[/Edit]

As an experiment with the new library, in particular with the HttpServer and related functionality, I created a very basic webserver example. This sample is not production usable, or even complete in any way. But I think it does provide a good introduction into how the new libraries are used and how extend the Stream interfaces to implement a very basic routing mechanism into the server. The source is available on github: sample_server. This is the basic premise that I'm now implementing in a project that I'm working on at the moment. With any luck I'll be able to extend the functionality of the server and abstract it away from the core logic I'm working on to be able to release the library for others if they are interested. In the mean time the sample_server should help you to get up and running.

One thing I do have to mention, is it was extremely easy to implement my own stream with the route by extending Stream, and just using a StreamController to provide most of the functionality. Only needed to implement the listen() method which in itself passes it on to the controller anyways. Love it!

Note: Currently this requires a bleeding_edge version, as these changes have not yet been added to the stable build. They were written with version: 0.1.2_r18836 and tested with version: 0.1.2_r18968. Details may change prior to stable release.The latest stable version of the Dart SDK has just been released and supports this API. It can be found in version: 0.4.0_r18915.

by Matthew Butler (noreply@blogger.com) at February 25, 2013 03:09 PM

February 21, 2013

Christian Grobmeier

A free book. Dart: Up and Running

Recently I got the book “Dart: Up and Running” written by Kathy Walrath and Seth Ladd. Both authors are well-known in the Dart community. Kathy is responsible for so much great docs on dartlang.org and Seth was the Dart-Ambassador since the language first faced the world (or even earlier, who knows). Definitely you want to meet at least one of them in your favorite coffee shop when you are running into Dart related trouble.

dartupandrunning

The Book itself is one of the first of its kind. Currently I know about two more Books on Dart, but thats it. As the language still progresses and changes are flowing in every day, it is a difficult matter to write a books about Dart. Kathy and Seth decided to write a short but valuable book, tailored for the busy developer who wants to get an overview on the Dart eco system. With that in mind most of the content will be valid for quite a while.

Actually you can read everything you need to get started quickly. After a brief introduction of the “whats hot” kind you’ll be introduced into the Dart syntax. You’ll see a lot of the great language features Dart supports, like named Constructors or the Cascade Operator.
The second chapter is a tour through the current Dart libraries, like for working with Isolates, HTML manipulation or I/O. It is a brief read which shows you what you can do with it, but doesn’t exhaust all possibilities. Of course a chapter on the great Dart toolset is not missing. If you ever wondered why people are so excited on Dart, this one of the reasons: the Editor and Dependency Resolver (aka Pub) is already built-in. The chapter introduces all of them and points you into the right direction when you are just starting. Finally the book ends with an example chapter.

This book is one of the kind you need to have on your desk until you know it from mind. It is an easy to read, easy to understand book which helps you to get started quickly. Don’t expect Kathy & Seth will explain object oriented paradigmas to you: it is really focused on the language itself.

If you are curious and would like to read more on the book I have some good – no GREAT – news for you. The whole book can be read online and free of charge. Just head on to the “Dart: Up and running website” and start hacking today. I also would like to mention that the books text and all source code examples are available on GitHub. You see, there is no excuse anymore. ;-)

buyfromamazoncomKindle Version


buyfromamazonde
Kindle Version

by Christian Grobmeier at February 21, 2013 08:57 AM

February 19, 2013

Shannon -jj Behrens

Dart with Google Web Toolkit

Cross-posted from Dart News & Updates.

In this episode of Dartisans, I'm going to show you a variety of ways to use Dart with Google Web Toolkit. I know that there are a lot of GWT developers out there who would like to give Dart a shot, but they aren't sure how because they already have a large, successful app that's written in GWT. I'm going to show you ways to integrate Dart into your existing GWT application without having to rewrite it from scratch.

To do this, I've built a sample application that uses both GWT and Dart. I'll show you how to setup a development environment so that you can work with both technologies. Then, I'll show you a variety of ways in which you can get GWT and Dart to interoperate, such as:
  • Using GWT and Dart to manage different parts of the same page
  • Using Dart to retrieve JSON from a Java servlet
  • Using window.postMessage and JSNI to pass messages between GWT and Dart
  • Using JavaScript, JSNI, and Dart's js package for synchronous interoperability between GWT and Dart
  • Using CustomEvent objects and Elemental to pass messages between GWT and Dart
Rather than show you a one-size-fits-all solution, I decided to show you a bunch of approaches so that you could pick the right tool for the job. Each of them has stengths and weaknesses, and I'll cover those along the way as well.

Aside from watching the video, you can also download the source code or view the video transcript.



As always, we invite you to join the discussion on the Dart mailing list, and ask us questions on Stack Overflow. Your feedback is important. Thanks for checking out Dart!

by Shannon Behrens (noreply@blogger.com) at February 19, 2013 08:38 PM

February 12, 2013

On Dart (Dzenan Ridjanovic)

February 08, 2013

Adam Coding @ Github

Dart Google Client Apis Now Available On Pub

The dart-gde team now brings you not only a generator to create google client apis but also pub.dartlang.org hosted packages. Lot of thanks goes to Gerwin Sturm for all of his hard work over the last few weeks developing discovery_api_dart_client_generator and dart-google-oauth2-library.

We plan to keep the client libraries up to date with uploader.dart script. Still somewhat a manual process, future automation could happen when/if we have the ability to get notified about google api changes. For now we will push updates when appropriate. This will ensure that we can push the latest versions of the apis to pub and still have previous revisions available. Some of the more intricate parts of this script include auto version incrementing pubspec files and syncing to github, then pushing to pub.

Would you want to contribute to this project? Please feel free to ping us Adam Singer/Gerwin Sturm on g+, we’re definitely looking to refactor some parts and test others. Our main focus for this release was to get something out the door that is pleasantly usable.

Many hours of testing and development was done to have a simple and easy way to use the google client apis in dart! We hope you enjoy and look forward to seeing what you build. To get started with client api examples check out dart_api_client_examples. The github hosted source code can be found at dart-google-apis

Full list of available Google client apis on pub.dartlang.org

February 08, 2013 10:18 PM

February 06, 2013

Kevin Moore

Dart is a great language for shell programming, too


I asked Twitter nicely yesterday. The only response:


I don't dislike writing bash scripts. I hate it. I also hate the lack of portability, as pointed out by +Daniel Steigerwald:


Great idea, +Daniel Steigerwald, but why use NodeJS when I could use Dart?

If you fetch the latest version of the Dart Bag-of-Tricks, you'll notice a new binary bin/bench.

If you're running bash and dart is in your path you can execute this directly. Otherwise run it through dart: dart bin/bench.

If you add bot.dart/bin to your path you can do things like this:
There is also a paramater -r, --run_count    (defaults to "20")

Dart is more than just a good tool for web apps.

Happy hacking.

by Kevin Moore (noreply@blogger.com) at February 06, 2013 05:32 PM

February 01, 2013

Kevin Moore

Headless Browser Testing: Dart, DumpRenderTree, drone.io

When writing any software, even for the web, I try to do as much testing as possible outside the browser.

A lot of great testing can be done of algorithms, data models, and business logic without booting up Chrome.

Node.js enabled this with Javascript. Dart has had an out-of-browser--read console--story since day one.

But some things you must test in a browser.

The Dart Bag of Tricks (BOT) has had browser tests since the beginning. There are only a few tests that must be run in the browser, but I make sure to run all tests both on the console and in the browser if they can run both places.

Browser tests are great, but they don't fit well into a build workflow or a continuous integration tool.

For that you need a way to run and control a browser (or a browser-like thing) via the console and get results out. Enter DumpRenderTree.

DumpRenderTree - Chrome without the chrome

DumpRenderTree (DRT) is a great little tool hidden in the guts of WebKit.

By default, DRT prints out an obscure text format representing the hierarchy of elements on the provided page.

Here's the output for DumpRenderTree example/fract/fract_demo.html

Content-Type: text/plain
layer at (0,0) size 808x820
  RenderView at (0,0) size 800x600
layer at (0,0) size 800x820
  RenderBlock {HTML} at (0,0) size 800x820
    RenderBody {BODY} at (8,8) size 784x804
      RenderHTMLCanvas {CANVAS} at (0,0) size 800x800 [bgcolor=#808080]
      RenderText {#text} at (0,0) size 0x0
#EOF
#EOF

DRT is controlled mostly through Javascript in the test page by via window.testRunner.

Here's the script block that lives in test/harness_browser.html:

<script>
// only run if testRunner is defined -- we're in DRT
if (window.testRunner) {

// Don't dump the structure. Just the text of the output plus console output
testRunner.dumpAsText();

// Don't finish when layout is done. Instead, wait to be notified
testRunner.waitUntilDone();

// listen for messages from the test harness
window.addEventListener("message", receiveMessage, false);

// listen for unhandled exceptions
window.addEventListener('error', onError);
}

// if there is an unhandled exception, tell DRT we're done
function onError(event) {
testRunner.notifyDone();
}

// if the test harness sends a done message, tell DRT we're done
function receiveMessage(event) {
if(event.data == 'unittest-suite-done') {
testRunner.notifyDone();
}
}
</script>

And since everything is keyed off the existence of window.testRunner, none of this affects the behavior of tests running normally in a browser.

Here's the first few lines of output from DumpRenderTree test/harness_browser.html:

Content-Type: text/plain
PASS
All 109 tests passed
Collapse All
bot
 
(4/4)
bot - Enumerable
 
(19/19)
bot - Enumerable - group

Compare to the content running the tests in the browser:


Getting DumpRenderTree

DRT is part of Linux and Windows builds of the Dart Editor now (look in the chromium) directory. It will be part of builds for Mac soon.

If you want to get DRT that is compatible with the latest integration build of Dart - 0.3.2.0 (r17657) - grab this guy.

Just make sure the DumpRenderTree executable is on your path when running tests.

Bringing it all together

drone.io supports DumpRenderTree for Dart projects. Read about it here.

The trick is creating a script that returns an exit code of zero for success and not zero (1 is pretty standard) for failure.

Check out the script I created for BOT.

And let me know how it goes for you.

Happy hacking.

by Kevin Moore (noreply@blogger.com) at February 01, 2013 03:29 AM

January 22, 2013

On Dart (Dzenan Ridjanovic)

Membership Web Components

I have created a simple membership application to explore web components in the Web UI package of Dart.

by Dzenan Ridjanovic at January 22, 2013 10:55 PM

January 11, 2013

Kevin Moore

Dart Widgets Dev Journal 1 - Basic Animations


tl;dr: Implementing features similar to Bootstrap is hard without basic animation support in Dart. Basic animation support is not as easy as you'd think. I've made a stab. Check out the demo.
I've started a new Dart project - Dart Widgets. The inspiration is Bootstrap, but with a focus on features that map cleanly to Web Components.

While digging into Bootstrap, I realized that there was a heavy dependency on jQuery--specifically the show/hide/toggle functionality. This is critical for expanders, menus, modals, pretty much everything.

Show, hide, toggle

It turns out implementing show/hide/toggle is not as easy as one might guess.

One could naively toggle display: none; in an element's style attribute and call it a day, but a lot of edge cases would be missed.

Throw in the ability to optionally animate the show/hide behavior and things get a lot more complicated.

A short list of the cases to ponder:

  • Element with a non-standard display value. (e.g. a div inherited a display of inline-block)
  • Element with a local display of none 
  • Element inherited a display of none
  • Show is called while an element is hiding and vice versa
  • Toggle is called 10 times before the first animation finishes
  • Show is called on an element with effect A while effect B is hiding it.
Huge props to the jQuery and jQuery-ui folks for tackling this problem. Their code served a great starting spot. I feel bad that they had to implement this logic in Javascript.

Test

I can't tell you how valuable test-driven development was in getting this project off the ground. It would have been next to impossible to ensure all of the edge cases were handled cleanly.

I need to write another post about how my approach to testing in Dart has evolved. Let's just say I didn't code up 939 tests by hand.
After a lot of head scratching, I think I ended up with pretty clean, extensible model.

As proof, I offer the code for doing a open/close door effect:

class DoorEffect extends Css3TransitionEffect {
DoorEffect() : super(
'-webkit-transform',
'perspective(1000px) rotateY(90deg)',
'perspective(1000px) rotateY(0deg)',
{'-webkit-transform-origin': '0% 50%'}
);
}

There are still a few things I'd like to get working--get tests working in Firefox, find a way to handle browser prefixes cleanly--but generally I'm happy with progress.

Check out the demo.

Check out the code.

Let me know what you think.

by Kevin Moore (noreply@blogger.com) at January 11, 2013 05:50 PM

January 01, 2013

Shailen Tuli

A first app with web components using Dart and Web UI library

Its time to finally create a simple hello world app using web components and the dart Web UI library.

There is already a ton of literature out there on why web components are a tremendously good idea and I won’t try to do a huge ‘sell’ here. If you are completely new to web components, I can recommend this really good introductory blog post by Seth Ladd

Or, if you are impatient, here’s an (almost) tweet sized summary: web components allow developers to encapsulate their UI elements as easily reusable components. You can define templates with markup that is inert until activated later, apply decorators to enhance the look of those templates, create custom elements and play with the shadow DOM. In this little app, we will not be tikering with decorators or the shadow DOM; we will be creating templates and defining our own custom element.

The app is called bookstore and you can find the code at https://github.com/shailen/bookstore.

Since I am new to web components and the Dart Web UI library, I am going to keep this simple. In its current iteration, the app will show the user the list of books in the bookstore and let the user add books to the collection. The plan is to start with something minimal and over the next few weeks and months build something a little bit elaborate (add Authors, Publishers, more attributes to our Book class, reviews, etc) while preserving the one-page feel of the app.

Important Files

There are a few important files in bookstore’s web directory that are worth discussing now:

lib/models.dart contains code for a Book class

web/books.html contains the basic markup for the app

web/books.dart contains the Dart code that goes with that markup

web/book_component.html contains the markup for our web component

web/book_component.dart contains the Dart code for our web component

build.dart helps use compile our code so that it can be run

We’ll discuss each of these files in detail soon.

lib/models.dart

We’re going to be creating books. This file defines a simple Book class. Our books only have 1 attribute for now, a title (I told you this was simple ;).

library models;

class Book {
  String title;
  Book(this.title);
}

web/books.html

Here is the entirety of teh web/books.html file. Consider this an entry point into the app:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Books</title>
    <link rel="components" href="book_component.html">
  </head>
  <body>
    <h1>Books</h1>

    <input id="new-book" type="text" placeholder="add another title">
    <button on-click="createNewBook()">Add Book</button>

    <ul id="books">
      <template iterate="book in books">
        <x-book-item book="{{ book }}"></x-book-item>
      </template>
    </ul>

    <!-- this is the non web-component way to create the <li>s
    <ul>
      <template iterate='book in books'>
        <li>{{ book.title }}</li>
      </template>
    </ul>
    -->

    <script type="application/dart" src="books.dart"></script>
    <script type="text/javascript" src="https://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>

  </body>
</html>

A few things to notice here:

<link rel="components" href="book_component.html">

is the way you access the contents of our web component from this file.

We create an input where the user enters the name of a book and an accompanying button:

<input id="new-book" type="text" placeholder="add another title">
<button on-click="createNewBook()">Add Book</button>

Notice the on-click? That is the way we inline an event listener: when the button is clicked, createNewBook() fires (we’ll get to that function soon)

And finally the code that actually deals with the web component:

<ul id="books">
  <template iterate="book in books">
    <x-book-item book="{{ book }}"></x-book-item>
  </template>
</ul>

A few things to note here. We define a <template> tag; we loop over our collection of books (stored in a variable books in web/books.dart); we instantiate our web component (<x-book-item></x-book-item>) and we pass each book in the loop as a template variable when we instantiate the web component.

There’s a lot going on here. Make sure you understand the above paragraph!

web/books.dart

web/books.html has a link to a Dart file at the bottom:

<script type="application/dart" src="books.dart"></script>

And here is what books.dart looks like:

import 'dart:html';
import 'package:bookstore/models.dart';

List<Book> books = [];

// binding created auto-magically!
void createNewBook() {
  var input = query("#new-book");
  books.add(new Book(input.value));
  input.value = "";
}

main() {
  // create some data so the page doesn't look empty
  ["War and Peace", "The Idiot", "Crime and Punishment"].forEach((title) {
    books.add(new Book(title));
  });
} 

It is pretty straightforward stuff: we import models.dart, the file that contains the Book class; we create a books variable to store our collection. We define createNewBook() to add a book to books, and we define a main() function.

This Dart file MUST contain a main(), even an empty one will do. In our case, we will add a few books to our books collection, so that there is some data to display.

web/book_component.html

This contains the code that defines our web component:

<!DOCTYPE html>
<html>
  <body>
    <element name="x-book-item" constructor="BookComponent" extends="li">
      <template> 
        <li>{{ book.title }}</li>
      </template>

      <script type="application/dart" src="book_component.dart"></script>
    </element>
  </body>
</html>

A few things to understand here: we create a custom <element>; we give it a name, x-book-item (all element names must begin with an x-); we call a constructor, BookComponent (defined in web/book_componenet.dart, we’ll get to that file shortly) and we declare that our custom element extends and li.

Inside our <element>, we create a <template> that stores the <li> that contains a book’s title.

And finally, we link to the accompanying Dart file, book_component.dart.

web/book_component.dart

Here we get to define our BookComponent class (remember that we declared that the <element> we created in book_componenet.html use this constructor?):

import 'package:web_ui/web_ui.dart';
import 'package:bookstore/models.dart';

class BookComponent extends WebComponent {
  Book book;
}

BookComponent extends WebComponent (this is the only option for subclassing at the moment; that may change in the future) and contains a book attribute (this can be set using the book = syntax when the web component is initialized). That’s it.

build.dart

import 'package:web_ui/component_build.dart';
import 'dart:io';

void main() {
  build(new Options().arguments, ['web/books.html']);
}

To actually build the project, run build.dart (this will create an out directory); then run web/out/books.html.

pubspec.yaml

The app only has a single pub dependency, web_ui:

name: bookstore
description: A sample app to demonstrate the use of a web component

dependencies:
    web_ui

Summary

This is a fair bit of code for a simple hello-world caliber app. Is all this web component stuff really necessary, or is it overkill?

We’re just starting out, so this may seem like too much of a production given what the needs of our app. But we have already established a pretty important development principle: our UI elements can be nicely ENCAPSULATED (!) and then used as necessary. We have taken the first baby steps towards creating a widget that displays the content of each book. As our application grows in complexity, our ‘widget’ will become more elaborate and we will want to use it in all sorts of different contexts in our app. A composable, encapsulated UI component - a web component - that can be instantiated with varying arguments will then prove to be quite useful.

January 01, 2013 01:54 AM

December 31, 2012

Shailen Tuli

setting up continuous integration for dart using drone.io

Creating a dummy project

I created a very simple project, droneDemo, to show how to set up Continuous Integration on drone.io for Dart projects. The code can be found here on Github.

droneDemo defines just two methods, add() and multiply(). These can be found in lib/. Tests for these methods can be found in test/. The pubspec.yaml file needs to declare a unittest dependency for these tests to work.

This is about as simple a project as you can have and there is little need for explanation. But it is worth delving into 2 points:

1) You should add packages to your .gitignore. This is to tell git not to commit the symlinks created by pub to version control. These symlinks are meaningful in the context of your filesystem but will trip drone.io.

If you already started your demo project and ended up with the symlinks, remove them.

2) drone.io needs a way to run all your tests. So far, Dart does not ship with a test runner, so you’ll have to cobble together something yourself.

Here’s what I did: my tests live in 2 different files, test/add_test.dart and test/multiply_test.dart. I declared both files as libraries (see the library add_test; and the library multiply_test; declaration at the top of each file) and imported components from them into test/test_runner.dart.

import “package:unittest/unittest.dart”; import “add_test.dart” as add_test; import “multiply_test.dart” as multiply_test;

void main() {

 add_test.main();
 multiply_test.main();

}

So, calling dart test/add_test.dart or dart test/multiply_test.dart runs only one test; calling dart/test_runner.dart runs both the tests.

With this out of the way, we can shift our attention to drone.io.

Drone.io: Basic Setup

Set up account at https://drone.io/signup.

On your dashboard, click on the New Project on the top right.

Pick Dart as the project language.

Pick Git as your Repository type.

Add the project name (I added droneDemo).

Add the Repository URL (mine was https://github.com/shailen/droneDemo.git). Make sure your github repo is set to use the http method, not the ssh method.

Press Create.

Configuring your Build

After you press Create, you will be redirected to the script/config page. Here, you will have to tell drone.io how to run your tests.

In the Commands section, type the following:

pub install
dart test/test_runner.dart

Remember test/test_runner.dart was our consolidating test runner? This is where the trouble we went through sewing our tests together pays off.

Press Save and when you get the message that tells you the build was successfully saved, press the blue Build Now button at the top.

A popup will appear with a Build Output link. Click that link.

Voila! You are swimming in a sea of green!

My build output can be seen at: https://drone.io/shailen/droneDemo/1

Setting up Continuous Build

Click on settings for your drone.io project

Click on General in the left column. You will see a couple of links under Build Hooks. Copy the top one.

Now, go back to your project on github. Mine is at https://github.com/shailen/droneDemo.

Click on Settings.

Click on Service Hooks (left column).

Click on the WebHook Urls link at the top.

Paste the build hook you had copied earlier in the text input box provided and press Update Settings.

From now on, every time you commit to your project on github, drone.io will run all your tests.

I changed one of my tests so that it was failing and pushed to github. No surprise, the build now show Failed (https://drone.io/shailen/droneDemo).

December 31, 2012 10:58 PM

December 24, 2012

Dart: Terra Incognita (Ladislav Thon)

Surprise me!

Looks like I’m clearly unable to write often (or at least more often :-) ), so I’ll instead try to focus on interesting stuff. Today, let’s take a look at some features in Dart that might be surprising. And since I wrote about the cool features earlier, today I’ll write about those that are … not so cool. Or bad, actually. Yes, each programming language that tries to hit the mainstream has to make compromises, which obviously leads to some kind of language smell (is there such a thing?). And Dart has particularly bad starting position, because it wants to compile to efficient JavaScript – and that is really huge constraint. So here comes the disclaimer: I’m writing this to point out some potential pain points, not to offend anyone (and especially not to say that Dart is bad, other languages would have much longer list!). Always remember the constraints Dart needs to fit into when judging.

All that said, let’s start.

Strings

What? Oh yeah, strings. Strings in Dart used to be sequences of Unicode code points. If that doesn’t make sense to you, that’s fine, it doesn’t have to. It essentially means that strings were comprised of characters. This was even in the M1 version of the specification (0.12).

It isn’t true anymore. It was changed, as you can find in revision 14357 and in the M2 version of the spec (0.20). Right now, strings are sequences of UTF-16 code units. What does that mean? If you imagine a string as a sequence of integers (which it essentially is, under the hood), the original version meant that single character was always represented by a single integer (Dart VM was clever about it and if all the characters fit into 8-bit integers, it used 8-bit integers for that; if not, then maybe 16-bit integers, and if even that wasn’t enough, then 32-bit integers). And this isn’t correct anymore – single character can still be a single integer (when the character belongs to the Basic Multilingual Plane), but it can also be two integers (characters from Supplementary Planes). These two integers together form a so called surrogate pair, and everytime you work with strings, you need to remember about them. Which is obviously a major source of programming errors – and I honestly believe that programmers making these errors shouldn’t be blamed. Who is guilty is the Unicode Consortium, which created the major abomination that UTF-16 is. It should really never have seen the light of day.

But sadly, it’s here witht us, and a lot of legacy software use it (Java, JavaScript, WebKit etc.). I was very sad to see this coming to Dart as well, but it was necessary for two reasons: compilation to JavaScript (otherwise Dart would need to implement strings on its own, which would probably perform badly) and integration of Dart VM with WebKit (before this change, each interaction with the DOM resulted in string conversions, again hurting performance).

Integers

Not really?! Oh yes. Dart has arbitrary precision integers, which is a very cool thing (you can work with arbitrarily big integers, as long as they fit into the heap) and also a big pain when compiling to JavaScript. You see, JavaScript only has one numeric type – double precision floating point (see IEEE 754). Which means that Dart doubles map naturally to JavaScript numbers, but Dart ints must somehow be implemented on top of them. And this implementation … is incomplete right now. It is probably the biggest difference between native Dart VM and Dart compiled to JavaScript, so take care.

Booleans

Now I’m surely kidding, right?! No, I’m not. Dart has a distinct bool type with two values, true and false, all nice and dandy, but it also features a boolean conversion. That is an infamous thing in a lot of dynamic programming languages, even those strongly typed, and I’d argue that it’s essentially bad. But in most languages that have it, it is actually useful – truthy and falsy values just make sense (the number zero, empty string, null, maybe empty list or map, all those can be used as a falsy value, anything else is truthy). Not in Dart. Dart only has one truthy value – the object true. Everything else is false. Which essentially means that the boolean conversion is useless – but it’s still there (apparently because it makes compilation to JavaScript easier). Just forget about it and you’ll be safe, but I’d wish it just disappeared. It doesn’t make any sense.

Collections

Am I trying to say something terrible about each of the basic types? I’m not, it just so happens. What is the problem with Collections? Their equality (and hash code). Or actually, the lack thereof.

If you think about it for a minute, it’s actually pretty hard to sensibly define equality and hash code for lists that can change its content during their lifetime. (What if you put an object to a map and use a mutable list as a key? If you later change that list, you won’t be able to use it again to lookup the object back from the map.) So Dart library designers decided not to base equality and hash code of collections on their content, but only on their identity. It has one tiny drawback, though: 1 == 1 is true, but [1] == [1] isn’t. That’s just plain wrong. The same applies to maps and sets.

Luckily, the library will probably contain functions to compare collections according to their content. So that’s at least something.

Nulls

That’s a joke, really. null is just fine in Dart. It doesn’t even throw the infamous NullPointerException but the nice old NoSuchMethodError.

Oh, and Merry Christmas to all Dartisans! :-)

December 24, 2012 08:00 AM

December 10, 2012

Shailen Tuli

Randomness in Dart: nextBool(), nextInt(), and nextDouble()

The Random class in dart:math contains 3 methods, nextBool(), nextInt() and nextDouble(). To use Random, you will need a import 'dart:math in your code.

nextBool()

simply returns true or false at random. Here is a little function, randUpcase() that demonstrates randBool() use. randUpcase() takes a string as an argument, and converts each character in the string to uppercase if random.nextBool() is true and leaves it untouched if it is false.

String randUpcase(String s) {
  Random random = new Random();
  List<String> chars = s.split('');
  return Strings.join(chars.map(
    (char) => random.nextBool() ? char.toUpperCase() : char), '');
}

And here is some sample usage:

var herbs = ["parsley", "sage", "rosemary", "thyme"];
print(herbs.map((herb) => randUpcase(herb))); // [pARslEY, SaGE, roSEMaRY, tHYME]

nextInt()

takes a max int argument and generates a positive int between 0 (inclusive) and max, exclusive.

To generate a random int within a range, you can do something like this:

int randRange(int min, int max) {
  var random = new Random();
  return min + random.nextInt(max - min);
}

You can also use nextInt() to randomly shuffle a list (using the familiar Fisher-Yates-Knuth algorithm):

List shuffle(List items) {
  var random = new Random();
  for (var i = items.length - 1; i > 0; i--) {
    var j = random.nextInt(i);
    var temp = items[i];
    items[i] = items[j];
    items[j] = temp;
  }
  return items;
}

You can use it like this:

var items = ["fee", "fi", "fo", "fum", "smell", "Englishman"];
print(shuffle(items)); // [fo, smell, fum, Englishman, fee, fi]

nextDouble()

generates a random floating point value distributed between 0.0 and 1.0. Here is a little function to simulate a biased coin toss; the percent argument alters the percent a coin will return heads (‘H’). This is pretty much cribbed from this discussion on Stack Overflow:

String flip(num percent) {
  Random random = new Random();
  return random.nextDouble() < percent ? 'H' : 'T';
}

And here is some code to test that it works:

int n = 1000;
int heads = 0;
for (var i = 0; i < 1000; i++) {
  if(flip(.20) == "H") heads++;
}
print(heads/n); // 0.209, 0.196, etc.

December 10, 2012 10:36 PM

December 08, 2012

Dart: Terra Incognita (Ladislav Thon)

Getting Dart from Git

I originally started to write this as a post on Google+, but I quickly found out that it’s a little longer and that it maybe warrants a full blog post. Here it is.

A small confession first: I have always been frustrated with building Dart from source.

First, Subversion is dead. Noone can expect me to participate on a project with Subversion. I want git and I want it now. Fortunately, the official page with instructions for getting the source also mentions git svn.

Second, git svn is a terrible idea. Every now and then, git svn fetch && git merge git-svn ended horribly for me and I really couldn’t repair the checkout. Luckily, we have two git mirrors of Dart: the primary one in Chromium Git repository and even one on GitHub (which is actually mirrored from the Chromium Git repository).

Third, Dart uses Google-specific tools for getting dependencies (Depot Tools) and building the code (GYP for generating makefiles + some hand-written scripts to invoke them). And in case of Dart, their configuration expects the SVN structure. Which means that if I clone Dart repo from one of those Git mirrors, I’m screwed. The structure doesn’t match. I have to live with those tools somehow, if I don’t want to create a new build system for Dart (which I don’t).

I got really fed up with this and spent few hours today (yes, hours!) trying to make a stream-lined process for getting Dart from Git and building it without issues, without higher-order wizardry and without special custom scripts. And I believe I’ve got one. Only a single, one-time, small and localized change… not bad. Here’s the process.

Initial setup

  1. git clone https://git.chromium.org/git/external/dart/bleeding_edge.git repo (if you forked Dart on GitHub, use a GitHub URL)

  2. cd repo

  3. gclient config http://dart.googlecode.com/svn/branches/bleeding_edge/deps/all.deps

  4. The previous command will create a .gclient file with a tiny configuration. Make this small change:

     @@ -4,6 +4,7 @@
          "deps_file"   : "DEPS",
          "managed"     : True,
          "custom_deps" : {
     +      "dart": None
          },
          "safesync_url": "",
        },

    Doing this, I’m overriding one of the instructions in the original DEPS file that says to clone the dart directory from SVN. I don’t need to do that, I’ve already got it from Git. All the other dependencies will still get cloned from SVN, but I don’t really care about those.

  5. gclient sync

Everytime I want to update

In the repo directory:

  1. git pull (or git fetch and git merge, you know know the drill)
  2. gclient sync && gclient runhooks

Building it is simple then

Just run ./tools/build.py in the repo/dart directory. No changes in this.

I wish I wouldn’t have to do all the crazy dance, but I think I can live with it. Nice thing is that this procedure is pretty similar to the official one.

P.S.: for easier work, I just added these entries to .git/info/exclude:

/.gclient
/.gclient_entries
/all.deps/

December 08, 2012 08:00 AM

December 07, 2012

Shailen Tuli

Running Only Some of Your Dart Tests with filterTests()

The Dart unittest library allows you to run just a single test; to do so, just change the call for that test form test() to solo_test().

Another way to run a subset of your tests is by using the filterTests() function. filterTests() takes a String or a RegExp argument and matches it against each test description; if the description matches, the test runs, otherwise, it doesn’t.

Before you use filterTests(), you need to disable the automatic running of tests (set autoStart to false) and ensure that the your configuration is initialized.

You can do this by creating a custom configuration:

import "package:unittest/unittest.dart";
import "package:args/args.dart";

class FilterTests extends Configuration {
  get autoStart => false;
}

void useFilteredTests() {
  configure(new FilterTests());
  ensureInitialized();  
}

Then, you can call useFilteredTests() in your main(), define all your tests, call filteredTests() with a string or regexp argument and run your tests using runTests():

void main() {
  useFilteredTests();

  // your tests go here

  filterTests(some_string_or_regexp);
  runTests();
}

Here is a little working example:

void main() {
  useFilteredTests();

  test("one test", () {
    expect(1, equals(1));
  }); 

  test("another test", () {
    expect(2, equals(2));
  });

  test("and another", () {
    expect(3, equals(3));
  });

  filterTests('test');
  // filterTests('another');

  runTests();
}

filterTests('test') will run the first 2 tests; filterTests('another') will run the last 2 tests.

It is easy to make this considerably more useful by getting the argument to filterTests() from the command line. That way, you can control what subset of tests to run without having to change the code in your test suite. Here is a slightly expanded version of the same example:

void main() {
  useFilteredTests();
  ArgParser argParser = new ArgParser();
  Options options = new Options();
  ArgResults results = argParser.parse(options.arguments);
  List<String> args = results.rest; // get the args from the command line

  test("one test", (){
    expect(1, equals(1));
  }); 

  test("another test", (){
    expect(2, equals(2));
  });

  test("and another", (){
    expect(3, equals(3));
  });

  // we add a group() to show how we can easily run just the tests
  // contained in it
  group("foo", () {
    test("this", (){
      expect('bar', equals('bar'));
    }); 

    test("that", (){
      expect('baz', equals('baz'));
    });
  });

  if (!args.isEmpty) {
    filterTests(args[0]);
  }
  runTests();
}

You can run the tests from the command line by using the

`dart name_of_file.dart [keyword]`

syntax. If the keyword is this, only one test will run. If the keyword is foo, all tests in the group() with the description of foo will run. If you do not provide a keyword, all 5 tests will run.

December 07, 2012 06:00 PM

November 26, 2012

Christian Grobmeier

Dart talk in Stuttgart – the Slides

On 22.11.2012 I was guest of the Java Usergroup in Stuttgart. It was a fun evening, with a lot of discussion on Dart. Here are the slides which I used:

What have I learned from that evening?

Not everybody likes JavaScript

First, there are still a lot of people who don’t like JavaScript. OK, I asked Java developers who are not known for their love to JavaScript. But after all, this group contains a lot of people. Some might say, they have not understood JavaScript very well and can’t judge. Well, that might be true. But this is not what counts. People often don’t have the time, the energy or the budget to learn things for which they need to make a complete refactoring of their minds. And this is often the case if you have programmed Java for a long while and suddenly turn to JavaScript. It happened to me back then, I know what I am speaking of.

JavaScript has its benefits – I myself like JavaScript meanwhile (except the quirks of course). I have invested a lot of time to learn about it. Still I am not a master, but I can survive. That’s fine. But it took me a lot of time and sometimes I was near to grief. Lucky me, I have found Stoyan Stefanovs excellent book “JavaScript Design Patterns” which is not only well written but also helped me to really get started.

Dart addresses the heavy learning curve. It seemed to me the audience liked the new flexibility which comes with Dart, compared to Java. And that they could still think in “old patterns” and use for example Classes. And that the syntax was so freaking familiar.

People don’t like experiments so much

Second, people were concerned whether Dartlang is an approach one needs to follow or if is just an experiment among thousand others.

JavaScript is everywhere. Why should one learn about Dart? It is easy to learn but you still need to read some docs and play around with the language – it costs you time.

There is a dart2js compiler, which lets you build your Apps right now. If Dart would become accepted by the masses is unknown to me. But I suspect there will be something “happen” in combination with Android.

Jochen Wiedmann summed up what I think on Android thing:

Had the pleasure to attend an interesting talk, organized by +JUG Stuttgart and given by +Christian Grobmeier on #Dart . Most appealing, in particular, a theory proposed by Christian: In order to resolve the chicken and egg problem that Dart’s not in widespread use, because the Browsers don’t support it natively, and vice versa, (and for a number of other reasons), Google might make Dart a first-class-citizen of Android: In other words, create a bridge between Dart and Dalvik that would allow to write Android Apps in Dart.

Well, that MIGHT be true. But I am not a Googler nor do I have insider information. It just makes… sense.

Using dart2js is not so elegant as running Dart in a native browser VM. With Roadcrew.js I found out that the generated JavaScript would take 200kb space, while writing JavaScript on my own + the jQuery library would only take only 100kb.

But Dart is still young and dart2js will optimize with time. And for just 100kb more (web fetishists will say its unbelievable huge and not acceptable) you get readable, maintainable code with great tooling which even the Java developers in your team can understand.

Java Usergroup Stuttgart - Dart Talk

Java Usergroup Stuttgart – Dart Talk

At the moment I do not use Dart in production. It is still changing to much. While the base syntax might be “pretty” stable, the libraries are undergoing a refactoring at the time of this writing which last for – i am guessing – 1 year or so. But once Dart is stable, I will surely start using it in production. Let us hope it this date is not so far away.

A nice evening

All speculations. What is real and fact: the evening was nice! The whole usergroup is organized in an excellent way. You would even get some snacks. And the location is wonderful. I simply decided that I will need to visit this beautiful city at daylight. Here is an unsharp photo of it. Sorry, but my Android phone wouldn’t make it better. For sure I will visit Stuttgart again – it is a great community over there.

NOTE: I have been asked if there was only one or two persons attending. That photo has been taken BEFORE the talk :-) In fact, around 40 people were there.

by Christian Grobmeier at November 26, 2012 08:32 AM

November 23, 2012

John Evans

Buckshot Now Supports Namespaces

Following on the recent mini-announcement on G+ that Buckshot is now a multi-platform library , I'm happy to also announce that Buckshot templates now support namespaces (in fact they require it).  Using namespaces provides several benefits:

  • Better visual identification of the template's target platform.
  • Element name collision avoidance.
  • The framework can better help identify misuse of elements within a template (namespace mismatch).
  • Sets up eventual support for multi-platform targetting withing the same application (HTML + SVG for example).

Introducing the "Template" Element

The addition of namespaces also introduces a new core element to the framework: "Template".  Template is essentially a non-visual element that is used to declare namespaces.  Yes you can declare namespaces directly on elements themselves, but this can get a bit messy.  "Template" provides a uniform way of declaring namespaces and is quite useful in a few specific scenarios.  Let's take a look at how this works:


Now lets say we have a library which defines some custom elements, and these belong to a namespace called 'http://buckshotui.org/sprockets'. We can include these elements using a named namespace declaration:


Ok, But Why?

To illustrate one example of the usefulness of namespaces, lets switch platforms and show a template from the (still experimental) SVG platform:

The default namespace tells Buckshot template engine to only accept elements in the template that are part of the SVG platform library.  This also gives a good visual indicator to anyone looking at the template that, aha, this is targetting SVG.

Other Places to Use Namespaces

Essentially any time you want to declare a template using platform-specific elements (non-core elements), you will need to also declare a namespace.  This applies to deferred templates such as the ItemsTemplate component of an CollectionPresenter.  Let's see what that looks like:

You might ask why the namespace for the ItemsTemplate isn't implicit since the template is declared within an CollectionPresenter. Good question! For now, explicit namespacing is required for deferred templates, but this may change in the future.

Go Get It!

Namespace support is now available in the Buckshot core library and in the HTML and SVG (still experimental at the time of this post) platform libraries.  Give it a try and let me know what you think.  Here are the links:



by John Evans (noreply@blogger.com) at November 23, 2012 10:46 PM

November 16, 2012

Kevin Moore

Excited to see dart2js minified output getting smaller (real world numbers below)



I noticed r15005 turns on more renaming in dart2js with --minify so I thought I'd see the impact on Pop, Pop, Win!

The last time I did a build and deploy of PPW was on r14873.

Here are the sizes of game.dart.js

dart2js617,201 bytes
closure compiler621.07KB
gzip (via http)107.7KB

Notes:
  • dart2js is running with the --minify flag
  • I'm using the closure-compiler with default settings. Build from 17 Sept, 2012
  • Notice how the output is bigger from closure? This is because output is optimized for gzip. Not intuitive, until you see the network panel in Chrome Dev Tools.
  • gzip is the size Chrome sees over the wire. Most servers gzip payloads. It's critical to pay attention to this number and not just the size on disk.


Now with the bleeding edge build r15005

dart2js451,183 bytes~33% smaller
closure compiler388.71 KB~37% smaller
gzip (via http)90.2KB~16% smaller


Notes:
  • The output from dart2js is substantially smaller. This is just the work from the dart2js guys recently. Amazing.
  • This time the output from the closure is smaller than the input (~12%). I can only speculate why. Perhaps the new minified output is more optimizable?
  • The gain with gzip is not as big (~16%). I'm not surprised by this. PPW is a pretty big game. The json that stores the texture data alone is huge.

Keep in mind, the Dart source for the game is 1.5 MB as reported by dart2js.
info: compiled 1576654 bytes Dart -> 451183 bytes JavaScript in web/game.dart.js
Is it fair to say we're getting ~94% smaller output? It depends on how valid one considers the the Dart code size reported by dart2js.

But I certainly don't feel I need to justify the javascript output size for non-trivial apps anymore.

Great work folks!

by Kevin Moore (noreply@blogger.com) at November 16, 2012 02:58 PM

Christian Grobmeier

Roadcrew.js – Page switching like a Boss.

When I started with mobile development I had only limited time available. The app should run on Android and iOS phones at the same time and therefore I looked into Apache Cordova and jQuery mobile. While the first one is enabling you to do mobile development with JavaScript and HTML5 in general (including hardware access), jQuery mobile is more or less a Widget factory and a framework to build your Apps. While jQuery mobile looked pretty nice it had one major drawback: it was slow as hell and way to complex to develop (for what it does). I need to add that I have used the versions before 1.0 and everything might be better meanwhile. But back than, it was like that.

There were two things I loved on jQuery mobile. One was it’s look. And the other thing was the “single page” approach. It meant, you have all your App HTML basically in one file, showing only the parts which are necessary.

When replacing jQuery mobile I used Twitter Bootstrap. Today I would probably look into Ratchet.

For the page switching I didn’t find anything, so I decided to write some code myself. Because I listened to “We are the Roadcrew” from the great Rock’n'Roll band Motörhead and “Roadcrew” is a pretty great name for mobile things, I simply named it like that: Roadcrew.

You can find more information on the official Roadcrew-Website. Or you start with cloning Roadcrew from Github.

How does it work?

It is pretty simple: include the Roadcrew.js files and make up your HTML, like for example:

<div class="page start" id="login">
...
</div>
<div class="page" id="content">
...
</div>

Every div which is a page, gets the “page” class. A page is basically the div which is shown on your mobile. You could also say “view” to it. Every page gets an ID. This is used to navigate between your pages. For example, if you want to show the “content” page, you would make up an link like:

<a href="#content">Leads to content</a>

To make this basic navigation work, you only need to make an instance of Roadcrew:

$(document).ready( function() {
   var roadcrew = new Roadcrew();
}

This is jQuery code. And in fact Roadcrew.js uses jQuery. I will try to reduce the dependencies to a minimum in future and hopefully I can make it work with Zepto.js. But for now you have to live with jQuery, which is said to be slower on mobiles than Zepto. Patches welcome!

Intercepting – show a loading page

On thing which really didn’t work well with jQuery mobile was to show a loading page. This is dead simple usually, but was forced to waste a lot of time to deal with it. In Roadcrew it’s pretty simple. You simply need to create an interceptor – something which is done before the actual target page is called.

It could look like that:

roadcrew.intercept('#interceptingPage', function(dispatch) {
   roadcrew.flip('#loadingPage');
   $.post('ajax/test.html', function(data) {
      dispatch();
   });
});

While the “flip” method just “flips” pages around, bypassing every potential interceptor, the dispatch() function argument is what you can think of “showing the actual target page”. With the code above you would show the loading page which is then visible until $.post is ready and calls the dispatch() function.

Call to arms: Error Handling

If your interceptor causes an error, you might want to have an error handler waiting for you. You can pass it on when registering your interceptor.

roadcrew.intercept('#troublePage', function(dispatch) {
   throw new RoadcrewError("I made trouble");
}, function(error) {
   $('#errorPage').find('.error').html(error.message);
   roadcrew.flip('#errorPage');
});

As you can see, I throw an error in my dispatcher. The second function is my error handler which will work with the error handler.

There is also a chance to define a global error handler, which deals with every error.

Dart port available

I ported Roadcrew to Dart. Dart is a great new language for the web. It is still a pretty young language and not so widely spread yet. Consider this port an experiment. If you want to compare JavaScript to Dart Code you might find this interesting too.

I will create a blog post on Roadcrew.dart and my experiences on the port when I find some time.

Future

The current implementation is pretty small and it gives me everything I need. But I have already seen some things which might be useful for others. For example, there is no transition animation so far. It should be pretty easy to implement such a thing, I just didn’t do it. If you want to help me, send me a patch.

As already mentioned I would like to support Zepto.js.

There is now way to load new divs by AJAX. Currently I am unsure if this would just blow up the code or if it is really useful.

And finally I need to say that there is always room to improve the current code itself.

That all said, I hope that you’ll find it useful. If you have some feedback, let me know – either by mail or – if appropriate as feature wish or issue in the issue tracker.

by Christian Grobmeier at November 16, 2012 11:02 AM

November 01, 2012

John Evans

Dart Metadata Is Your Friend

Metadata is a recent feature addition to the Dart language.  The Dart SDK already includes a few metadata tags that (integrated with the Dart Editor) can help you catch common errors, and alert users to deprecated code.  In this post, we'll see how to use the two metadata types included in the SDK: '@deprecated' and '@override'


What Is Metadata?


Metadata is essentially a piece of information that can provide additional context to your code.  This information can be used by tools such as Dart Editor, and eventually by your own code via mirror-based reflection.

According to the Dart Specification "Metadata can appear before a library, class, typedef, type parameter, constructor, factory, function, field, parameter, or variable declaration and before an import or export directive."

Using The Dart 'meta' Library


Since this is a package library, you'll need to add a reference to it in your application pubspec, and then run pub install (see pub.dartlang.org for more information about this process).  Once available, you can import the library like so:

 import 'package:meta/meta.dart';  

Now that the metadata types are in scope for your app, it's time to put them to good use!


Using the @deprecated Metadata Type

Let's say you have a class for a function that you no longer want users of your library to use.  By marking your object with the @deprecated tag, the Dart editor will strike-through any references to it, giving a great visual clue to the developer that they should use a new approach.

First lets look at our function before @deprecated is applied:

Suddenly foo() isn't so cool anymore and we want to let users of the library know about it.  Let's add the @deprecated metadata and see what Dart Editor does:

Notice how Dart editor strikes through not only the implementation function, but also any references to that function.  Neat huh?  The editor also gives other visual clues, such as an informational message and a squiggly underneath the reference.


Using the @override Metadata Type

Now this one I really like, because it's actually helped me catch a few inheritance-related bugs in my code.  Let's look at this example where we have a class Bar which inherits from a class Foo, and Bar wants to override some methods in Foo:


By using the @override metadata type, we can see that the editor is helping us identify a problem in our Bar class, where we have a typo in the override class name.  Notice how we get no help on the 'donothing()' method in Bar, when we probably wanted to override 'doNothing()' in Foo.

In larger, non-trivial applications these kinds of bugs can be nasty to track down, if you consider that this code...

 new Bar().doThat();  

...will happily execute and give you a result of "doThat" from Foo instead of the expected "Do that other thing." from Bar - leaving you with clenched fists and pulled hair as you try to trace down the problem..  In short, using @override every time you expect to be overriding a superclass method will help you avoid a whole class of bugs in your code.

Summary

Dart's metadata functionality is still in early days, but already proves quite helpful when combined with tools such as the Dart Editor.  Liberal use of @deprecated and @override will go along way toward making your code easier to work with and troubleshoot.  Give it a try in your code today and give your feedback to the Dart team.

References:
http://news.dartlang.org/2012/07/draft-spec-changes-for-metadata-in-dart.html
http://www.dartlang.org/docs/spec/latest/dart-language-specification.html#h.d0rowtffuudf

by John Evans (noreply@blogger.com) at November 01, 2012 06:07 PM

October 05, 2012

John Evans

Common Dart Scenarios for the 'Future' API

A Future<T> object represents a unit of work that will complete at some point in the - you guessed it - future.  I use Futures a lot in my code and I thought that rather than do an exhaustive walk-through of the class itself, I'd share some of the more common patterns and concepts that I often find useful.

In Future Does Not Mean In Parallel

If you come from the .net world, you'll probably have some experience with Task<T> and the whole parallel processing API.  Futures aren't that.  They are more like structured callbacks, which will almost always run in the same memory space and thread as your application.  They won't run in their own threads or multi-core on their own.  If you're interested in parallelism, consider exploring Dart's Isolates API.

Futures Are Not Automatically Asynchronous

At the time of this writing, there is a ticket open in the Dart queue to make all futures asynchronous, but for now what you are about to read remains accurate.

It is important to understand that Futures are not necessarily asynchronous by default. Let's look at this example:
 // This future is not asynchronous and will complete as soon as it is called.  
Future<bool> greaterThan42(int number){
final c = new Completer();
c.complete(number > 42);
return c.future;
}

This above code is synchronous, in fact you can write it in a much more succinct way using the .immediate() constructor of the Future class:
 Future<bool> greaterThan42(int number) =>  new Future.immediate(number > 42);  

Futures are really most powerful when dealing with asynchronous work, lets use the Timer class to simulate that here:
 Future<bool> greaterThan42(num number){  
final c = new Completer();

void doWork(_){
c.complete(number > 42);
}

// take 3 long seconds to return our result
new Timer(3000, doWork);

return c.future;
}

The example above uses the Timer asynchronously callback a function after a 3 seconds has elapsed.

A Couple Of Common Future Scenarios

Waiting For One Or More Futures To Complete

The futures API provides a very convenient way to deal with this scenario, in Futures.wait().  Lets see how it works by modifying our greaterThan42 future a bit.
 Future<bool> greaterThan42(num number, int howLongMs){  
final c = new Completer();

void doWork(_){
c.complete(number > 42);
}

// take 3 long seconds to return our result
new Timer(howLongMs, doWork);

return c.future;
}

main(){
Futures
.wait([greaterThan42(5, 1000), greaterThan42(100, 3000)])
.then((List<bool> results){
print(results);
}
}

So what is happening above when we send a list of 2 futures into Futures.wait()?  Well, it waits!  It does all the mundane work necessary to be sure that all the futures in the list have completed.  It then itself returns a Future, containing a list of the results returned by the Futures we were waiting on.

The results of running the above code will yield:
 [false, true]  

Similar to this, we often need to iterate over a list of objects, where a method in each object returns a future. Dealing with this in a standard iteration construct won't work cleanly,  because the iteration will continue happily along whether or not our future has completed.  We can use Futures.wait() and a .map() to deal with this nicely:
 main(){  
Futures
.wait(listOfFoos.map((foo) => foo.callFutureMethod()))
.then(results){
// now we can safely iterate the results of the future calls
results.forEach((bar) { // ... });
}
}


Working with Futures in Sequence

Often times we want to receive the result of some Future, and then pass that result into another Future.  Do this 4 or 5 times and you get a really nasty scaffolding effect:
 callFutureA()  
.then((resultA){
callFutureB(resultA)
.then((resultB){
callFutureC(resultB)
.then((resultC){
print('Kill me now!');
});
});
});

Fortunately, the Future API gives us a nice way to deal with this as well, with Future.chain().  Future.chain() takes some result and then returns another future, such that you can keep your control flow flat:
 callFutureA()  
.chain((resultA) => callFutureB(resultA))
.chain((resultB) => callFutureC(resultB))
.chain((resultC) => callFutureD(resultC))
.then((resultD){
print('Wait, don't kill me after all!');
});

Furthermore, if you are just doing a simple transforms on a future, you don't have to wrap all of your transformational functions in Futures.  You can use the Future.transform() function to achieve the same result:
 futureA(String foo) => new Future.immediate('$foo A');  
functionB(String foo) => '$foo B';
functionC(String foo) => '$foo C';
functionD(String foo) => '$foo D';


main(){
futureA('Transform me!')
.transform(functionB)
.transform(functionC)
.transform(functionD)
.then((result) => print('$result'));
}

Yields:
 Transform me! A B C D

Now, I could go off on a tangent here about the need for an await keyword in Dart, and how that would make dealing with asynchronous control flows even more simple to work with, but I'll save that for another post (maybe).

Summary

The Future API provides a great way to manage asynchronous coding in Dart.  Smart use of the API will keep your asynchronous code well managed and readable.

by John Evans (noreply@blogger.com) at October 05, 2012 08:15 PM

October 02, 2012

Dart: Terra Incognita (Ladislav Thon)

So what's with this TypeScript thingie?

It shouldn’t come as a surprise that the Dart community discusses TypeScript a lot. And I can’t come late. You’ll note that I’m obviously biased – I love Dart and know it inside and out, while the TypeScript language isn’t out longer than few hours and I only managed to skim through the specification. But I’ll try anyway.

Warning: this is mostly opinions. You won’t find almost any hard facts in this post (and it’s unlikely that I will ever write such post about TypeScript).

First of all: TypeScript takes a very pragmatic approach. All valid JavaScript code is valid TypeScript code and TypeScript produces a human-style JavaScript as its output. Which means that TypeScript still retains all the quirks of JavaScript semantics, but it also means that people can immediately start to use it and integrate with existing JavaScript code seamlessly. That’s a real pain point of Dart, which, in this light, takes a more idealistic and more ambitious approach.

JS interop seems to be the main design goal of TypeScript, because its static type system is specifically designed to be sound while covering all the JavaScript dynamicisms at the same time. The result is pretty impressive and also a bit weird. So here we have structurally typed interfaces and nominally typed classes. Both of them make sense in certain contexts, but combining them in one language – that’s a bold idea. I can’t decide if I like it or fear it… probably both. One thing should be made very clear about TypeScript, though – it isn’t statically typed. Instead, it takes an optional approach exactly as Dart. You don’t have to write type annotations, but once you do, the compiler will warn you about possible problems (while still generating the target JavaScript code).

TypeScript doesn’t seem to be a big language. It takes JavaScript, adds type annotations, classes and interfaces, modules and maybe some other minor stuff (they plan to add generics and enums in the future). That made me wonder – given that the specification only covers the augmentations, how come it has 100 pages? Dart specification is about the same length, and it covers whole new language! The truth is that TypeScript specification is a lot more “wordy”, the Dart one is very abstract (which isn’t a bad thing). If they wanted, they could squeeze it in a half.

But the current form of the specification and the language isn’t that interesting. What’s more interesting is the future. TypeScript builds on existing JavaScript, the classes are even identical to the current ECMAScript 6 proposal. All nice and dandy… right now. I can easily imagine TypeScript reaching 1.0 before ES6 is published. What happens when some features that TypeScript has later come to JavaScript too, but in a slightly different shape? But perhaps using similar syntax with the same keywords? (Both classes and modules are first-class candidates.) Is TypeScript going to make backwards-incompatible changes, or is the “all JavaScript is valid TypeScript” mantra going to burn in hell? Or will they somehow manage to put new JS with old TS together, no matter what happens?

Also, I think that while Anders Hejlsberg is a great language designer, he isn’t that great language maintainer. He keeps adding features to his languages relentlessly and even if the result is always backwards compatible, it also feels more and more like a mutant. I do hate Java, but I have to admire the fact that it still feels tight and consistent.

To sum it up, I think that TypeScript has some very nice tricks in the bag and if I were to work on an existing JavaScript project right now, I would at least consider using it (unlike CoffeeScript and similar languages). But I also think that Dart’s approach of designing completely new language with completely new set of libraries and tools (and even with completely new DOM API!) is significantly better in the long term. And you expected that from me, didn’t you?

P.S.: it’s great that the TypeScript compiler is open-source and readily available as a Node module, but the tooling is still proprietary. And it’s a VisualStudio-only plugin. That doesn’t impress me much.

October 02, 2012 07:00 AM

October 01, 2012

John Evans

Switchy - A Starter MVVM App for Buckshot

Switchy is a single page, content switching application that uses the MVVM pattern.  It is part of Buckshot's growing "starter projects" collection, and is included in the framework (/example/starter_projects/switchy).

You can view it online here (Chrome Only): http://www.buckshotui.org/switchy/

It demonstrates a common application scenario:  A top-aligned menu, with a content area below.  It shows how to take advantage of the following Buckshot concepts:

  • Use a master/content MVVM structure.
  • Use content views with their own view models.
  • Reference and use control extensions:.
    • DockPanel
    • MenuStrip, Menu, MenuItem
    • ModalDialog
  • Use default theme resources to create consistent UI appearance.
  • Declare and use attached properties (DockPanel.dock)
  • Use data binding, resource binding in templates and wire them up to view models.
  • Declare events in templates and wire them up to view models.
Switchy's layout is made of 3 main sections:  A menu strip, a status bar, and a content area.  These are illustrated in the image below:



Selecting something from the menu, will trigger action in the master view model which will reflect in the page view.  These actions include switching the content area to a new content view, opening another web page, or displaying the "about" modal dialog, as seen below:


Notice how the modal dialog masks out the window until it receives input from the user.  Also notice how the status bar is updated to reflect what is happening in the application.

The Switchy project is a great starting point for building an application with Buckshot.  Give it a try today!

by John Evans (noreply@blogger.com) at October 01, 2012 01:37 PM

September 30, 2012

Trials (and Errors) in Dart

Dart Koans

The next week or so, I'm going to be limited in the amount of time I will have for some programming. I will hopefully still get some programming in but I will be limited in how much time and frequency I will have for it. Because of that, and the fact that I'm a little impatient, I've decided to share some information on my current project.

The project is Dart Koans. It is inspired, though not based on, a ruby project of a similar name: Ruby Koans. I completed the Ruby Koans when I was first learning Ruby, having come from other similar languages like Python as well as from JavaScript. The Koans helped a lot because I learn really well from hands-on coding. Additionally, while covering the basics, it does dive right in.

I felt that a similar approach to learning Dart would be a great contribution to the community. There are many programmers coming in from other languages who are comfortable with the basic concepts and don't need some of the background or theory involved with traditional tutorials. They're familiar with what a variable is, and just want to know how they're used in Dart. They're itching to write some code in Dart to see how it feels.

The Dart Koans are for people new to Dart, and comfortable on the CLI (currently it's not recommended to run from the Dart editor, as it's blocked by a couple of bugs.
1) Issue 4654 (Dart Editor should handle ANSI color output).
or
2) Issue 2789 (Provide a way to find out if stdout is connected to a terminal).

The idea behind Dart Koans is that you achieve enlightenment through failure. You start with many failing tests. And individually correct each test and re-run the program. With each run of the application you should get closer and closer to resolving all tests. Each test introduces a new concept of the Dart language or libraries. At the moment it is still very very early and only a small portion of the total tests are completed. Currently there are 55 tests. By the time this is completed I expect well over 300 or more. As each test fails it will provide the error, line and file to look at to correct the issue. Each test (using the unittest library) is accompanied by several comments which will provide information about the concept being introduced.

Due to the early development stage, the tutorial is currently very much in the preview stage and far from its completed form. However I intend to add more tests and areas as much as I can. I'm interested in any feedback or comments or concerns but please keep in mind things are very much subject to change. Current output is primarily for demonstration purposes and is most likely not the final result.

Because I will be updating very frequently I will not be making many blog posts about the projecct unless its regarding a significant milestone or involves any major changes to the project.

by Matthew Butler (noreply@blogger.com) at September 30, 2012 11:34 PM

September 28, 2012

Dart: Terra Incognita (Ladislav Thon)

3 ways how Dart could get even cooler

Few days after I published 3 reasons why Dart is cool, I realized that should this be year 1998 or so, I would probably be writing 3 reasons why Java is cool. And it hit me hard, because I truly hate Java nowadays. What happened?

See, my 3 reasons why Java is cool would probably look like this:

  • it runs in a virtual machine (meaning no pointers and especially no pointer arithmetics, automatic memory management via garbage collection, sandboxing etc.);
  • it has interfaces, which are great for describing APIs;
  • it has a great standard library (kudos to Josh Bloch of the Java Collections Framework fame!).

These were all great innovations on the mainstream field (knowing that Lisp already had a VM in 1960’s, but that’s hardly mainstream) and we owe Java a lot, because we take them for granted nowadays. (I’m speaking about Java here because that’s what I do. The same applies to a bunch of other languages.) But as I said, I hate Java today (meaning I hate the language – I still very much love the JVM). The thing is – Java didn’t evolve very much. The only significant change was adding annotations and generics in Java 5, and I wouldn’t describe both of them as a great success. Closures are coming in Java 8 – at last! (That’s even more weird if we realize that closures didn’t make it into Java 1 merely because lack of time.) Traits too (stateless, I think) – hooray! The world has changed, and Java didn’t. Contrary to C#, for example (which, on the other hand, throws in features quite wildly).

Dart absolutely must evolve at a steady pace! Luckily, there are no signs that Dart will fall asleep. There will be no language changes for some time now, as Dart approaches M1, but mixins are coming afterwards and who knows what else (dynamic loading? Mirror builders? World peace?). Here are my post-M1 wishes (or even post-1.0, I don’t care that much about timing right now).

Language support for asynchronous programming

This is probably a no. 1 wish of all “seasoned” Dart programmers. Dart very much loves asynchrony (as JavaScript does), but doesn’t provide anything better than callbacks (with their famous nesting hell) and Futures (which can get right into the same hell very fast with all those chains and transforms).

Luckily, we’re not on our own here. For quite some time, there has been an experimental implementation of the await concept in the dart2js compiler. It is pretty much the same as in C# – it helps us write Future-based asynchronous code in a similar-to-synchronous way. I like the fact that, unlike C#, there is no async keyword and that we still know that we are dealing with Futures. To me, it’s absolutely essential that the programmer can immediatelly tell whether some code is synchronous or asynchronous, because there are some fundamental differences in the computation model that we must be aware of.

I like await nowadays (I used to hate it and I still think that the fact that async methods in C# run on another thread isn’t a great idea) and I’d love to see it in Dart. But please, please (and this doesn’t only apply to Dart designers, but to all Dart programmers out there), don’t try to make async code look too much like sync code, it would burn us badly.

(Funny thing here: if we didn’t have mutable state in the language, we wouldn’t have to worry that much about differences between sync and async code. We would have other issues, though, and as I said earlier, I believe that mutable state is essential for dealing with the real world.)

Unified event model (or not so much?)

This is also one thing that a lot of people is calling for. There is an event loop at the very heart of Dart, so it seems natural to have one true event model. But there’s a problem with this – the DOM. Its event model is way too complex to be accomodated in a general event model for everything else. So here’s my proposal: try to get one reasonable, simple and universal event model together, but leave the DOM out. Two event models are still a hell better than everything-has-its-own-event-model situation that we are facing now.

And how should it look like? We all know observers and observables, right? So that must be the way… Well, no. For one, I honestly believe that observable is the single worst name in the whole history of computer science. It doesn’t describe what the object does, it only describes what you can do to it. That sucks. And to be honest, I struggled with observers and observables a lot until I realized that it’s all about poor naming. Observable should have been called EventSource from the very beginning. Or something like that.

Second, plain old observers (also called listeners) are extremely fragile, hard to compose, and, well, you should all read the Deprecating the Observer Pattern paper by Ingo Maier, Tiark Rompf and Martin Odersky. They are going quite far and define a whole new dataflow-based language (a DSL on top of Scala, actually). I would stick with something not that advanced – a reactive model. But not the push-based reactive model we know from Reactive eXtensions for .NET. I want pretty much the pull-based reactive model from this paper you all just read (you didn’t? You most definitely should).

A little richer type system

Sounds weird, but I really want the type system to be a little richer. Especially, I’m talking about two things: nullable types and union types.

Inventing null was a billion-dollar mistake, as Tony Hoare explains. We all know that, as we all deal with nulls every day. C# looks like the leader here, having added nullable types in version 2 (but only for value types, which are by default non-null; reference types are always nullable and can’t be made non-null), a lot of other coming languages have non-null/nullable types as well. I want them in Dart too. And I especially want non-nullable to be the default (but that, sadly, isn’t probably going to happen). I don’t think that we need to enforce non-nullability at the runtime, this could (and should) only be a part of the static type system that is only checked in the IDEs and in the checked mode.

With nullable types should also come some new operators: null-safe navigation (a.b throws NullPointerException when a is null, but a?.b returns null in that case), null-safe indexing (same as null-safe navigation, but for the [] operator) and default value, which is essentialy a shortened ternary operator (a ?: b is equivalent to a != null ? a : b; it is also called the Elvis operator and this name itself is a good reason to prefer this syntax to JavaScript proposed a ?? b).

And now for something completely different: it’s quite common in dynamically typed languages to accept objects of different classes as arguments to functions. Sadly, Dart’s type system can’t express this situation, so you are left alone (and in better case, it’s documented in the function’s documentation comment). I’d strongly prefer union types to be a part of the language, so that we can write self-documenting code like setStyle(String name, String|int|CssValue value) instead of setStyle(String name, value). Note that this would have some (I think nice) consequences: type parameter constraints would immediatelly be more powerful. I know that generics are hard (and F-bounded quantification especially), but there are some incredibly smart people on the Dart team, so I believe that should this pose a problem, they will figure it out.

With union types, some people would immediatelly want intersection types too. While they might be useful, I don’t really see the need right now. So I would skip them at the moment.

Oh, and since we are talking union types… just give us proper enums (pretty please, with a cherry on top!).

Language support for working with data

And again, there’s more.

At first, LINQ. A huge number of people are screaming for something like LINQ in Dart. I personally don’t want all that expression trees machinery, but I admit that LINQ somewhat has a point. On the other hand, you can get quite far just by adding a bunch of useful methods to the Collection class: filter, map, reduce, you know it. Take a look at Deequery, it is – to my knowledge – the most advanced Dart library for this declarative/functional style of working with collections.

But I think we could and should do a little better. Back then when I was thinking about list comprehensions and how to generalize them, I came up with something very similar to LINQ. So, guys… what about collection comprehensions (supporting both Lists and Sets)? And could we, somehow, extend them to Maps too?

And second, pattern matching. This is useful in wide range of situations, not only when working with data, but I figured I will stick it in this bucket anyway. For all who are not familiar with this concept, imagine a switch on steroids: a switch that is able to dive into the structure of given object and when the structure matches given pattern (see?), it can also assign the real values to given variables.

With the increasing popularity of schema-free databases (I’m a radical NoSQL guy as well ;-) ), we need better tools for working with dynamic data structures. And especially nested data structures. I think that pattern matching can help us a lot in this area, and I’m sure that Dart designers will come up with other ways.

Conclusion

I strongly believe that Dart must continue to innovate – and by innovate, I mean innovate on the mainstream field. The features I mentioned above are not really formative parts of the language and some of them even appeared in mainstream languages before, but they will help us tremendously. I also believe that the Dart team knows very well what I am talking about and doesn’t want Dart to become “the next Java”. So… what are your favorite features that should appear in future Dart? Regexp literals, anyone? :-)

September 28, 2012 07:00 AM

September 25, 2012

Dartery

js.dart Makes an Appearance on G+

Vijay Menon announced on Google+ that the JS interop library he's been working on is coming along.

I'll be checking this out as soon as possible, with the first task being to rewrite the Channel API library using js.dart rather than custom events. I also want to see what it's like to write a library in Dart and expose it to JavaScipt. If nice JavaScript APIs can be built with little effort on top of Dart libraries it would be a huge boon to Dart, in my opinion.

The library is up on guthub, but the most interesting part to scan right now is the dartdoc page.

A few things about js.dart that might be interesting to readers:

  1. The library is implemented on top of synchronous isolate send ports. Those will be useful for other purposes as well, including Dart<->Dart proxies across isolates.
  2. The library requires a bit of manual memory management, either via retain() and release() calls, or by running JS interop code inside a scoped() closure. See the dartdoc for examples.
  3. The API currently provides untyped proxies to JavaScript objects, that is they don't have a Dart interface defined based on the Javascript object. Currently that would be impossible, because you can't define a class at runtime in Dart. It should be possible to hand-write typed wrappers on those proxies, but they will have to be careful to play well with the memory management. APIs with objects that have a very obvious lifetime should be relatively easy to wrap, I think.
  4. Lists and Maps require special handling. Because arrays and objects are built-ins in JavaScript and there are no interfaces you won't be able to just send a Dart List to JS and always have it work as expected. It's impossible (with out ES6 Proxies or Object.observe) to invoke Dart modification methods like add() and remove() when the collections are modified in JS. This means that Dart Lists and Maps must be copied into JS, and read back later.
It will be very interesting to see if automatic memory management can be made to work and if typed wrappers could be generated from JavaScript annotated with Closure-style type annotations

All-in-all this is a very exciting development for Dart, and I think it's just the beginning.

by Justin Fagnani (noreply@blogger.com) at September 25, 2012 06:18 AM

September 24, 2012

Dartery

Using the App Engine Channel API in Dart

In this post, I showed how to do a limited form of JS interop via custom events. This technique really only works well for asynchronous APIs, and is too tedious for large APIs, but it's quite reasonable for APIs that are event based because all you're doing is forwarding events across the JS/Dart divide.

One such API that's been brought up in misc@dartlang.org posts and Stack Overflow questions is the Google App Engine Channel API.

For those who don't know, the Channel API is server-push for App Engine. The really nice thing is that it allows App Engine apps to send messages to browsers without having to know how it's done. It might use polling or hanging GETs or WebSockets... we don't know, or have to.  All you have to know is how to use the Channel API to register a client and send it a message.

This is nice, but it presents a problem for porting to Dart. We can't just port the JavaScript, because the App Engine servers might send different versions of the JavaScript depending on what APIs the browsers and servers support. Instead we have to use the custom event technique to proxy the provided JavaScript API.

I just pushed such a Dart version of the Channel API that uses custom events to Google Code.

http://code.google.com/p/gwt-gae-channel/

Using it is fairly straightforward, here's an example that registers handler's to print all messages:
openChannel(String token) {
Channel channel = new Channel(token);
Socket socket = channel.open()
..onOpen = (() => print("open"))
..onClose = (() => print("close"))
..onMessage = ((m) => print("message: $m"))
..onError = ((code, desc) => print("error: $code $desc"));
}
To port to Dart I created Dart versions of Channel and Socket, very much like the GWT port, but they work very differently, since Dart doesn't have JSNI or overlay types like GWT.

In Dart the classes forward their method calls as custom events that are received in JavaScript handlers, and they listen for custom events that are fired when the Channel API calls our handlers on the JavaScript side.

When a channel is opened the JavaScript handler creates a channel, opens it to get a socket and adds handlers to the socket that forward events back to Dart through custom events. It keeps track of sockets in a map keyed by token so that they can be later closed. The Dart side also keeps tracks of Sockets in a Map keyed by token so that it can associate messages received via custom event to the correct Socket instance. Thus, the tokens function as a Socket ids.

This pattern of having maps of id->instance on both sides of the JS/Dart divide is going to be common for this type of interop. The instances are proxys, and the ids help route messages to the right instance. The Channel API is small and naturally lends itself to this pattern especially using tokens as ids. For other APIs it might be necessary to generate synthetic unique ids for this purpose.

If you're combining Dart and App Engine, and can make use of this library, please try it out and let me know if it's working for you. It probably needs more testing and of course, contributions are always welcome!

by Justin Fagnani (noreply@blogger.com) at September 24, 2012 12:22 AM

September 23, 2012

Dartery

Memoizing Functions in Dart

Today I saw a post on Reddit about dynamic programming that reminded me of memoization, so I thought I'd try some experiments in Dart to see how it handles some of the more interesting techniques I've seen in other languages.

Dynamic programming and memoization are concepts that are so useful that I remember being excited when I learned them, but actually disappointed that I hadn't learned them earlier. If you're not familiar with them, I highly recommend reading up.

To very quickly summarize: memoization is the strategy of caching the results of function invocations and using the cache when possible on subsequent invocations instead of re-calculating the result. This can obviously speed up repeated function calls with the same arguments. Where things become awesomer is when dealing with recursive functions that call themselves multiple times with the same argument as they recurse. Naive implementations of such functions do a lot of repeated work and can run very slowly, and dynamic programming can dramatically speed them up.

Example: Fibbonaci

The most common example is a function to calculate Fibbonaci numbers. The naive implementation looks like this:
int fib(int n) => (n < 2) ? n : fib(n - 1) + fib(n - 2);
This is pretty much a straight translation of the recursive relation definition of a Fibbonaci number. What's nice about this is that it's simple, it's a very common example of a recursive function, and was even the default example on the Dartboard for a while. The problem is that it's slow. So slow that I hate ever seeing the naive version shown, even as an example, when a much faster version is still simple.

Here's a version that uses dynamic programming:
int dynamicfib(int n) {
var r = new List<int>(n + 1);
r[0] = 0;
r[1] = 1;
for (int i = 2; i < n + 1; i++) {
r[i] = r[i - 1] + r[i - 2];
}
return[n];
}
It runs significantly faster. How much faster? In cases where the recursive version would still be running at the heat death of the universe, the non-recursive can give an answer while you wait. fib(40) takes 41 seconds to compute recursively on my laptop, dynamicfib takes less than a millisecond. Whoa.

Automatic Memoization

"Memoization isn't cool. You know what's cool? Automatic memoization." - No One Ever
So our memoized Fibonacci function is about a zillion times faster than the recursive one. But it's not as obviously correct when compared to the recursive relation definition of a Fibbonaci number.

If we could take the simple recursive definition and run it through a process where it just remembers previous values, then we would have a fast and easy to inspect implementation.

Since Dart supports first-class functions and closures we can try to write a function that takes a function and returns another function that does the same thing, but adds memoization.

Here's my first attempt:
memoize1(f(x)) {
var cache = new Map();
m(x) {
if (cache.containsKey(x)) {
return cache[x];
} else {
var result = f(x);
cache[x] = result;
return result;
}
}
return m;
}
Line-by-line, memoize1 takes a function f as an argument, creates a cache, defines a function m which first checks the cache for an existing value and returns it if found, or it calculates the value, caches the result and then returns it. Finally memoize1 returns that new function.

memoize1 is so named because it works for functions with one parameter. Dart lacks varargs as of now, so the wrapper function m must have a fixed number of arguments. Function emulation would fix this, as would real vararg support.

To use memoize1 we pass it a reference to fib like so:
var fastfib = memoize1(fib);
var f40 = fastfib(40);
Easy, right? The only problem is that fastfib(40) still takes 41 seconds to run. Why? because even though the initial call to fastfib uses the memoization wrapper, the recursive calls don't. They still call plain ol' fib. Ouch.

So what do we do? First let's consider how this works in other languages.

One great thing about many dynamic languages (not to be confused with dynamic programming!) is that it's often relatively easy to modify code at runtime, which makes writing an automatic memoizer that works on recursive function possible.

For instance, in a language where you can rebind a function name, like Ruby or Javascript, you rebind  the original function name to a function that wraps the original and caches it's return values. Rebinding the name means that even the recursive calls in the function call the memoized version, not the original.

In Python it's even easier because decorators capture calls to the function so that even rebinding isn't necessary.

In a less dynamic* language like Dart we can't redefine a function and there are no decorators, so automatic memoization is much trickier. Mirrors and/or MirrorBuilders might help in the future, but they can't save us now.

* "dynamic language" is such an overloaded term that things get confusing. Dart is still dynamically typed, but it's less easy to redefine functions and classes or introduce new variables, so it's in some ways less dynamic that Python, Javascript or Ruby.

Designing for Memoization

What we can do though is write our function specifically so that it's amenable to this type of transformation. In order to do that we can't hardcode our recursive calls anymore because we must allow them to be replaced.

What we do is pass the function to itself as an argument. This looks weird, but it lets us pass in a wrapper instead of the original function and then the recursive calls will call the wrapper. I'm pretty sure this either is an example of some kind of combinator or was used to derive a combinator in a programming languages class a long time back... but unfortunately I forget now.

Here's the code:
int fib1(int f(f2, n2), int n) => (n <= 1) ? n : f(f, n - 1) + f(f, n - 2);

int fib(int n) => fib1(fib1, n);

memoize1(f(f2, x)) {
var cache = new Map();
m(m2, x) {
if (cache.containsKey(x)) {
return cache[x];
} else {
var result = f(m2, x);
cache[x] = result;
return result;
}
}
return (x) => m(m, x);
}

main() {
var fastfib = memoize(fib1);
print(fib(40);
print(fastfib(40));
}
fib1 is our modified Fibbonaci function that now takes two arguments: a function f with the same signature as fib1 that we use to make the recursive calls, and n the original argument.

fib is the regular, easy-to-use, recursive Fibbonaci function that we create be passing fib1 to itself. The result is essentially the same as the original fib.

The new memoize1 still takes one argument, but that argument is now a memoizable single-argument function, such as fib1. The wrapper m takes a new argument, m2, and now passes that to the recursive function so that when we pass the memoizing wrapper to itself, recursive calls call the wrapper and not the original function like before.

Now when I run fastfib(40) on my laptop it runs in 3ms. A little slower that dynamicfib due to the wrapper, using a Map rather than a List, and the few recursive calls that are actually made, but still roughly a zillion times faster than the original. Importantly for this exercise, the new memoize1 will work on any recursive function written to take itself as a parameter. Now someone could include a memoize function in a library and developers can write functions that they can easily speed up.

Reflections on Dart

I'm not sure that automatic memoization is actually that useful - it's probably better to have a programmer really understand the implications of caching results - but I think this exercise points out a few areas where Dart could improve.

  • Transforming functions is hard without varargs/kwargs. I suspect until then we'll see a bunch cases where a library has foo1, foo2, foo3 to transform functions with different arity. I'm not sure how transforming functions with key-word arguments could even work, except with apply() maybe.
  • It'd be nicer if developers didn't have to use the technique of passing a function to itself. I'm sure that's confusing to a lot of people. This is one reason I'd like to see Dart adopt Python-style decorators, though with the arrival of the @ syntax for metadata, some thought would have to go into the syntax and how metadata and decorators co-exist.
  • This technique is probably not going to work well in checked mode, because we can't force the wrapper to have the same runtime type as the function we're transforming. Generic functions might help in some cases, but in the general case we won't be able to specify or capture all the type parameters that the original function uses.
  • It'd also be interesting to see how MirrorBuilders might come into play here. If it were possible to introspect the code of a function and transform it to build a new function, then we could memoize functions that we didn't even write. MirrorBuilders might not be possible in dart2js, but Groovy's compile-time AST transformations could be an inspiration here. We don't need to do the memoize transformation at runtime, if we could run the mirror system at compile time we could generate new code that the VM or dart2js each could use.


Well, I hope that was interesting to at least someone out there. If anything it was fun to investigate, and if I got anything wrong, please let me know!

by Justin Fagnani (noreply@blogger.com) at September 23, 2012 03:08 AM

September 22, 2012

Dartflash

dartflash has a new website

The Dart project is proceeding fast and soon they will reach Milestone 1. This milestone means that the language becomes pretty much stable and the team will focus more on the libraries and the tools in the future. At the same time or short after they will release the first version of the package manager called "Pub". I hope that dartflash will be listed on the package manager and if this happens the dartflash website has to become much more pretty.

I'm not an expert in web development. I have some knowledge of HTML and CSS but i would need more practice to get better. Luckily Bootstrap (http://twitter.github.com/bootstrap) does a very good job and with little effort you get something that looks pretty nice. So here it is, not finished and still a lot of "lorem ipsum" texts, but much better than the old website :)

It's a start: http://www.dartflash.com

by Bernhard Pichler (noreply@blogger.com) at September 22, 2012 07:32 PM

September 19, 2012

Trials (and Errors) in Dart

Resort to sort

So the past few days I've been playing around with some simple algorithms. I'm not 'professionally' trained, and most of my experience has been with what I've seen in code or have implemented myself. Does that make me less of a developer for not being classically trained? Maybe, maybe not.

In particular I've been playing around with some of the sorting algorithms. Stuff like Bubble sort, Selection sort, Insertion sort, and of course Quicksort.

My first task as been to study the algorithm and look at whatever pseudo-code or explanation is presented for the algorithm. Study and understand it. Then is to walk away from any computer or anything, take a little break. After a short time I then pull out a pen and paper and write down a Dart version of the code. I write it out in front of me without referring to APIs, or without referencing the material.

I later then enter that code (or re-write it) into the Dart editor in a simple test file I have. I run it, fix my bugs, and run it again. My test file contains all of the various sorts as I learn them, it then prints out the sorted list and the time it took to complete (using a Stopwatch). I also have a function to create a list of X size filed with values from Random.nextInt.

Being able to easily create a random list of a determined size is nice, as it allows me to easily increment the list size as I choose and see the differences in performance. For instance it took a list of almost 5000 items for Quicksort with the two isolates to be faster than the main-thread version of Quicksort. (See Edit note below)

Many of the algorithms I've implemented are without performance improvements and are far from the most efficient versions available. One thing I've noticed though is List.sort((a, b) => a - b); has generally been one of the best performing algorithms, in lists of up to 10,000 items.

However as I mentioned none of the algorithms has been tuned for best performance or memory usage and are just the 'simple' versions of the algorithms just for my own learning purposes and less for actual performance comparisons. The performance comparisons are more of a visual reference to the Big O Notation for myself.

[Edit:]So I was wrong. I had poorly implemented my Quicksort with Isolates. Very poorly. It was a hodgepodge of Futures and a custom callback. I went through and cleaned it up and changed it so it returned a Future instead of calling a callback. Once I did that I saw an over 10x speed increase in the Quicksort with Isolates version and it and was about the same speed as the Main-threaded Quicksort for lists below 500 items. And faster for lists greater than 500 items. This has more to do with my unfamiliarity with Isolates than with the algorithms themselves.[/Edit]

For those who may be interested, you can the current version of the file here: https://github.com/butlermatt/sorting_dart. As time goes by, I will be adding more algorithms (with comments) as I learn them myself. Again please recall these are not optimized in any way and are only presented as-is, as proof of concept.
In time I may add some optimized versions of algorithms myself as I progress. Keep in mind however this is primarily a learning project and not designed for use. They may be (and are) buggy.

by Matthew Butler (noreply@blogger.com) at September 19, 2012 04:58 PM

September 17, 2012

Trials (and Errors) in Dart

Contributed Contributions

So it has been quite some time since my last post. Today will be a relatively short one, but I think I'm going to try and get into the habit of writing a blog post now and then.

Today I wanted to mention a little about contributing back to Dart. This is something very easy for anyone to do, on a variety of different levels. First and foremost, I've been contributing in small ways in the past just by using Dart. And in particular by using Dart and filing bug reports when you run into something. Currently I have 15 bug reports that I have reported and are still open. And many more which have been fixed for a long time.

You can submit bug reports for not only code that isn't working correctly, but also for documentation which may need to be updated or corrected; for updates to the website; or even just style recommendations (particularly those which may apply to the Style Guide).

Bug reports are a great way to contribute as the more bugs that are found and squashed the more stable and attractive Dart becomes.

Eventually you may start feeling comfortable enough to provide solutions to the bugs you provide. Either pasting in a suggestion into the bug report, or by submitting a patch.

Note: I will mention this here ahead of time. Before Google can integrate any code you provide them, you must sign the Contributor License Agreement (CLA).

I have personally submitted patches to a number of areas of the Dart project. My first was to the dartlang.org website. I found a typo in the language tour. So I went to GitHub site. Found the Dartlang/dartlang.org repository and forked it. I made the edits that I saw needed to be corrected and issued a pull request.

One handy tip I received, was to use a rebase workflow when dealing with edits to the github repositories. After doing a bit of searching around, a very good article I found was A Git Workflow for Agile Teams. This shows a very straight forward method of using rebase to create nice clean commits when pushing upstream. I still refer to it when working on patch for the sites.

After submitting a couple of corrections to the dartlang.org site(s) I began to feel comfortable enough with submitting code to the dart source code. This process is significantly different than just forking a github repository. First instead of using github, its best to follow the steps here for getting the source. Make sure you can build before trying to edit any code.

Once you've verified you can build after getting the source code for the first time. You can go ahead and make your changes. After making your changes, make sure you once again build. Then also make sure you can pass the tests. If possible run as many tests as you can, not just specific to one area as you never know what else might rely on behaviour you didn't expect (I found this out the hard way myself).

If everything looks good with the test. Submit your patch. I'll give you a hint now as well. Once the patch is uploaded, it will display a chromium code review site. Similar to: https://chromiumcodereview.appspot.com/10918056/ Be sure to go to that site. Edit the issue and add a reviewer (if you're not sure who should review ask in either the bug report that you're working on or from the mailing list). Update the issue once you've added a reviewer. Then click on 'Publish+Mail Comments'. If you don't do this, no one will know that your patch is waiting for review!!! (Mine waited over a week because I didn't do this haha).

Once your patch is looked at, you will usually get a 'lgtm' (Looks good to me) and possibly some suggestions on small typos to fix. If you get line comments on things to fix, then fix them in your code, then re-upload a patch (using the same method as before). It will automatically associate it with your previous patch (as long as you're using the same git branch!). Then go to the comments in the source that were left for you, click on each. Then click on the 'Done' link. That will signal to the reviewer that you looked at each comment and addressed the issue. Once you've marked each comment as 'Done', then 'Publish+Mail Comments' again.

Usually by this point the reviewer will commit your patch for you into the source. They will usually link another patch ID, and on that patch ID will be a revision id such as https://code.google.com/p/dart/source/detail?r=12278. Once you have that you can also watch the buildbot progress for your patch to see if you end up breaking anything ;)

So that's a summary of how I have, and you can, contribute to Dart. Now get out there and enjoy it!

by Matthew Butler (noreply@blogger.com) at September 17, 2012 07:15 PM

Dart Logo

Last updated: May 24, 2013 12:45 PM UTC

Dartosphere channels