Commit 82404e03 authored by Ian Fischer's avatar Ian Fischer

Move sky/examples to sky/sdk/lib/example, and code changes to support that change. Fixes T277.

R=abarth@chromium.org

Review URL: https://codereview.chromium.org/1218593002.
parent 75f1c05b
Sky Examples
============
This directory contains several examples of using Sky. Each of these is an
individual Dart application package. If you wish to run them with `sky_tool`
then you will want to run `pub get` inside their directory before running
`./packages/sky/sky_tool start`.
1. *Hello, world.* The [hello world app](hello_world) is a basic app that shows
the text "hello, world."
2. *Stocks.* The [stocks app](stocks) is an example of a typical mobile app
built using Sky. The app shows a list of all the stocks in the NASDAQ.
3. *Widgets.* The [widgets app](widgets) contains a number of Sky widgets so
you can experiment with them in a simple container.
#!mojo mojo:sky_viewer
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-->
<sky>
<style>
#chooser {
display: flex;
flex-direction: column;
justify-content: center;
padding: 5%;
}
#color-wheel {
min-width: 100%;
height: auto;
}
#color-sample {
margin: 5%;
padding: 10%;
text-align: center;
border-radius: 10px;
}
</style>
<div id="chooser">
<img id="color-wheel" src="color-wheel.png"/>
<h1 id="color-sample">Select Color</h1>
</div>
<script>
import 'dart:sky';
import 'dart:math';
class RGB {
final int r;
final int g;
final int b;
const RGB(this.r, this.g, this.b);
String toString() => "rgb($r, $g, $b)";
}
RGB hsvToRgb(double h, double s, double v) {
var i = (h * 6).floor();
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
var r, g, b;
switch (i % 6) {
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
return new RGB((r * 255).floor(), (g * 255).floor(), (b * 255).floor());
}
RGB xyToRgb(x, y, radius) {
var rx = x - radius;
var ry = y - radius;
var d = radius * radius;
if (rx * rx + ry * ry > d)
return null;
var h = (atan2(ry, rx) + PI) / (2 * PI);
var s = sqrt(d) / radius;
return hsvToRgb(h, s, 1.0);
}
elt(String id) => document.getElementById(id);
void updateColor(event) {
var bounds = event.target.getBoundingClientRect();
var x = event.x - bounds.left;
var y = event.y - bounds.top;
var radius = min(bounds.width, bounds.height) / 2.0;
var rgb = xyToRgb(x, y, radius);
if (rgb != null) {
var ccsColor = rgb.toString();
elt("color-sample").style["background-color"] = ccsColor;
}
}
void selectColor(event) {
var ccsColor = elt("color-sample").style["background-color"];
print(ccsColor);
}
void main() {
elt("color-wheel").addEventListener("pointerdown", updateColor);
elt("color-sample").addEventListener("pointerdown", selectColor);
elt("color-sample").style["background-color"] = "rgb(0, 209, 255)";
}
</script>
</sky>
This diff was suppressed by a .gitattributes entry.
name: color
dependencies:
sky: any
library game;
import 'dart:sky';
import 'dart:math' as Math;
import 'package:vector_math/vector_math_64.dart';
import 'sprites.dart';
import 'package:box2d/box2d.dart';
import 'package:sky/rendering/object.dart';
part 'game_demo_world.dart';
This diff is collapsed.
part of sprites;
typedef void ImageMapCallback(ImageMap preloader);
class ImageMap {
Map<String, Image> _images;
int _totalNumImages = 0;
int _numLoadedImages = 0;
ImageMapCallback _callback;
ImageMap(List<String> urls, ImageMapCallback this._callback) {
_images = new Map();
_totalNumImages = urls.length;
urls.forEach(_addURL);
}
void _addURL(String url) {
image_cache.load(url, (Image image) {
// Store reference to image
_images[url] = image;
// Check if all images are loaded
_numLoadedImages++;
if (_numLoadedImages==_totalNumImages) {
// Everything loaded, make callback
_callback(this);
}
});
}
Image getImage(String url) => _images[url];
Image operator [](String url) => _images[url];
}
\ No newline at end of file
This diff is collapsed.
part of sprites;
/// The super class of any [Node] that has a size.
///
/// NodeWithSize adds the ability for a node to have a size and a pivot point.
abstract class NodeWithSize extends Node {
/// Changing the size will affect the size of the rendering of the node.
///
/// myNode.size = new Size(1024.0, 1024.0);
Size size;
/// The normalized point which the node is transformed around.
///
/// // Position myNode from is middle top
/// myNode.pivot = new Point(0.5, 0.0);
Point pivot;
/// Creates a new NodeWithSize.
///
/// The default [size] is zero and the default [pivot] point is the origin. Subclasses may change the default values.
///
/// var myNodeWithSize = new NodeWithSize(new Size(1024.0, 1024.0));
NodeWithSize([Size this.size, Point this.pivot]) {
if (size == null) size = Size.zero;
if (pivot == null) pivot = Point.origin;
}
/// Call this method in your [paint] method if you want the origin of your drawing to be the top left corner of the
/// node's bounding box.
///
/// If you use this method you will need to save and restore your canvas at the beginning and
/// end of your [paint] method.
///
/// void paint(RenderCanvas canvas) {
/// canvas.save();
/// applyTransformForPivot(canvas);
///
/// // Do painting here
///
/// canvas.restore();
/// }
void applyTransformForPivot(RenderCanvas canvas) {
if (pivot.x != 0 || pivot.y != 0) {
double pivotInPointsX = size.width * pivot.x;
double pivotInPointsY = size.height * pivot.y;
canvas.translate(-pivotInPointsX, -pivotInPointsY);
}
}
bool isPointInside (Point nodePoint) {
double minX = -size.width * pivot.x;
double minY = -size.height * pivot.y;
double maxX = minX + size.width;
double maxY = minY + size.height;
return (nodePoint.x >= minX && nodePoint.x < maxX &&
nodePoint.y >= minY && nodePoint.y < maxY);
}
}
part of sprites;
/// A Sprite is a [Node] that renders a bitmap image to the screen.
class Sprite extends NodeWithSize {
/// The texture that the sprite will render to screen.
///
/// If the texture is null, the sprite will be rendered as a red square
/// marking the bounds of the sprite.
///
/// mySprite.texture = myTexture;
Texture texture;
/// If true, constrains the proportions of the image by scaling it down, if its proportions doesn't match the [size].
///
/// mySprite.constrainProportions = true;
bool constrainProportions = false;
double _opacity = 1.0;
/// The color to draw on top of the sprite, null if no color overlay is used.
///
/// // Color the sprite red
/// mySprite.colorOverlay = new Color(0x77ff0000);
Color colorOverlay;
/// The transfer mode used when drawing the sprite to screen.
///
/// // Add the colors of the sprite with the colors of the background
/// mySprite.transferMode = TransferMode.plusMode;
TransferMode transferMode;
/// Creates a new sprite from the provided [texture].
///
/// var mySprite = new Sprite(myTexture)
Sprite([this.texture]) {
if (texture != null) {
size = texture.size;
pivot = texture.pivot;
} else {
pivot = new Point(0.5, 0.5);
}
}
/// Creates a new sprite from the provided [image].
///
/// var mySprite = new Sprite.fromImage(myImage);
Sprite.fromImage(Image image) {
assert(image != null);
texture = new Texture(image);
size = texture.size;
pivot = new Point(0.5, 0.5);
}
/// The opacity of the sprite in the range 0.0 to 1.0.
///
/// mySprite.opacity = 0.5;
double get opacity => _opacity;
void set opacity(double opacity) {
assert(opacity != null);
assert(opacity >= 0.0 && opacity <= 1.0);
_opacity = opacity;
}
void paint(RenderCanvas canvas) {
canvas.save();
// Account for pivot point
applyTransformForPivot(canvas);
if (texture != null) {
double w = texture.size.width;
double h = texture.size.height;
if (w <= 0 || h <= 0) return;
double scaleX = size.width / w;
double scaleY = size.height / h;
if (constrainProportions) {
// Constrain proportions, using the smallest scale and by centering the image
if (scaleX < scaleY) {
canvas.translate(0.0, (size.height - scaleX * h) / 2.0);
scaleY = scaleX;
} else {
canvas.translate((size.width - scaleY * w) / 2.0, 0.0);
scaleX = scaleY;
}
}
canvas.scale(scaleX, scaleY);
// Setup paint object for opacity and transfer mode
Paint paint = new Paint();
paint.color = new Color.fromARGB((255.0*_opacity).toInt(), 255, 255, 255);
if (colorOverlay != null) {
paint.setColorFilter(new ColorFilter.mode(colorOverlay, TransferMode.srcATop));
}
if (transferMode != null) {
paint.setTransferMode(transferMode);
}
// Do actual drawing of the sprite
if (texture.rotated) {
// Calculate the rotated frame and spriteSourceSize
Size originalFrameSize = texture.frame.size;
Rect rotatedFrame = new Rect.fromPointAndSize(texture.frame.upperLeft, new Size(originalFrameSize.height, originalFrameSize.width));
Point rotatedSpriteSourcePoint = new Point(
-texture.spriteSourceSize.top - (texture.spriteSourceSize.bottom - texture.spriteSourceSize.top),
texture.spriteSourceSize.left);
Rect rotatedSpriteSourceSize = new Rect.fromPointAndSize(rotatedSpriteSourcePoint, new Size(originalFrameSize.height, originalFrameSize.width));
// Draw the rotated sprite
canvas.rotate(-Math.PI/2.0);
canvas.drawImageRect(texture.image, rotatedFrame, rotatedSpriteSourceSize, paint);
} else {
// Draw the sprite
canvas.drawImageRect(texture.image, texture.frame, texture.spriteSourceSize, paint);
}
} else {
// Paint a red square for missing texture
canvas.drawRect(new Rect.fromLTRB(0.0, 0.0, size.width, size.height),
new Paint()..color = const Color.fromARGB(255, 255, 0, 0));
}
canvas.restore();
}
}
This diff is collapsed.
part of sprites;
/// A widget that uses a [SpriteBox] to render a sprite node tree to the screen.
class SpriteWidget extends OneChildRenderObjectWrapper {
/// The rootNode of the sprite node tree.
///
/// var node = mySpriteWidget.rootNode;
final NodeWithSize rootNode;
/// The transform mode used to fit the sprite node tree to the size of the widget.
final SpriteBoxTransformMode transformMode;
/// Creates a new sprite widget with [rootNode] as its content.
///
/// The widget will setup the coordinate space for the sprite node tree using the size of the [rootNode] in
/// combination with the supplied [transformMode]. By default the letterbox transform mode is used. See
/// [SpriteBoxTransformMode] for more details on the different modes.
///
/// The most common way to setup the sprite node graph is to subclass [NodeWithSize] and pass it to the sprite widget.
/// In the custom subclass it's possible to build the node graph, do animations and handle user events.
///
/// var mySpriteTree = new MyCustomNodeWithSize();
/// var mySpriteWidget = new SpriteWidget(mySpriteTree, SpriteBoxTransformMode.fixedHeight);
SpriteWidget(this.rootNode, [this.transformMode = SpriteBoxTransformMode.letterbox]);
SpriteBox get root => super.root;
SpriteBox createNode() => new SpriteBox(rootNode, transformMode);
void syncRenderObject(SpriteWidget old) {
super.syncRenderObject(old);
// SpriteBox doesn't allow mutation of these properties
assert(rootNode == root.rootNode);
assert(transformMode == root._transformMode);
}
}
\ No newline at end of file
library sprites;
import 'dart:math' as Math;
import 'dart:sky';
import 'dart:typed_data';
import 'dart:convert';
import 'package:sky/base/scheduler.dart' as scheduler;
import 'package:sky/mojo/net/image_cache.dart' as image_cache;
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/widgets/widget.dart';
import 'package:vector_math/vector_math.dart';
import 'package:sky/framework/net/fetch.dart';
part 'sprite_box.dart';
part 'sprite_widget.dart';
part 'node.dart';
part 'node_with_size.dart';
part 'sprite.dart';
part 'image_map.dart';
part 'texture.dart';
part 'spritesheet.dart';
part of sprites;
/// A sprite sheet packs a number of smaller images into a single large image.
///
/// The placement of the smaller images are defined by a json file. The larger image and json file is typically created
/// by a tool such as TexturePacker. The [SpriteSheet] class will take a reference to a larger image and a json string.
/// From the image and the string the [SpriteSheet] creates a number of [Texture] objects. The names of the frames in
/// the sprite sheet definition are used to reference the different textures.
class SpriteSheet {
Image _image;
Map<String, Texture> _textures = new Map();
/// Creates a new sprite sheet from an [_image] and a sprite sheet [jsonDefinition].
///
/// var mySpriteSheet = new SpriteSheet(myImage, jsonString);
SpriteSheet(this._image, String jsonDefinition) {
assert(_image != null);
assert(jsonDefinition != null);
JsonDecoder decoder = new JsonDecoder();
Map file = decoder.convert(jsonDefinition);
assert(file != null);
List frames = file["frames"];
for (Map frameInfo in frames) {
String fileName = frameInfo["filename"];
Rect frame = _readJsonRect(frameInfo["frame"]);
bool rotated = frameInfo["rotated"];
bool trimmed = frameInfo["trimmed"];
Rect spriteSourceSize = _readJsonRect(frameInfo["spriteSourceSize"]);
Size sourceSize = _readJsonSize(frameInfo["sourceSize"]);
Point pivot = _readJsonPoint(frameInfo["pivot"]);
var texture = new Texture._fromSpriteFrame(_image, fileName, sourceSize, rotated, trimmed, frame,
spriteSourceSize, pivot);
_textures[fileName] = texture;
}
}
Rect _readJsonRect(Map data) {
num x = data["x"];
num y = data["y"];
num w = data["w"];
num h = data["h"];
return new Rect.fromLTRB(x.toDouble(), y.toDouble(), (x + w).toDouble(), (y + h).toDouble());
}
Size _readJsonSize(Map data) {
num w = data["w"];
num h = data["h"];
return new Size(w.toDouble(), h.toDouble());
}
Point _readJsonPoint(Map data) {
num x = data["x"];
num y = data["y"];
return new Point(x.toDouble(), y.toDouble());
}
/// The image used by the sprite sheet.
///
/// var spriteSheetImage = mySpriteSheet.image;
Image get image => _image;
/// Returns a texture by its name.
///
/// var myTexture = mySpriteSheet["example.png"];
Texture operator [](String fileName) => _textures[fileName];
}
part of sprites;
/// A texture represents a rectangular area of an image and is typically used to draw a sprite to the screen.
///
/// Normally you get a reference to a texture from a [SpriteSheet], but you can also create one from an [Image].
class Texture {
/// The image that this texture is a part of.
///
/// var textureImage = myTexture.image;
final Image image;
/// The logical size of the texture, before being trimmed by the texture packer.
///
/// var textureSize = myTexture.size;
final Size size;
/// The name of the image acts as a tag when acquiring a reference to it.
///
/// myTexture.name = "new_texture_name";
String name;
/// The texture was rotated 90 degrees when being packed into a sprite sheet.
///
/// if (myTexture.rotated) drawRotated();
final bool rotated;
/// The texture was trimmed when being packed into a sprite sheet.
///
/// bool trimmed = myTexture.trimmed
final bool trimmed;
/// The frame of the trimmed texture inside the image.
///
/// Rect frame = myTexture.frame;
final Rect frame;
/// The offset and size of the trimmed texture inside the image.
///
/// Position represents the offset from the logical [size], the size of the rect represents the size of the trimmed
/// texture.
///
/// Rect spriteSourceSize = myTexture.spriteSourceSize;
final Rect spriteSourceSize;
/// The default pivot point for this texture. When creating a [Sprite] from the texture, this is the pivot point that
/// will be used.
///
/// myTexture.pivot = new Point(0.5, 0.5);
Point pivot;
/// Creates a new texture from an [Image] object.
///
/// var myTexture = new Texture(myImage);
Texture(Image image) :
size = new Size(image.width.toDouble(), image.height.toDouble()),
image = image,
trimmed = false,
rotated = false,
frame = new Rect.fromLTRB(0.0, 0.0, image.width.toDouble(), image.height.toDouble()),
spriteSourceSize = new Rect.fromLTRB(0.0, 0.0, image.width.toDouble(), image.height.toDouble()),
pivot = new Point(0.5, 0.5);
Texture._fromSpriteFrame(this.image, this.name, this.size, this.rotated, this.trimmed, this.frame,
this.spriteSourceSize, this.pivot) {
}
// Texture textureFromRect(Rect rect, [String name = null]) {
// assert(rect != null);
// Rect frame = new Rect.fromLTRB();
// return new Texture._fromSpriteFrame(image, name, rect.size, false, false, );
// }
}
import 'dart:sky';
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/raised_button.dart';
import 'package:sky/widgets/widget.dart';
import 'package:sky/framework/net/fetch.dart';
import 'lib/game_demo.dart';
import 'lib/sprites.dart';
void main() {
// Load images
new ImageMap([
"res/nebula.png",
"res/sprites.png",
],
allImagesLoaded);
}
void allImagesLoaded(ImageMap loader) {
_loader = loader;
fetchBody("res/sprites.json").then((Response response) {
String json = response.bodyAsString();
_spriteSheet = new SpriteSheet(_loader["res/sprites.png"], json);
allResourcesLoaded();
});
}
void allResourcesLoaded() {
runApp(new GameDemoApp());
}
class GameDemoApp extends App {
Widget build() {
return new Stack([
new SpriteWidget(new GameDemoWorld(_loader, _spriteSheet)),
// new StackPositionedChild(
// new Flex([
// new FlexExpandingChild(
// new RaisedButton(child:new Text("Hello")),
// key: 1
// ),
// new FlexExpandingChild(
// new RaisedButton(child:new Text("Foo!")),
// key: 2
// )
// ]),
// right:0.0,
// top: 20.0
// )
]);
}
}
ImageMap _loader;
SpriteSheet _spriteSheet;
name: game
dependencies:
sky: '>=0.0.10 <1.0.0'
This diff was suppressed by a .gitattributes entry.
{"frames": [
{
"filename": "arrow.png",
"frame": {"x":2,"y":2,"w":446,"h":283},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":30,"y":49,"w":446,"h":283},
"sourceSize": {"w":512,"h":512},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_0.nrm.png",
"frame": {"x":2,"y":287,"w":200,"h":188},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":200,"h":188},
"sourceSize": {"w":200,"h":188},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_0.png",
"frame": {"x":204,"y":287,"w":200,"h":188},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":200,"h":188},
"sourceSize": {"w":200,"h":188},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_1.nrm.png",
"frame": {"x":545,"y":275,"w":204,"h":166},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":204,"h":166},
"sourceSize": {"w":204,"h":166},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_1.png",
"frame": {"x":589,"y":2,"w":204,"h":166},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":204,"h":166},
"sourceSize": {"w":204,"h":166},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_2.nrm.png",
"frame": {"x":795,"y":2,"w":194,"h":165},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":194,"h":165},
"sourceSize": {"w":194,"h":165},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_2.png",
"frame": {"x":795,"y":169,"w":194,"h":165},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":0,"y":2,"w":194,"h":165},
"sourceSize": {"w":194,"h":167},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_0.nrm.png",
"frame": {"x":646,"y":170,"w":102,"h":84},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":102,"h":84},
"sourceSize": {"w":102,"h":84},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_0.png",
"frame": {"x":862,"y":336,"w":102,"h":84},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":102,"h":84},
"sourceSize": {"w":102,"h":84},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_1.nrm.png",
"frame": {"x":450,"y":171,"w":96,"h":102},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":96,"h":102},
"sourceSize": {"w":96,"h":102},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_1.png",
"frame": {"x":548,"y":171,"w":96,"h":102},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":0,"y":0,"w":96,"h":102},
"sourceSize": {"w":96,"h":106},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_2.nrm.png",
"frame": {"x":751,"y":336,"w":109,"h":84},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":109,"h":84},
"sourceSize": {"w":109,"h":84},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_2.png",
"frame": {"x":751,"y":422,"w":109,"h":84},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":109,"h":84},
"sourceSize": {"w":109,"h":84},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "laser.png",
"frame": {"x":751,"y":170,"w":37,"h":76},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":37,"h":76},
"sourceSize": {"w":37,"h":76},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "ship.nrm.png",
"frame": {"x":406,"y":287,"w":137,"h":167},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":137,"h":167},
"sourceSize": {"w":137,"h":167},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "ship.png",
"frame": {"x":450,"y":2,"w":137,"h":167},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":25,"y":10,"w":137,"h":167},
"sourceSize": {"w":188,"h":188},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "star.png",
"frame": {"x":862,"y":422,"w":62,"h":68},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":11,"y":5,"w":62,"h":68},
"sourceSize": {"w":82,"h":78},
"pivot": {"x":0.5,"y":0.5}
}],
"meta": {
"app": "http://www.codeandweb.com/texturepacker",
"version": "1.0",
"image": "sprites.png",
"format": "RGBA8888",
"size": {"w":991,"h":508},
"scale": "1",
"smartupdate": "$TexturePacker:SmartUpdate:b79d98a34caa23746c4e2af6dd5b8506:bfdb7027c351003110a2082bbb53a657:1eabdf11f75e3a4fe3147baf7b5be24b$"
}
}
This diff was suppressed by a .gitattributes entry.
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:sky/framework/fn.dart';
class HelloWorldApp extends App {
UINode build() {
return new Text('Hello, world!');
}
}
<script>
import 'hello_world.dart';
void main() {
new HelloWorldApp();
}
</script>
name: hello_world
dependencies:
sky: any
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/box.dart';
class RenderSolidColorBox extends RenderDecoratedBox {
final Size desiredSize;
final Color backgroundColor;
RenderSolidColorBox(Color backgroundColor, { this.desiredSize: Size.infinite })
: backgroundColor = backgroundColor,
super(decoration: new BoxDecoration(backgroundColor: backgroundColor));
double getMinIntrinsicWidth(BoxConstraints constraints) {
return constraints.constrainHeight(
this.desiredSize == Size.infinite ? 0.0 : desiredSize.width
);
}
double getMaxIntrinsicWidth(BoxConstraints constraints) {
return constraints.constrainWidth(
this.desiredSize == Size.infinite ? 0.0 : desiredSize.width
);
}
double getMinIntrinsicHeight(BoxConstraints constraints) {
return constraints.constrainHeight(
this.desiredSize == Size.infinite ? 0.0 : desiredSize.height
);
}
double getMaxIntrinsicHeight(BoxConstraints constraints) {
return constraints.constrainHeight(
this.desiredSize == Size.infinite ? 0.0 : desiredSize.height
);
}
void performLayout() {
size = constraints.constrain(desiredSize);
}
void handleEvent(sky.Event event, BoxHitTestEntry entry) {
if (event.type == 'pointerdown')
decoration = new BoxDecoration(backgroundColor: const Color(0xFFFF0000));
else if (event.type == 'pointerup')
decoration = new BoxDecoration(backgroundColor: backgroundColor);
}
}
This diff is collapsed.
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
void drawText(sky.Canvas canvas, String lh) {
sky.Paint paint = new sky.Paint();
// offset down
canvas.translate(0.0, 100.0);
// set up the text
sky.Document document = new sky.Document();
sky.Text arabic = document.createText("مرحبا");
sky.Text english = document.createText(" Hello");
sky.Element block = document.createElement('div');
block.style['display'] = 'paragraph';
block.style['font-family'] = 'monospace';
block.style['font-size'] = '50px';
block.style['line-height'] = lh;
block.style['color'] = '#0000A0';
block.appendChild(arabic);
block.appendChild(english);
sky.LayoutRoot layoutRoot = new sky.LayoutRoot();
layoutRoot.rootElement = block;
layoutRoot.maxWidth = sky.view.width - 20.0; // you need to set a width for this to paint
layoutRoot.layout();
// draw a line at the text's baseline
sky.Path path = new sky.Path();
path.moveTo(0.0, 0.0);
path.lineTo(block.maxContentWidth, 0.0);
path.moveTo(0.0, block.alphabeticBaseline);
path.lineTo(block.maxContentWidth, block.alphabeticBaseline);
path.moveTo(0.0, block.height);
path.lineTo(block.maxContentWidth, block.height);
paint.color = const sky.Color(0xFFFF9000);
paint.setStyle(sky.PaintingStyle.stroke);
paint.strokeWidth = 3.0;
canvas.drawPath(path, paint);
// paint the text
layoutRoot.paint(canvas);
}
void main() {
// prepare the rendering
sky.PictureRecorder recorder = new sky.PictureRecorder();
sky.Canvas canvas = new sky.Canvas(recorder, sky.view.width, sky.view.height);
// background
sky.Paint paint = new sky.Paint();
paint.color = const sky.Color(0xFFFFFFFF);
paint.setStyle(sky.PaintingStyle.fill);
canvas.drawRect(new sky.Rect.fromLTRB(0.0, 0.0, sky.view.width, sky.view.height), paint);
canvas.translate(10.0, 0.0);
drawText(canvas, '1.0');
drawText(canvas, 'lh');
// put it on the screen
sky.view.picture = recorder.endRecording();
sky.view.scheduleFrame();
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import "dart:math";
import 'dart:sky';
Picture draw(int a, int r, int g, int b) {
double width = view.width;
double height = view.height;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, width, height);
double radius = min(width, height) * 0.45;
Paint paint = new Paint()..color = new Color.fromARGB(a, r, g, b);
canvas.drawCircle(width / 2, height / 2, radius, paint);
return recorder.endRecording();
}
bool handleEvent(Event event) {
if (event.type == "pointerdown") {
view.picture = draw(255, 0, 0, 255);
view.scheduleFrame();
return true;
}
if (event.type == "pointerup") {
view.picture = draw(255, 0, 255, 0);
view.scheduleFrame();
return true;
}
if (event.type == "back") {
print("Pressed back button.");
return true;
}
return false;
}
void main() {
print("Hello, world");
view.picture = draw(255, 0, 255, 0);
view.scheduleFrame();
view.setEventCallback(handleEvent);
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import "dart:math";
import 'dart:sky';
import 'package:sky/framework/shell.dart' as shell;
import 'package:mojom/intents/intents.mojom.dart';
Picture draw(int a, int r, int g, int b) {
double width = view.width;
double height = view.height;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, width, height);
double radius = min(width, height) * 0.45;
Paint paint = new Paint()..color = new Color.fromARGB(a, r, g, b);
canvas.drawRect(new Rect.fromSize(new Size(width, height)), paint);
return recorder.endRecording();
}
bool handleEvent(Event event) {
if (event.type == "pointerdown") {
view.picture = draw(255, 0, 0, 255);
view.scheduleFrame();
return true;
}
if (event.type == "pointerup") {
view.picture = draw(255, 255, 255, 0);
view.scheduleFrame();
ActivityManagerProxy activityManager = new ActivityManagerProxy.unbound();
Intent intent = new Intent()
..action = 'android.intent.action.VIEW'
..url = 'sky://localhost:9888/sky/examples/raw/hello_world.dart';
shell.requestService(null, activityManager);
activityManager.ptr.startActivity(intent);
return true;
}
if (event.type == "back") {
print("Pressed back button.");
return true;
}
return false;
}
void main() {
print("Hello, world");
view.picture = draw(255, 255, 255, 0);
view.scheduleFrame();
view.setEventCallback(handleEvent);
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'dart:math' as math;
import 'dart:typed_data';
void beginFrame(double timeStamp) {
sky.PictureRecorder recorder = new sky.PictureRecorder();
Canvas canvas = new Canvas(recorder, sky.view.width, 200.0);
sky.Paint paint = new sky.Paint();
sky.Point mid = new sky.Point(sky.view.width / 2.0, sky.view.height / 2.0);
double radius = math.min(mid.x, mid.y);
canvas.drawPaint(new sky.Paint()..color = const sky.Color(0xFFFFFFFF));
canvas.save();
canvas.translate(-mid.x/2.0, sky.view.height*2.0);
canvas.clipRect(
new sky.Rect.fromLTRB(0.0, -sky.view.height, sky.view.width, radius));
canvas.translate(mid.x, mid.y);
paint.color = const sky.Color.fromARGB(128, 255, 0, 255);
canvas.rotate(math.PI/4.0);
sky.Gradient yellowBlue = new sky.Gradient.linear(
[new sky.Point(-radius, -radius), new sky.Point(0.0, 0.0)],
[const sky.Color(0xFFFFFF00), const sky.Color(0xFF0000FF)]);
canvas.drawRect(new sky.Rect.fromLTRB(-radius, -radius, radius, radius),
new sky.Paint()..setShader(yellowBlue));
// Scale x and y by 0.5.
var scaleMatrix = new Float32List.fromList([
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0,
]);
canvas.concat(scaleMatrix);
paint.color = const sky.Color.fromARGB(128, 0, 255, 0);
canvas.drawCircle(0.0, 0.0, radius, paint);
canvas.restore();
canvas.translate(0.0, 50.0);
var builder = new sky.LayerDrawLooperBuilder()
..addLayerOnTop(
new sky.DrawLooperLayerInfo()
..setOffset(const sky.Point(150.0, 0.0))
..setColorMode(sky.TransferMode.src)
..setPaintBits(sky.PaintBits.all),
(sky.Paint layerPaint) {
layerPaint.color = const sky.Color.fromARGB(128, 255, 255, 0);
layerPaint.setColorFilter(new sky.ColorFilter.mode(
const sky.Color.fromARGB(128, 0, 0, 255), sky.TransferMode.srcIn));
layerPaint.setMaskFilter(new sky.MaskFilter.blur(
sky.BlurStyle.normal, 3.0, highQuality: true));
})
..addLayerOnTop(
new sky.DrawLooperLayerInfo()
..setOffset(const sky.Point(75.0, 75.0))
..setColorMode(sky.TransferMode.src)
..setPaintBits(sky.PaintBits.shader),
(sky.Paint layerPaint) {
sky.Gradient redYellow = new sky.Gradient.radial(
new sky.Point(0.0, 0.0), radius/3.0,
[const sky.Color(0xFFFFFF00), const sky.Color(0xFFFF0000)],
null, sky.TileMode.mirror);
layerPaint.setShader(redYellow);
// Since we're don't set sky.PaintBits.maskFilter, this has no effect.
layerPaint.setMaskFilter(new sky.MaskFilter.blur(
sky.BlurStyle.normal, 50.0, highQuality: true));
})
..addLayerOnTop(
new sky.DrawLooperLayerInfo()..setOffset(const sky.Point(225.0, 75.0)),
(sky.Paint layerPaint) {
// Since this layer uses a DST color mode, this has no effect.
layerPaint.color = const sky.Color.fromARGB(128, 255, 0, 0);
});
paint.setDrawLooper(builder.build());
canvas.drawCircle(0.0, 0.0, radius, paint);
sky.view.picture = recorder.endRecording();
}
void main() {
sky.view.setBeginFrameCallback(beginFrame);
sky.view.scheduleFrame();
}
name: raw
dependencies:
sky: any
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
void beginFrame(double timeStamp) {
var size = 100.0;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, view.width, view.height);
canvas.translate(size + 10.0, size + 10.0);
Paint paint = new Paint();
paint.color = const Color.fromARGB(255, 0, 255, 0);
var builder = new LayerDrawLooperBuilder()
// Shadow layer.
..addLayerOnTop(
new DrawLooperLayerInfo()
..setPaintBits(PaintBits.all)
..setOffset(const Point(5.0, 5.0))
..setColorMode(TransferMode.src),
(Paint layerPaint) {
layerPaint.color = const Color.fromARGB(128, 55, 55, 55);
layerPaint.setMaskFilter(
new MaskFilter.blur(BlurStyle.normal, 5.0, highQuality: true));
})
// Main layer.
..addLayerOnTop(new DrawLooperLayerInfo(), (Paint) {});
paint.setDrawLooper(builder.build());
canvas.drawPaint(
new Paint()..color = const Color.fromARGB(255, 255, 255, 255));
canvas.drawRect(new Rect.fromLTRB(-size, -size, size, size), paint);
view.picture = recorder.endRecording();
}
void main() {
view.setBeginFrameCallback(beginFrame);
view.scheduleFrame();
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import "dart:math" as math;
import 'dart:sky';
double timeBase = null;
LayoutRoot layoutRoot = new LayoutRoot();
void beginFrame(double timeStamp) {
if (timeBase == null)
timeBase = timeStamp;
double delta = timeStamp - timeBase;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, view.width, view.height);
canvas.translate(view.width / 2.0, view.height / 2.0);
canvas.rotate(math.PI * delta / 1800);
canvas.drawRect(new Rect.fromLTRB(-100.0, -100.0, 100.0, 100.0),
new Paint()..color = const Color.fromARGB(255, 0, 255, 0));
double sin = math.sin(delta / 200);
layoutRoot.maxWidth = 150.0 + (50 * sin);
layoutRoot.layout();
canvas.translate(layoutRoot.maxWidth / -2.0, (layoutRoot.maxWidth / 2.0) - 125);
layoutRoot.paint(canvas);
view.picture = recorder.endRecording();
view.scheduleFrame();
}
void main() {
var document = new Document();
var arabic = document.createText("هذا هو قليلا طويلة من النص الذي يجب التفاف .");
var more = document.createText(" و أكثر قليلا لجعله أطول. ");
var block = document.createElement('p');
block.style['display'] = 'paragraph';
block.style['direction'] = 'rtl';
block.style['unicode-bidi'] = 'plaintext';
block.appendChild(arabic);
block.appendChild(more);
layoutRoot.rootElement = block;
view.setBeginFrameCallback(beginFrame);
view.scheduleFrame();
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:sky';
import 'package:sky/mojo/net/image_cache.dart' as image_cache;
double timeBase = null;
Image image = null;
String url1 = "https://www.dartlang.org/logos/dart-logo.png";
String url2 = "http://i2.kym-cdn.com/photos/images/facebook/000/581/296/c09.jpg";
void beginFrame(double timeStamp) {
if (timeBase == null) timeBase = timeStamp;
double delta = timeStamp - timeBase;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, view.width, view.height);
canvas.translate(view.width / 2.0, view.height / 2.0);
canvas.rotate(math.PI * delta / 1800);
canvas.scale(0.2, 0.2);
Paint paint = new Paint()..color = const Color.fromARGB(255, 0, 255, 0);
// Draw image
if (image != null)
canvas.drawImage(image, -image.width / 2.0, -image.height / 2.0, paint);
// Draw cut out of image
canvas.rotate(math.PI * delta / 1800);
if (image != null) {
var w = image.width.toDouble();
var h = image.width.toDouble();
canvas.drawImageRect(image,
new Rect.fromLTRB(w * 0.25, h * 0.25, w * 0.75, h * 0.75),
new Rect.fromLTRB(-w / 4.0, -h / 4.0, w / 4.0, h / 4.0),
paint);
}
view.picture = recorder.endRecording();
view.scheduleFrame();
}
void handleImageLoad(result) {
if (result != image) {
print("${result.width}x${result.width} image loaded!");
image = result;
view.scheduleFrame();
} else {
print("Existing image was loaded again");
}
}
bool handleEvent(Event event) {
if (event.type == "pointerdown") {
return true;
}
if (event.type == "pointerup") {
image_cache.load(url2, handleImageLoad);
return true;
}
return false;
}
void main() {
image_cache.load(url1, handleImageLoad);
image_cache.load(url1, handleImageLoad);
view.setEventCallback(handleEvent);
view.setBeginFrameCallback(beginFrame);
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
import 'dart:math' as math;
double timeBase = null;
void beginFrame(double timeStamp) {
tracing.begin('beginFrame');
if (timeBase == null)
timeBase = timeStamp;
double delta = timeStamp - timeBase;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, view.width, view.height);
canvas.translate(view.width / 2.0, view.height / 2.0);
canvas.rotate(math.PI * delta / 1800);
canvas.drawRect(new Rect.fromLTRB(-100.0, -100.0, 100.0, 100.0),
new Paint()..color = const Color.fromARGB(255, 0, 255, 0));
view.picture = recorder.endRecording();
view.scheduleFrame();
tracing.end('beginFrame');
}
void main() {
view.setBeginFrameCallback(beginFrame);
view.scheduleFrame();
}
#!mojo mojo:sky_viewer
<sky>
<import src="/packages/sky/framework/debug/shake-to-reload.sky" />
<style>
dot {
position: absolute;
height: 10px;
width: 10px;
background-color: #00FF00;
border-radius: 5px;
opacity: .75;
}
log {
display: paragraph;
margin-top: 50px;
}
</style>
<log>Touch the screen!</log>
<script>
import "dart:sky";
// Material design colors. :p
List<String> colors = [
"#009688",
"#FFC107",
"#9C27B0",
"#03A9F4",
"#673AB7",
"#CDDC39",
];
Element whichDot(event) {
return document.querySelector('dot[id="${event.pointer}"]');
}
void moreDots(event) {
Element dot = document.createElement('dot');
dot.setAttribute('id', "${event.pointer}");
dot.style['background-color'] = colors[event.pointer.remainder(colors.length)];
document.querySelector('sky').appendChild(dot);
runToTheCenter(event);
}
void goAway(event) {
whichDot(event).remove();
}
void stopDots(event) {
for (Element e in document.querySelectorAll('dot'))
e.remove();
}
void runToTheCenter(event) {
double radius = (5 + (95 * event.pressure));
Element dot = whichDot(event);
dot.style["transform"] = "translate(${event.x-radius}px,${event.y-radius}px)";
dot.style["width"] = "${2 * radius}px";
dot.style["height"] = "${2 * radius}px";
dot.style["border-radius"] = "${radius}px";
}
void main() {
document.addEventListener("pointerdown", moreDots);
document.addEventListener("pointermove", runToTheCenter);
document.addEventListener("pointerup", goAway);
document.addEventListener("pointercancel", stopDots);
}
</script>
</sky>
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'package:sky/painting/text_style.dart';
import 'package:sky/rendering/block.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/paragraph.dart';
import 'package:sky/rendering/sky_binding.dart';
RenderBox getBox(double lh) {
RenderParagraph paragraph = new RenderParagraph(
new InlineStyle(
new TextStyle(),
[
new InlineText('test'),
new InlineStyle(
new TextStyle(
color: const Color(0xFF0000A0),
fontFamily: 'serif',
fontSize: 50.0,
height: lh
),
[new InlineText('مرحبا Hello')]
)
]
)
);
return new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 200.0),
child: new RenderDecoratedBox(
decoration: new BoxDecoration(
backgroundColor: const Color(0xFFFFFFFF)
),
child: new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderCustomPaint(
child: paragraph,
callback: (canvas, size) {
double baseline = paragraph.getDistanceToBaseline(TextBaseline.alphabetic);
double w = paragraph.getMaxIntrinsicWidth(new BoxConstraints.loose(size));
double h = paragraph.getMaxIntrinsicHeight(new BoxConstraints.loose(size));
Path path = new Path();
path.moveTo(0.0, 0.0);
path.lineTo(w, 0.0);
path.moveTo(0.0, baseline);
path.lineTo(w, baseline);
path.moveTo(0.0, h);
path.lineTo(w, h);
Paint paint = new Paint();
paint.color = const Color(0xFFFF9000);
paint.setStyle(sky.PaintingStyle.stroke);
paint.strokeWidth = 3.0;
canvas.drawPath(path, paint);
}
)
)
)
)
);
}
void main() {
RenderBox root = new RenderBlock(children: [
new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 50.0)
),
getBox(1.0),
getBox(null),
]);
var b = new SkyBinding(root: root);
// b.onFrame = b.debugDumpRenderTree;
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:sky' as sky;
import 'package:sky/rendering/block.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/sky_binding.dart';
void main() {
var root = new RenderBlock(children: [
new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 100.0),
child: new RenderDecoratedBox(
decoration: new BoxDecoration(
backgroundColor: new sky.Color(0xFFFFFF00)
)
)
)
),
new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 100.0),
child: new RenderDecoratedBox(
decoration: new BoxDecoration(
border: new Border(
top: new BorderSide(color: new sky.Color(0xFFF00000), width: 5.0),
right: new BorderSide(color: new sky.Color(0xFFFF9000), width: 10.0),
bottom: new BorderSide(color: new sky.Color(0xFFFFF000), width: 15.0),
left: new BorderSide(color: new sky.Color(0xFF00FF00), width: 20.0)
),
backgroundColor: new sky.Color(0xFFDDDDDD)
)
)
)
),
new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 100.0),
child: new RenderDecoratedBox(
decoration: new BoxDecoration(
backgroundColor: new sky.Color(0xFFFFFF00)
)
)
)
),
new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 100.0),
child: new RenderDecoratedBox(
decoration: new BoxDecoration(
backgroundColor: new sky.Color(0xFFFFFF00)
)
)
)
),
new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 100.0),
child: new RenderDecoratedBox(
decoration: new BoxDecoration(
backgroundColor: new sky.Color(0xFFFFFF00)
)
)
)
),
]);
new SkyBinding(root: root);
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
import 'dart:math' as math;
import 'package:sky/mojo/net/image_cache.dart' as image_cache;
import 'package:sky/painting/text_style.dart';
import 'package:sky/rendering/block.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/paragraph.dart';
import 'package:sky/rendering/sky_binding.dart';
import '../lib/solid_color_box.dart';
class Touch {
final double x;
final double y;
const Touch(this.x, this.y);
}
class RenderImageGrow extends RenderImage {
final Size _startingSize;
RenderImageGrow(String src, Size size) : _startingSize = size, super(src, size);
double _growth = 0.0;
double get growth => _growth;
void set growth(double value) {
_growth = value;
double newWidth = _startingSize.width == null ? null : _startingSize.width + growth;
double newHeight = _startingSize.height == null ? null : _startingSize.height + growth;
requestedSize = new Size(newWidth, newHeight);
}
}
RenderImageGrow image;
Map<int, Touch> touches = new Map();
void handleEvent(event) {
if (event is PointerEvent) {
if (event.type == 'pointermove')
image.growth = math.max(0.0, image.growth + event.x - touches[event.pointer].x);
touches[event.pointer] = new Touch(event.x, event.y);
}
}
void main() {
void addFlexChildSolidColor(RenderFlex parent, Color backgroundColor, { int flex: 0 }) {
RenderSolidColorBox child = new RenderSolidColorBox(backgroundColor);
parent.add(child);
child.parentData.flex = flex;
}
var row = new RenderFlex(direction: FlexDirection.horizontal);
// Left cell
addFlexChildSolidColor(row, const Color(0xFF00D2B8), flex: 1);
// Resizeable image
image = new RenderImageGrow("https://www.dartlang.org/logos/dart-logo.png",
new Size(100.0, null));
var padding = new RenderPadding(padding: const EdgeDims.all(10.0), child: image);
row.add(padding);
RenderFlex column = new RenderFlex(direction: FlexDirection.vertical);
// Top cell
addFlexChildSolidColor(column, const Color(0xFF55DDCA), flex: 1);
// The internet is a beautiful place. https://baconipsum.com/
String meatyString = """Bacon ipsum dolor amet ham fatback tri-tip, prosciutto
porchetta bacon kevin meatball meatloaf pig beef ribs chicken. Brisket ribeye
andouille leberkas capicola meatloaf. Chicken pig ball tip pork picanha bresaola
alcatra. Pork pork belly alcatra, flank chuck drumstick biltong doner jowl.
Pancetta meatball tongue tenderloin rump tail jowl boudin.""";
var text = new InlineStyle(
new TextStyle(color: const Color(0xFF009900)),
[new InlineText(meatyString)]);
padding = new RenderPadding(
padding: const EdgeDims.all(10.0),
child: new RenderParagraph(text));
column.add(padding);
// Bottom cell
addFlexChildSolidColor(column, const Color(0xFF0081C6), flex: 2);
row.add(column);
column.parentData.flex = 8;
RenderDecoratedBox root = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF)),
child: row
);
new SkyBinding(root: root);
view.setEventCallback(handleEvent);
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
import 'dart:math' as math;
import 'package:sky/rendering/block.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/paragraph.dart';
import 'package:sky/rendering/sky_binding.dart';
import '../lib/solid_color_box.dart';
// Attempts to draw
// http://www.w3.org/TR/2015/WD-css-flexbox-1-20150514/images/flex-pack.svg
void main() {
var table = new RenderFlex(direction: FlexDirection.vertical);
void addRow(FlexJustifyContent justify) {
RenderParagraph paragraph = new RenderParagraph(new InlineText("${justify}"));
table.add(new RenderPadding(child: paragraph, padding: new EdgeDims.only(top: 20.0)));
var row = new RenderFlex(direction: FlexDirection.horizontal);
row.add(new RenderSolidColorBox(const Color(0xFFFFCCCC), desiredSize: new Size(80.0, 60.0)));
row.add(new RenderSolidColorBox(const Color(0xFFCCFFCC), desiredSize: new Size(64.0, 60.0)));
row.add(new RenderSolidColorBox(const Color(0xFFCCCCFF), desiredSize: new Size(160.0, 60.0)));
row.justifyContent = justify;
table.add(row);
row.parentData.flex = 1;
}
addRow(FlexJustifyContent.flexStart);
addRow(FlexJustifyContent.flexEnd);
addRow(FlexJustifyContent.center);
addRow(FlexJustifyContent.spaceBetween);
addRow(FlexJustifyContent.spaceAround);
RenderDecoratedBox root = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF)),
child: new RenderPadding(child: table, padding: new EdgeDims.symmetric(vertical: 50.0))
);
new SkyBinding(root: root);
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
import 'package:sky/painting/text_style.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/paragraph.dart';
import 'package:sky/rendering/sky_binding.dart';
import '../lib/solid_color_box.dart';
void main() {
RenderFlex flexRoot = new RenderFlex(direction: FlexDirection.vertical);
RenderObject root = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFF606060)),
child: flexRoot
);
RenderObject child = new RenderSolidColorBox(const Color(0xFFFFFF00));
flexRoot.add(child);
child.parentData.flex = 2;
// The internet is a beautiful place. https://baconipsum.com/
String meatyString = """Bacon ipsum dolor amet ham fatback tri-tip, prosciutto
porchetta bacon kevin meatball meatloaf pig beef ribs chicken. Brisket ribeye
andouille leberkas capicola meatloaf. Chicken pig ball tip pork picanha bresaola
alcatra. Pork pork belly alcatra, flank chuck drumstick biltong doner jowl.
Pancetta meatball tongue tenderloin rump tail jowl boudin.""";
var text = new InlineStyle(
new TextStyle(color: const Color(0xFF009900)),
[new InlineText(meatyString)]);
child = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF)),
child: new RenderParagraph(text)
);
flexRoot.add(child);
child.parentData.flex = 1;
new SkyBinding(root: root);
}
This diff is collapsed.
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/sky_binding.dart';
import 'package:sky/theme/colors.dart';
import 'package:sky/theme/shadows.dart';
void main() {
var coloredBox = new RenderDecoratedBox(
decoration: new BoxDecoration(
gradient: new RadialGradient(
center: Point.origin, radius: 500.0,
colors: [Yellow[500], Blue[500]]),
boxShadow: shadows[3])
);
var paddedBox = new RenderPadding(
padding: const EdgeDims.all(50.0),
child: coloredBox);
new SkyBinding(root: new RenderDecoratedBox(
decoration: const BoxDecoration(
backgroundColor: const Color(0xFFFFFFFF)
),
child: paddedBox
));
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'dart:math' as math;
import 'package:sky/base/scheduler.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/sky_binding.dart';
import 'package:vector_math/vector_math.dart';
import '../lib/solid_color_box.dart';
double timeBase;
RenderTransform transformBox;
void main() {
RenderFlex flexRoot = new RenderFlex(direction: FlexDirection.vertical);
void addFlexChildSolidColor(RenderFlex parent, sky.Color backgroundColor, { int flex: 0 }) {
RenderSolidColorBox child = new RenderSolidColorBox(backgroundColor);
parent.add(child);
child.parentData.flex = flex;
}
addFlexChildSolidColor(flexRoot, const sky.Color(0xFFFF00FF), flex: 1);
addFlexChildSolidColor(flexRoot, const sky.Color(0xFFFFFF00), flex: 2);
addFlexChildSolidColor(flexRoot, const sky.Color(0xFF00FFFF), flex: 1);
transformBox = new RenderTransform(child: flexRoot, transform: new Matrix4.identity());
RenderPadding root = new RenderPadding(padding: new EdgeDims.all(20.0), child: transformBox);
new SkyBinding(root: root);
addPersistentFrameCallback(rotate);
}
void rotate(double timeStamp) {
if (timeBase == null)
timeBase = timeStamp;
double delta = (timeStamp - timeBase) / 1000; // radians
transformBox.setIdentity();
transformBox.translate(transformBox.size.width / 2.0, transformBox.size.height / 2.0);
transformBox.rotateZ(delta);
transformBox.translate(-transformBox.size.width / 2.0, -transformBox.size.height / 2.0);
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'dart:sky';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/paragraph.dart';
import 'package:sky/rendering/sky_binding.dart';
import 'package:sky/rendering/stack.dart';
import 'package:sky/theme/colors.dart';
// Material design colors. :p
List<Color> colors = [
Teal[500],
Amber[500],
Purple[500],
LightBlue[500],
DeepPurple[500],
Lime[500],
];
class Dot {
final Paint _paint;
double x = 0.0;
double y = 0.0;
double radius = 0.0;
Dot({ Color color }) : _paint = new Paint()..color = color;
void update(PointerEvent event) {
x = event.x;
y = event.y;
radius = 5 + (95 * event.pressure);
}
void paint(RenderCanvas canvas) {
canvas.drawCircle(x, y, radius, _paint);
}
}
class RenderTouchDemo extends RenderBox {
Map<int, Dot> dots = new Map();
RenderTouchDemo();
void handleEvent(Event event, BoxHitTestEntry entry) {
switch (event.type) {
case 'pointerdown':
Color color = colors[event.pointer.remainder(colors.length)];
dots[event.pointer] = new Dot(color: color)..update(event);
break;
case 'pointerup':
dots.remove(event.pointer);
break;
case 'pointercancel':
dots = new Map();
break;
case 'pointermove':
dots[event.pointer].update(event);
break;
}
markNeedsPaint();
}
void performLayout() {
size = constraints.constrain(Size.infinite);
}
void paint(RenderCanvas canvas) {
Paint white = new Paint()..color = const Color(0xFFFFFFFF);
canvas.drawRect(new Rect.fromSize(size), white);
for (Dot dot in dots.values)
dot.paint(canvas);
}
}
void main() {
var paragraph = new RenderParagraph(new InlineText("Touch me!"));
var stack = new RenderStack(children: [
new RenderTouchDemo(),
paragraph,
]);
// Prevent the RenderParagraph from filling the whole screen so
// that it doesn't eat events.
paragraph.parentData..top = 40.0
..left = 20.0;
new SkyBinding(root: stack);
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/sky_binding.dart';
import 'package:vector_math/vector_math.dart';
void main() {
RenderDecoratedBox green = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const sky.Color(0xFF00FF00))
);
RenderConstrainedBox box = new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tight(const Size(200.0, 200.0)),
child: green
);
Matrix4 transform = new Matrix4.identity();
RenderTransform spin = new RenderTransform(
transform: transform, child: box);
spin.rotateZ(1.0);
RenderFlex flex = new RenderFlex();
flex.add(spin);
new SkyBinding(root: flex);
}
This sample app is our main test harness right now.
Follow these steps to make sure everything works, comparing the
results to earlier builds:
1. Load the app
2. Scroll down and up.
3. Fling down.
4. Fling up. Verify that it bounces at the top.
5. Tap on rows. Make sure they get ink splashes.
6. Open the drawer.
7. Slide the drawer in and out.
8. Check that you can change the radio buttons.
9. Check for ink splashes on each row but not in the header.
10. Check that you can't scroll the list with the drawer out.
11. Close the drawer.
12. Open the menu.
13. Check the checkbox.
14. Open the menu. Verify the checkbox is checked.
15. Tap another menu item.
16. Hit search.
17. Type a query like "XXI".
18. Dismiss the keyboard.
19. Scroll the list. Verify that you can't overscroll.
20. Tap the search bar. Verify the keyboard comes back.
21. Switch to the voice keyboard. Verify that that keyboard works.
22. Hit the back button.
23. Verify that the floating action button gets ink splashes.
These steps carefully avoid known bugs. See:
https://github.com/domokit/mojo/labels/stock%20demo
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'package:sky/framework/fn.dart';
import 'package:sky/framework/layout.dart';
class StockArrow extends Component {
static final Style _style = new Style('''
width: 40px;
height: 40px;
align-items: center;
justify-content: center;
border-radius: 40px;
margin-right: 16px;
border: 1px solid transparent;'''
);
static final Style _upStyle = new Style('''
width: 0;
height: 0;
border-left: 9px solid transparent;
border-right: 9px solid transparent;
margin-bottom: 3px;
border-bottom: 9px solid white;'''
);
static final Style _downStyle = new Style('''
width: 0;
height: 0;
border-left: 9px solid transparent;
border-right: 9px solid transparent;
margin-top: 3px;
border-top: 9px solid white'''
);
double percentChange;
StockArrow({ Object key, this.percentChange }) : super(key: key);
// TODO(abarth): These should use sky/framework/theme/colors.dart.
final List<String> _kRedColors = [
'#E57373',
'#EF5350',
'#F44336',
'#E53935',
'#D32F2F',
'#C62828',
'#B71C1C',
];
// TODO(abarth): These should use sky/framework/theme/colors.dart.
final List<String> _kGreenColors = [
'#81C784',
'#66BB6A',
'#4CAF50',
'#43A047',
'#388E3C',
'#2E7D32',
'#1B5E20',
];
int _colorIndexForPercentChange(double percentChange) {
// Currently the max is 10%.
double maxPercent = 10.0;
return max(0, ((percentChange.abs() / maxPercent) * _kGreenColors.length).floor());
}
String _colorForPercentChange(double percentChange) {
if (percentChange > 0)
return _kGreenColors[_colorIndexForPercentChange(percentChange)];
return _kRedColors[_colorIndexForPercentChange(percentChange)];
}
UINode build() {
String border = _colorForPercentChange(percentChange).toString();
bool up = percentChange > 0;
String type = up ? 'bottom' : 'top';
return new FlexContainer(
inlineStyle: 'border-color: $border',
direction: FlexDirection.Row,
style: _style,
children: [
new Container(
inlineStyle: 'border-$type-color: $border',
style: up ? _upStyle : _downStyle
)
]
);
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
#!mojo mojo:sky_viewer
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-->
<sky>
<script>
// TODO(abarth): Should this be package:stocks/stocks_app.dart?
import 'lib/stock_app.dart';
void main() {
new StocksApp();
}
</script>
</sky>
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment