Move example out of sky/packages to //examples

This commit is contained in:
Ian Fischer
2015-08-07 14:42:20 -07:00
parent 9154bfed29
commit 4a75fbeff9
13 changed files with 613 additions and 7 deletions

View File

@@ -62,10 +62,11 @@ Thumbs.db
/tools/grit/
# dart packages directories and related.
/examples/**/packages
/examples/**/pubspec.lock
/mojo/dart/apptest/packages
/mojo/dart/mojo_services/packages
/mojo/dart/mojo_services/pubspec.lock
/mojo/dart/mojom/bin/packages
/mojo/dart/mojom/packages
/mojo/dart/mojom/test/packages

View File

@@ -46,7 +46,7 @@ target. Building on MacOS for Android, iOS, and a head-less MacOS target is comi
* (Only the first time) `sudo ./build/install-build-deps-android.sh`
* `./sky/tools/gn --android`
* `ninja -C out/android_Debug`
* `./sky/tools/shelldb start out/android_Debug/ sky/packages/sky/example/hello_world/lib/main.dart`
* `./sky/tools/shelldb start out/android_Debug/ examples/hello_world/lib/main.dart`
### Desktop (Mac and Linux)

View File

@@ -120,7 +120,7 @@ def Main():
help='Path to the simulator application.')
parser.add_argument('-t', dest='target', required=False,
default='sky/packages/sky/example/demo_launcher/lib/main.dart',
default='examples/demo_launcher/lib/main.dart',
help='Sky server-relative path to the Sky app to run.')
parser.add_argument('-s', dest='server', required=False,

View File

@@ -0,0 +1,17 @@
# 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.
group("examples") {
testonly = true
deps = [
"//examples/demo_launcher",
"//examples/fitness",
"//examples/game",
"//examples/mine_digger",
"//examples/rendering",
"//examples/stocks",
"//examples/widgets",
]
}

View File

@@ -0,0 +1,16 @@
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.

View File

@@ -0,0 +1,149 @@
// 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/editing/input.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/theme/typography.dart' as typography;
import 'package:sky/widgets.dart';
class Field extends Component {
Field({
Key key,
this.inputKey,
this.icon,
this.placeholder
}): super(key: key);
final GlobalKey inputKey;
final String icon;
final String placeholder;
Widget build() {
return new Flex([
new Padding(
padding: const EdgeDims.symmetric(horizontal: 16.0),
child: new Icon(type: icon, size: 24)
),
new Flexible(
child: new Input(
key: inputKey,
placeholder: placeholder
)
)
],
direction: FlexDirection.horizontal
);
}
}
class AddressBookApp extends App {
Widget buildToolBar(Navigator navigator) {
return new ToolBar(
left: new IconButton(icon: "navigation/arrow_back"),
right: [new IconButton(icon: "navigation/check")]
);
}
Widget buildFloatingActionButton(Navigator navigator) {
return new FloatingActionButton(
child: new Icon(type: 'image/photo_camera', size: 24),
backgroundColor: Theme.of(this).accentColor,
onPressed: () {
showDialog(navigator, (navigator) {
return new Dialog(
title: new Text("Describe your picture"),
content: new ScrollableBlock([
new Field(inputKey: fillKey, icon: "editor/format_color_fill", placeholder: "Color"),
new Field(inputKey: emoticonKey, icon: "editor/insert_emoticon", placeholder: "Emotion"),
]),
onDismiss: navigator.pop,
actions: [
new FlatButton(
child: new Text('DISCARD'),
onPressed: navigator.pop
),
new FlatButton(
child: new Text('SAVE'),
onPressed: () {
navigator.pop();
}
),
]
);
});
}
);
}
static final GlobalKey nameKey = new GlobalKey();
static final GlobalKey phoneKey = new GlobalKey();
static final GlobalKey emailKey = new GlobalKey();
static final GlobalKey addressKey = new GlobalKey();
static final GlobalKey ringtoneKey = new GlobalKey();
static final GlobalKey noteKey = new GlobalKey();
static final GlobalKey fillKey = new GlobalKey();
static final GlobalKey emoticonKey = new GlobalKey();
Widget buildBody(Navigator navigator) {
return new Material(
child: new ScrollableBlock([
new AspectRatio(
aspectRatio: 16.0 / 9.0,
child: new Container(
decoration: new BoxDecoration(backgroundColor: colors.Purple[300])
)
),
new Field(inputKey: nameKey, icon: "social/person", placeholder: "Name"),
new Field(inputKey: phoneKey, icon: "communication/phone", placeholder: "Phone"),
new Field(inputKey: emailKey, icon: "communication/email", placeholder: "Email"),
new Field(inputKey: addressKey, icon: "maps/place", placeholder: "Address"),
new Field(inputKey: ringtoneKey, icon: "av/volume_up", placeholder: "Ringtone"),
new Field(inputKey: noteKey, icon: "content/add", placeholder: "Add note"),
])
);
}
Widget buildMain(Navigator navigator) {
return new Scaffold(
toolbar: buildToolBar(navigator),
body: buildBody(navigator),
floatingActionButton: buildFloatingActionButton(navigator)
);
}
NavigationState _navigationState;
void initState() {
_navigationState = new NavigationState([
new Route(
name: '/',
builder: (navigator, route) => buildMain(navigator)
),
]);
super.initState();
}
Widget build() {
ThemeData theme = new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Teal,
accentColor: colors.PinkAccent[100]
);
return new Theme(
data: theme,
child: new DefaultTextStyle(
style: typography.error, // if you see this, you've forgotten to correctly configure the text style!
child: new TaskDescription(
label: 'Address Book',
child: new Navigator(_navigationState)
)
)
);
}
}
void main() {
runApp(new AddressBookApp());
}

View File

@@ -0,0 +1,15 @@
// 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/widgets.dart';
class HelloWorldApp extends App {
Widget build() {
return new Center(child: new Text('Hello, world!'));
}
}
void main() {
runApp(new HelloWorldApp());
}

View File

@@ -0,0 +1,13 @@
# 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("//sky/build/sky_app.gni")
sky_app("mine_digger") {
main_dart = "lib/main.dart"
if (is_android) {
apk_name = "MineDigger"
}
}

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 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.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.domokit.mine_digger">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:name="org.domokit.sky.shell.SkyApplication" android:label="Mine Digger">
<activity android:name="org.domokit.sky.shell.SkyActivity"
android:launchMode="singleTask"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize"
android:hardwareAccelerated="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,365 @@
// 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';
import 'package:sky/painting/text_style.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/widgets.dart';
// Classic minesweeper-inspired game. The mouse controls are standard
// except for left + right combo which is not implemented. For touch,
// the duration of the pointer determines probing versus flagging.
//
// There are only 3 classes to understand. MineDiggerApp, which is
// contains all the logic and two classes that describe the mines:
// CoveredMineNode and ExposedMineNode, none of them holding state.
// Colors for each mine count (0-8):
const List<TextStyle> textStyles = const <TextStyle>[
const TextStyle(color: const Color(0xFF555555), fontWeight: bold),
const TextStyle(color: const Color(0xFF0094FF), fontWeight: bold), // blue
const TextStyle(color: const Color(0xFF13A023), fontWeight: bold), // green
const TextStyle(color: const Color(0xFFDA1414), fontWeight: bold), // red
const TextStyle(color: const Color(0xFF1E2347), fontWeight: bold), // black
const TextStyle(color: const Color(0xFF7F0037), fontWeight: bold), // dark red
const TextStyle(color: const Color(0xFF000000), fontWeight: bold),
const TextStyle(color: const Color(0xFF000000), fontWeight: bold),
const TextStyle(color: const Color(0xFF000000), fontWeight: bold),
];
enum CellState { covered, exploded, cleared, flagged, shown }
class MineDiggerApp extends App {
static const int rows = 9;
static const int cols = 9;
static const int totalMineCount = 11;
bool alive;
bool hasWon;
int detectedCount;
// |cells| keeps track of the positions of the mines.
List<List<bool>> cells;
// |uiState| keeps track of the visible player progess.
List<List<CellState>> uiState;
void initState() {
resetGame();
}
void resetGame() {
alive = true;
hasWon = false;
detectedCount = 0;
// Build the arrays.
cells = new List<List<bool>>();
uiState = new List<List<CellState>>();
for (int iy = 0; iy != rows; iy++) {
cells.add(new List<bool>());
uiState.add(new List<CellState>());
for (int ix = 0; ix != cols; ix++) {
cells[iy].add(false);
uiState[iy].add(CellState.covered);
}
}
// Place the mines.
Random random = new Random();
int cellsRemaining = rows * cols;
int minesRemaining = totalMineCount;
for (int x = 0; x < cols; x += 1) {
for (int y = 0; y < rows; y += 1) {
if (random.nextInt(cellsRemaining) < minesRemaining) {
cells[y][x] = true;
minesRemaining -= 1;
if (minesRemaining <= 0)
return;
}
cellsRemaining -= 1;
}
}
assert(false);
}
Stopwatch longPressStopwatch;
PointerEventListener _pointerDownHandlerFor(int posX, int posY) {
return (sky.PointerEvent event) {
if (event.buttons == 1) {
probe(posX, posY);
} else if (event.buttons == 2) {
flag(posX, posY);
} else {
// Touch event.
longPressStopwatch = new Stopwatch()..start();
}
};
}
PointerEventListener _pointerUpHandlerFor(int posX, int posY) {
return (sky.PointerEvent event) {
if (longPressStopwatch == null)
return;
// Pointer down was a touch event.
if (longPressStopwatch.elapsedMilliseconds < 250) {
probe(posX, posY);
} else {
// Long press flags.
flag(posX, posY);
}
longPressStopwatch = null;
};
}
Widget buildBoard() {
bool hasCoveredCell = false;
List<Flex> flexRows = <Flex>[];
for (int iy = 0; iy != 9; iy++) {
List<Widget> row = <Widget>[];
for (int ix = 0; ix != 9; ix++) {
CellState state = uiState[iy][ix];
int count = mineCount(ix, iy);
if (!alive) {
if (state != CellState.exploded)
state = cells[iy][ix] ? CellState.shown : state;
}
if (state == CellState.covered) {
row.add(new Listener(
onPointerDown: _pointerDownHandlerFor(ix, iy),
onPointerUp: _pointerUpHandlerFor(ix, iy),
child: new CoveredMineNode(
flagged: false,
posX: ix,
posY: iy
)
));
// Mutating |hasCoveredCell| here is hacky, but convenient, same
// goes for mutating |hasWon| below.
hasCoveredCell = true;
} else if (state == CellState.flagged) {
row.add(new CoveredMineNode(
flagged: true,
posX: ix,
posY: iy
));
} else {
row.add(new ExposedMineNode(
state: state,
count: count
));
}
}
flexRows.add(
new Flex(
row,
direction: FlexDirection.horizontal,
justifyContent: FlexJustifyContent.center,
key: new Key.stringify(iy)
)
);
}
if (!hasCoveredCell) {
// all cells uncovered. Are all mines flagged?
if ((detectedCount == totalMineCount) && alive) {
hasWon = true;
}
}
return new Container(
padding: new EdgeDims.all(10.0),
margin: new EdgeDims.all(10.0),
decoration: new BoxDecoration(backgroundColor: const Color(0xFF6B6B6B)),
child: new Flex(
flexRows,
direction: FlexDirection.vertical
)
);
}
Widget buildToolBar() {
String toolbarCaption = hasWon ?
'Awesome!!' : alive ?
'Mine Digger [$detectedCount-$totalMineCount]': 'Kaboom! [press here]';
return new ToolBar(
// FIXME: Strange to have the toolbar be tapable.
center: new Listener(
onPointerDown: handleToolbarPointerDown,
child: new Text(toolbarCaption, style: Theme.of(this).text.title)
)
);
}
Widget build() {
// We build the board before we build the toolbar because we compute the win state during build step.
Widget board = buildBoard();
return new TaskDescription(
label: 'Mine Digger',
child: new Scaffold(
toolbar: buildToolBar(),
body: new Container(
child: new Center(child: board),
decoration: new BoxDecoration(backgroundColor: colors.Grey[50])
)
)
);
}
EventDisposition handleToolbarPointerDown(sky.PointerEvent event) {
setState(() {
resetGame();
});
return EventDisposition.processed;
}
// User action. The user uncovers the cell which can cause losing the game.
void probe(int x, int y) {
if (!alive)
return;
if (uiState[y][x] == CellState.flagged)
return;
setState(() {
// Allowed to probe.
if (cells[y][x]) {
// Probed on a mine --> dead!!
uiState[y][x] = CellState.exploded;
alive = false;
} else {
// No mine, uncover nearby if possible.
cull(x, y);
}
});
}
// User action. The user is sure a mine is at this location.
void flag(int x, int y) {
setState(() {
if (uiState[y][x] == CellState.flagged) {
uiState[y][x] = CellState.covered;
--detectedCount;
} else {
uiState[y][x] = CellState.flagged;
++detectedCount;
}
});
}
// Recursively uncovers cells whose totalMineCount is zero.
void cull(int x, int y) {
if ((x < 0) || (x > rows - 1))
return;
if ((y < 0) || (y > cols - 1))
return;
if (uiState[y][x] == CellState.cleared)
return;
uiState[y][x] = CellState.cleared;
if (mineCount(x, y) > 0)
return;
cull(x - 1, y);
cull(x + 1, y);
cull(x, y - 1);
cull(x, y + 1 );
cull(x - 1, y - 1);
cull(x + 1, y + 1);
cull(x + 1, y - 1);
cull(x - 1, y + 1);
}
int mineCount(int x, int y) {
int count = 0;
int my = cols - 1;
int mx = rows - 1;
count += x > 0 ? bombs(x - 1, y) : 0;
count += x < mx ? bombs(x + 1, y) : 0;
count += y > 0 ? bombs(x, y - 1) : 0;
count += y < my ? bombs(x, y + 1 ) : 0;
count += (x > 0) && (y > 0) ? bombs(x - 1, y - 1) : 0;
count += (x < mx) && (y < my) ? bombs(x + 1, y + 1) : 0;
count += (x < mx) && (y > 0) ? bombs(x + 1, y - 1) : 0;
count += (x > 0) && (y < my) ? bombs(x - 1, y + 1) : 0;
return count;
}
int bombs(int x, int y) {
return cells[y][x] ? 1 : 0;
}
}
Widget buildCell(Widget child) {
return new Container(
padding: new EdgeDims.all(1.0),
height: 27.0, width: 27.0,
decoration: new BoxDecoration(backgroundColor: const Color(0xFFC0C0C0)),
margin: new EdgeDims.all(2.0),
child: child
);
}
Widget buildInnerCell(Widget child) {
return new Container(
padding: new EdgeDims.all(1.0),
margin: new EdgeDims.all(3.0),
height: 17.0, width: 17.0,
child: child
);
}
class CoveredMineNode extends Component {
CoveredMineNode({ this.flagged, this.posX, this.posY });
final bool flagged;
final int posX;
final int posY;
Widget build() {
Widget text;
if (flagged)
text = buildInnerCell(new StyledText(elements : [textStyles[5], '\u2691']));
Container inner = new Container(
margin: new EdgeDims.all(2.0),
height: 17.0, width: 17.0,
decoration: new BoxDecoration(backgroundColor: const Color(0xFFD9D9D9)),
child: text
);
return buildCell(inner);
}
}
class ExposedMineNode extends Component {
ExposedMineNode({ this.state, this.count });
final CellState state;
final int count;
Widget build() {
StyledText text;
if (state == CellState.cleared) {
// Uncovered cell with nearby mine count.
if (count != 0)
text = new StyledText(elements : [textStyles[count], '$count']);
} else {
// Exploded mine or shown mine for 'game over'.
int color = state == CellState.exploded ? 3 : 0;
text = new StyledText(elements : [textStyles[color], '\u2600']);
}
return buildCell(buildInnerCell(text));
}
}
void main() {
runApp(new MineDiggerApp());
}

View File

@@ -8,7 +8,7 @@ group("sky") {
deps = [
"//sky/engine/platform:platform_unittests($host_toolchain)",
"//sky/engine/wtf:unittests($host_toolchain)",
"//sky/packages/sky/example",
"//examples",
"//sky/tools/imagediff($host_toolchain)",
"//sky/tools/sky_snapshot($host_toolchain)",
":sky_dev",
@@ -24,7 +24,7 @@ group("sky_dev") {
deps = [
"//sky/packages",
"//sky/packages/sky/example/demo_launcher",
"//examples/demo_launcher",
"//sky/shell",
]

View File

@@ -16,7 +16,7 @@ PUBSPECS = [
]
MANIFESTS = [
'sky/packages/sky/example/demo_launcher/apk/AndroidManifest.xml',
'examples/demo_launcher/apk/AndroidManifest.xml',
]
MANIFEST_PREFACE = '''<?xml version="1.0" encoding="utf-8"?>

View File

@@ -14,6 +14,7 @@ WORKBENCH_ROOT = os.path.join(SRC_ROOT, 'sky', 'packages', 'workbench')
DART_SDK = os.path.join(SRC_ROOT, 'third_party', 'dart-sdk', 'dart-sdk', 'bin')
PUB = os.path.join(DART_SDK, 'pub')
PUB_CACHE = os.path.join(SRC_ROOT, "dart-pub-cache")
EXAMPLES_ROOT = os.path.join(SRC_ROOT, 'examples')
SKY_ROOT = os.path.join(SRC_ROOT, 'sky')
class SkyServer(object):
@@ -37,7 +38,12 @@ class SkyServer(object):
env = os.environ.copy()
env["PUB_CACHE"] = PUB_CACHE
args = [PUB, 'run', 'sky_tools:sky_server', '--route=/sky,%s' % SKY_ROOT, str(self.port)]
args = [PUB,
'run',
'sky_tools:sky_server',
'--route=/sky,%s' % SKY_ROOT,
'--route=/examples,%s' % EXAMPLES_ROOT,
str(self.port)]
self.server = subprocess.Popen(args, cwd=WORKBENCH_ROOT, env=env)
return self.server.pid