diff --git a/examples/address_book/lib/main.dart b/examples/address_book/lib/main.dart index 964c39f2cf..8bc9a8ea9b 100644 --- a/examples/address_book/lib/main.dart +++ b/examples/address_book/lib/main.dart @@ -34,10 +34,6 @@ class Field extends StatelessComponent { } class AddressBookHome extends StatelessComponent { - AddressBookHome({ this.navigator }); - - final NavigatorState navigator; - Widget buildToolBar(BuildContext context) { return new ToolBar( left: new IconButton(icon: "navigation/arrow_back"), @@ -60,22 +56,20 @@ class AddressBookHome extends StatelessComponent { static final GlobalKey noteKey = new GlobalKey(label: 'note field'); Widget buildBody(BuildContext context) { - return new Material( - child: new Block([ - 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"), - ]) - ); + return new Block([ + 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 build(BuildContext context) { @@ -98,7 +92,7 @@ void main() { title: 'Address Book', theme: theme, routes: { - '/': (RouteArguments args) => new AddressBookHome(navigator: args.navigator) + '/': (RouteArguments args) => new AddressBookHome() } )); } diff --git a/examples/fitness/lib/feed.dart b/examples/fitness/lib/feed.dart index cbb9922bed..e49473ccf8 100644 --- a/examples/fitness/lib/feed.dart +++ b/examples/fitness/lib/feed.dart @@ -14,13 +14,11 @@ class FitnessItemList extends StatelessComponent { final FitnessItemHandler onDismissed; Widget build(BuildContext context) { - return new Material( - child: new ScrollableList( - padding: const EdgeDims.all(4.0), - items: items, - itemExtent: kFitnessItemHeight, - itemBuilder: (_, item) => item.toRow(onDismissed: onDismissed) - ) + return new ScrollableList( + padding: const EdgeDims.all(4.0), + items: items, + itemExtent: kFitnessItemHeight, + itemBuilder: (_, item) => item.toRow(onDismissed: onDismissed) ); } } @@ -69,7 +67,7 @@ class FeedFragmentState extends State { void _showDrawer() { showDrawer( - navigator: config.navigator, + context: context, child: new Block([ new DrawerHeader(child: new Text('Fitness')), new DrawerItem( @@ -119,7 +117,7 @@ class FeedFragmentState extends State { void _handleItemDismissed(FitnessItem item) { config.onItemDeleted(item); showSnackBar( - navigator: config.navigator, + context: context, placeholderKey: _snackBarPlaceholderKey, content: new Text("Item deleted."), actions: [new SnackBarAction(label: "UNDO", onPressed: () { @@ -171,14 +169,13 @@ class FeedFragmentState extends State { Widget buildBody() { TextStyle style = Theme.of(context).text.title; if (config.userData == null) - return new Material(); - if (config.userData.items.length == 0) - return new Material( - child: new Row( - [new Text("No data yet.\nAdd some!", style: style)], - justifyContent: FlexJustifyContent.center - ) + return new Container(); + if (config.userData.items.length == 0) { + return new Row( + [new Text("No data yet.\nAdd some!", style: style)], + justifyContent: FlexJustifyContent.center ); + } switch (_fitnessMode) { case FitnessMode.feed: return new FitnessItemList( @@ -186,17 +183,15 @@ class FeedFragmentState extends State { onDismissed: _handleItemDismissed ); case FitnessMode.chart: - return new Material( - child: new Container( - padding: const EdgeDims.all(20.0), - child: buildChart() - ) + return new Container( + padding: const EdgeDims.all(20.0), + child: buildChart() ); } } void _handleActionButtonPressed() { - showDialog(config.navigator, (NavigatorState navigator) => new AddItemDialog(navigator)).then((routeName) { + showDialog(context: context, child: new AddItemDialog()).then((routeName) { if (routeName != null) config.navigator.pushNamed(routeName); }); @@ -225,10 +220,6 @@ class FeedFragmentState extends State { } class AddItemDialog extends StatefulComponent { - AddItemDialog(this.navigator); - - final NavigatorState navigator; - AddItemDialogState createState() => new AddItemDialogState(); } @@ -258,16 +249,20 @@ class AddItemDialogState extends State { return new Dialog( title: new Text("What are you doing?"), content: new Block(menuItems), - onDismiss: config.navigator.pop, + onDismiss: () { + Navigator.of(context).pop(); + }, actions: [ new FlatButton( child: new Text('CANCEL'), - onPressed: config.navigator.pop + onPressed: () { + Navigator.of(context).pop(); + } ), new FlatButton( child: new Text('ADD'), onPressed: () { - config.navigator.pop(_addItemRoute); + Navigator.of(context).pop(_addItemRoute); } ), ] diff --git a/examples/fitness/lib/meal.dart b/examples/fitness/lib/meal.dart index ea96b91ba6..fb1765c0f5 100644 --- a/examples/fitness/lib/meal.dart +++ b/examples/fitness/lib/meal.dart @@ -85,19 +85,17 @@ class MealFragmentState extends State { Widget buildBody() { Meal meal = new Meal(when: new DateTime.now()); - return new Material( - child: new ScrollableViewport( - child: new Container( - padding: const EdgeDims.all(20.0), - child: new BlockBody([ - new Text(meal.displayDate), - new Input( - key: descriptionKey, - placeholder: 'Describe meal', - onChanged: _handleDescriptionChanged - ), - ]) - ) + return new ScrollableViewport( + child: new Container( + padding: const EdgeDims.all(20.0), + child: new BlockBody([ + new Text(meal.displayDate), + new Input( + key: descriptionKey, + placeholder: 'Describe meal', + onChanged: _handleDescriptionChanged + ), + ]) ) ); } diff --git a/examples/fitness/lib/measurement.dart b/examples/fitness/lib/measurement.dart index 83b8c88cc0..eba6746a92 100644 --- a/examples/fitness/lib/measurement.dart +++ b/examples/fitness/lib/measurement.dart @@ -55,9 +55,8 @@ class MeasurementRow extends FitnessItemRow { } class MeasurementDateDialog extends StatefulComponent { - MeasurementDateDialog({ this.navigator, this.previousDate }); + MeasurementDateDialog({ this.previousDate }); - final NavigatorState navigator; final DateTime previousDate; MeasurementDateDialogState createState() => new MeasurementDateDialogState(); @@ -89,12 +88,14 @@ class MeasurementDateDialogState extends State { actions: [ new FlatButton( child: new Text('CANCEL'), - onPressed: config.navigator.pop + onPressed: () { + Navigator.of(context).pop(); + } ), new FlatButton( child: new Text('OK'), onPressed: () { - config.navigator.pop(_selectedDate); + Navigator.of(context).pop(_selectedDate); } ), ] @@ -124,7 +125,7 @@ class MeasurementFragmentState extends State { } on FormatException catch(e) { print("Exception $e"); showSnackBar( - navigator: config.navigator, + context: context, placeholderKey: _snackBarPlaceholderKey, content: new Text('Save failed') ); @@ -157,43 +158,41 @@ class MeasurementFragmentState extends State { static final GlobalKey weightKey = new GlobalKey(); - void _handleDatePressed() { - showDialog(config.navigator, (NavigatorState navigator) { - return new MeasurementDateDialog(navigator: navigator, previousDate: _when); - }).then((DateTime value) { - if (value == null) - return; + Future _handleDatePressed() async { + DateTime value = await showDialog( + context: context, + child: new MeasurementDateDialog(previousDate: _when) + ); + if (value != null) { setState(() { _when = value; }); - }); + } } Widget buildBody(BuildContext context) { Measurement measurement = new Measurement(when: _when); // TODO(jackson): Revisit the layout of this pane to be more maintainable - return new Material( - child: new Container( - padding: const EdgeDims.all(20.0), - child: new Column([ - new GestureDetector( - onTap: _handleDatePressed, - child: new Container( - height: 50.0, - child: new Column([ - new Text('Measurement Date'), - new Text(measurement.displayDate, style: Theme.of(context).text.caption), - ], alignItems: FlexAlignItems.start) - ) - ), - new Input( - key: weightKey, - placeholder: 'Enter weight', - keyboardType: KeyboardType.NUMBER, - onChanged: _handleWeightChanged - ), - ], alignItems: FlexAlignItems.stretch) - ) + return new Container( + padding: const EdgeDims.all(20.0), + child: new Column([ + new GestureDetector( + onTap: _handleDatePressed, + child: new Container( + height: 50.0, + child: new Column([ + new Text('Measurement Date'), + new Text(measurement.displayDate, style: Theme.of(context).text.caption), + ], alignItems: FlexAlignItems.start) + ) + ), + new Input( + key: weightKey, + placeholder: 'Enter weight', + keyboardType: KeyboardType.NUMBER, + onChanged: _handleWeightChanged + ), + ], alignItems: FlexAlignItems.stretch) ); } diff --git a/examples/fitness/lib/settings.dart b/examples/fitness/lib/settings.dart index 5c6035290f..144ba29ac7 100644 --- a/examples/fitness/lib/settings.dart +++ b/examples/fitness/lib/settings.dart @@ -60,9 +60,10 @@ class SettingsFragmentState extends State { } } - void _handleGoalWeightPressed() { - showDialog(config.navigator, (NavigatorState navigator) { - return new Dialog( + Future _handleGoalWeightPressed() async { + double goalWeight = await showDialog( + context: context, + child: new Dialog( title: new Text("Goal Weight"), content: new Input( key: weightGoalKey, @@ -71,50 +72,49 @@ class SettingsFragmentState extends State { onChanged: _handleGoalWeightChanged ), onDismiss: () { - navigator.pop(); + Navigator.of(context).pop(); }, actions: [ new FlatButton( child: new Text('CANCEL'), onPressed: () { - navigator.pop(); + Navigator.of(context).pop(); } ), new FlatButton( child: new Text('SAVE'), onPressed: () { - navigator.pop(_goalWeight); + Navigator.of(context).pop(_goalWeight); } ), ] - ); - }).then((double goalWeight) => config.updater(goalWeight: goalWeight)); + ) + ); + config.updater(goalWeight: goalWeight); } Widget buildSettingsPane(BuildContext context) { - return new Material( - child: new ScrollableViewport( - child: new Container( - padding: const EdgeDims.symmetric(vertical: 20.0), - child: new BlockBody([ - new DrawerItem( - onPressed: () { _handleBackupChanged(!(config.userData.backupMode == BackupMode.enabled)); }, - child: new Row([ - new Flexible(child: new Text('Back up data to the cloud')), - new Switch(value: config.userData.backupMode == BackupMode.enabled, onChanged: _handleBackupChanged), - ]) - ), - new DrawerItem( - onPressed: () => _handleGoalWeightPressed(), - child: new Column([ - new Text('Goal Weight'), - new Text(goalWeightText, style: Theme.of(context).text.caption), - ], - alignItems: FlexAlignItems.start - ) - ), - ]) - ) + return new ScrollableViewport( + child: new Container( + padding: const EdgeDims.symmetric(vertical: 20.0), + child: new BlockBody([ + new DrawerItem( + onPressed: () { _handleBackupChanged(!(config.userData.backupMode == BackupMode.enabled)); }, + child: new Row([ + new Flexible(child: new Text('Back up data to the cloud')), + new Switch(value: config.userData.backupMode == BackupMode.enabled, onChanged: _handleBackupChanged), + ]) + ), + new DrawerItem( + onPressed: () => _handleGoalWeightPressed(), + child: new Column([ + new Text('Goal Weight'), + new Text(goalWeightText, style: Theme.of(context).text.caption), + ], + alignItems: FlexAlignItems.start + ) + ), + ]) ) ); } diff --git a/examples/fitness/sky.yaml b/examples/fitness/sky.yaml index ebb7dc2280..3eb1406efe 100644 --- a/examples/fitness/sky.yaml +++ b/examples/fitness/sky.yaml @@ -1,6 +1,6 @@ name: fitness version: 0.0.1 -update_url: http://localhost:9888/examples/fitness/ +update-url: http://localhost:9888/examples/fitness/ material-design-icons: - name: action/assessment - name: action/help diff --git a/examples/game/lib/game_objects.dart b/examples/game/lib/game_objects.dart index e10510c2da..e15f765101 100644 --- a/examples/game/lib/game_objects.dart +++ b/examples/game/lib/game_objects.dart @@ -16,7 +16,7 @@ abstract class GameObject extends Node { Paint _paintDebug = new Paint() ..color=new Color(0xffff0000) ..strokeWidth = 1.0 - ..setStyle(ui.PaintingStyle.stroke); + ..style = ui.PaintingStyle.stroke; bool collidingWith(GameObject obj) { return (GameMath.distanceBetweenPoints(position, obj.position) diff --git a/examples/game/lib/main.dart b/examples/game/lib/main.dart index e7497703b7..0238a4790d 100644 --- a/examples/game/lib/main.dart +++ b/examples/game/lib/main.dart @@ -159,7 +159,7 @@ class TextureButtonState extends State { width: config.width, height: config.height, child: new CustomPaint( - callback: paintCallback, + onPaint: paintCallback, token: new _TextureButtonToken( _highlight, config.texture, diff --git a/examples/game/lib/power_bar.dart b/examples/game/lib/power_bar.dart index dc435d6d2b..17ee1c4a92 100644 --- a/examples/game/lib/power_bar.dart +++ b/examples/game/lib/power_bar.dart @@ -10,7 +10,7 @@ class PowerBar extends NodeWithSize { Paint _paintOutline = new Paint() ..color = new Color(0xffffffff) ..strokeWidth = 1.0 - ..setStyle(ui.PaintingStyle.stroke); + ..style = ui.PaintingStyle.stroke; void paint(PaintingCanvas canvas) { applyTransformForPivot(canvas); diff --git a/examples/game/test_physics.dart b/examples/game/test_physics.dart index ecadb2f6f0..00fc9e0e3f 100644 --- a/examples/game/test_physics.dart +++ b/examples/game/test_physics.dart @@ -1,5 +1,6 @@ import 'dart:ui'; +import 'package:flutter/animation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; @@ -46,23 +47,39 @@ main() async { class TestBed extends NodeWithSize { Sprite _obstacle; - PhysicsNode _physicsNode; + PhysicsWorld _physicsNode; TestBed() : super(new Size(1024.0, 1024.0)) { - _physicsNode = new PhysicsNode(new Offset(0.0, 100.0)); + _physicsNode = new PhysicsWorld(new Offset(0.0, 100.0)); + PhysicsGroup group = new PhysicsGroup(); + _physicsNode.addChild(group); _obstacle = new Sprite(_spriteSheet["ship.png"]); - _obstacle.position = new Point(532.0, 800.0); + _obstacle.position = new Point(512.0, 800.0); _obstacle.size = new Size(64.0, 64.0); + _obstacle.scale = 2.0; _obstacle.physicsBody = new PhysicsBody( new PhysicsShapeCircle(Point.origin, 32.0), type: PhysicsBodyType.static, friction: 0.5, tag: "obstacle" ); - _physicsNode.addChild(_obstacle); + group.addChild(_obstacle); _physicsNode.addContactCallback(myCallback, "obstacle", "ship", PhysicsContactType.begin); + // Animate obstacle + ActionSequence seq = new ActionSequence([ + new ActionTween((a) => _obstacle.position = a, new Point(256.0, 800.0), new Point(768.0, 800.0), 1.0, Curves.easeInOut), + new ActionTween((a) => _obstacle.position = a, new Point(768.0, 800.0), new Point(256.0, 800.0), 1.0, Curves.easeInOut) + ]); + _obstacle.actions.run(new ActionRepeatForever(seq)); + + seq = new ActionSequence([ + new ActionTween((a) => _obstacle.scale = a, 1.0, 2.0, 2.0, Curves.easeInOut), + new ActionTween((a) => _obstacle.scale = a, 2.0, 1.0, 2.0, Curves.easeInOut) + ]); + _obstacle.actions.run(new ActionRepeatForever(seq)); + addChild(_physicsNode); userInteractionEnabled = true; diff --git a/examples/raw/baseline.dart b/examples/raw/baseline.dart index 234803ab70..cad63bb19c 100644 --- a/examples/raw/baseline.dart +++ b/examples/raw/baseline.dart @@ -36,9 +36,10 @@ void drawText(ui.Canvas canvas, String lh) { path.lineTo(block.maxContentWidth, block.alphabeticBaseline); path.moveTo(0.0, block.height); path.lineTo(block.maxContentWidth, block.height); - paint.color = const ui.Color(0xFFFF9000); - paint.setStyle(ui.PaintingStyle.stroke); - paint.strokeWidth = 3.0; + paint + ..color = const ui.Color(0xFFFF9000) + ..style = ui.PaintingStyle.stroke + ..strokeWidth = 3.0; canvas.drawPath(path, paint); // paint the text @@ -49,9 +50,9 @@ ui.Picture paint(ui.Rect paintBounds) { ui.PictureRecorder recorder = new ui.PictureRecorder(); ui.Canvas canvas = new ui.Canvas(recorder, paintBounds); - ui.Paint paint = new ui.Paint(); - paint.color = const ui.Color(0xFFFFFFFF); - paint.setStyle(ui.PaintingStyle.fill); + ui.Paint paint = new ui.Paint() + ..color = const ui.Color(0xFFFFFFFF) + ..style = ui.PaintingStyle.fill; canvas.drawRect(new ui.Rect.fromLTRB(0.0, 0.0, ui.view.width, ui.view.height), paint); canvas.translate(10.0, 0.0); diff --git a/examples/raw/painting.dart b/examples/raw/painting.dart index e43299f86c..d12ba51e0a 100644 --- a/examples/raw/painting.dart +++ b/examples/raw/painting.dart @@ -29,7 +29,7 @@ ui.Picture paint(ui.Rect paintBounds) { [new ui.Point(-radius, -radius), new ui.Point(0.0, 0.0)], [const ui.Color(0xFFFFFF00), const ui.Color(0xFF0000FF)]); canvas.drawRect(new ui.Rect.fromLTRB(-radius, -radius, radius, radius), - new ui.Paint()..setShader(yellowBlue)); + new ui.Paint()..shader = yellowBlue); // Scale x and y by 0.5. var scaleMatrix = new Float64List.fromList([ diff --git a/examples/rendering/baseline.dart b/examples/rendering/baseline.dart index 11da5f1a20..c3f730ad2b 100644 --- a/examples/rendering/baseline.dart +++ b/examples/rendering/baseline.dart @@ -37,7 +37,7 @@ RenderBox getBox(double lh) { padding: new EdgeDims.all(10.0), child: new RenderCustomPaint( child: paragraph, - callback: (canvas, size) { + onPaint: (PaintingCanvas canvas, Size size) { double baseline = paragraph.getDistanceToBaseline(TextBaseline.alphabetic); double w = paragraph.getMaxIntrinsicWidth(new BoxConstraints.loose(size)); double h = paragraph.getMaxIntrinsicHeight(new BoxConstraints.loose(size)); @@ -48,10 +48,10 @@ RenderBox getBox(double lh) { path.lineTo(w, baseline); path.moveTo(0.0, h); path.lineTo(w, h); - Paint paint = new Paint(); - paint.color = const Color(0xFFFF9000); - paint.setStyle(ui.PaintingStyle.stroke); - paint.strokeWidth = 3.0; + Paint paint = new Paint() + ..color = const Color(0xFFFF9000) + ..style = ui.PaintingStyle.stroke + ..strokeWidth = 3.0; canvas.drawPath(path, paint); } ) diff --git a/examples/rendering/flex.dart b/examples/rendering/flex.dart index 164220c4df..30545b2267 100644 --- a/examples/rendering/flex.dart +++ b/examples/rendering/flex.dart @@ -18,7 +18,8 @@ RenderBox buildFlexExample() { void addFlexChildSolidColor(RenderFlex parent, ui.Color backgroundColor, { int flex: 0 }) { RenderSolidColorBox child = new RenderSolidColorBox(backgroundColor); parent.add(child); - child.parentData.flex = flex; + final FlexParentData childParentData = child.parentData; + childParentData.flex = flex; } // Yellow bar at top diff --git a/examples/rendering/interactive_flex.dart b/examples/rendering/interactive_flex.dart index ce50fd9204..86494790a7 100644 --- a/examples/rendering/interactive_flex.dart +++ b/examples/rendering/interactive_flex.dart @@ -49,7 +49,8 @@ void main() { void addFlexChildSolidColor(RenderFlex parent, Color backgroundColor, { int flex: 0 }) { RenderSolidColorBox child = new RenderSolidColorBox(backgroundColor); parent.add(child); - child.parentData.flex = flex; + final FlexParentData childParentData = child.parentData; + childParentData.flex = flex; } var row = new RenderFlex(direction: FlexDirection.horizontal); @@ -90,7 +91,8 @@ Pancetta meatball tongue tenderloin rump tail jowl boudin."""; addFlexChildSolidColor(column, const Color(0xFF0081C6), flex: 2); row.add(column); - column.parentData.flex = 8; + final FlexParentData childParentData = column.parentData; + childParentData.flex = 8; RenderDecoratedBox root = new RenderDecoratedBox( decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF)), diff --git a/examples/rendering/render_paragraph.dart b/examples/rendering/render_paragraph.dart index 83a9bb0413..40207ebb35 100644 --- a/examples/rendering/render_paragraph.dart +++ b/examples/rendering/render_paragraph.dart @@ -16,7 +16,8 @@ void main() { RenderObject child = new RenderSolidColorBox(const Color(0xFFFFFF00)); flexRoot.add(child); - child.parentData.flex = 2; + FlexParentData childParentData = child.parentData; + childParentData.flex = 2; // The internet is a beautiful place. https://baconipsum.com/ String meatyString = """Bacon ipsum dolor amet ham fatback tri-tip, prosciutto @@ -33,7 +34,8 @@ Pancetta meatball tongue tenderloin rump tail jowl boudin."""; child: new RenderParagraph(text) ); flexRoot.add(child); - child.parentData.flex = 1; + childParentData = child.parentData; + childParentData.flex = 1; new FlutterBinding(root: root); } diff --git a/examples/rendering/spinning_flex.dart b/examples/rendering/spinning_flex.dart index c6d21ce168..543b42e29c 100644 --- a/examples/rendering/spinning_flex.dart +++ b/examples/rendering/spinning_flex.dart @@ -18,7 +18,8 @@ void main() { void addFlexChildSolidColor(RenderFlex parent, ui.Color backgroundColor, { int flex: 0 }) { RenderSolidColorBox child = new RenderSolidColorBox(backgroundColor); parent.add(child); - child.parentData.flex = flex; + final FlexParentData childParentData = child.parentData; + childParentData.flex = flex; } addFlexChildSolidColor(flexRoot, const ui.Color(0xFFFF00FF), flex: 1); diff --git a/examples/stocks/BUILD.gn b/examples/stocks/BUILD.gn index d1484fdd5e..814adf3a10 100644 --- a/examples/stocks/BUILD.gn +++ b/examples/stocks/BUILD.gn @@ -10,5 +10,10 @@ sky_app("stocks") { if (is_android) { apk_name = "Stocks" + } else if (is_ios) { + info_plist = "ios/Info.plist" + launcher_resources = [ + "ios/LaunchScreen.storyboardc", + ] } } diff --git a/examples/stocks/ios/Info.plist b/examples/stocks/ios/Info.plist new file mode 100644 index 0000000000..52da94f645 --- /dev/null +++ b/examples/stocks/ios/Info.plist @@ -0,0 +1,58 @@ + + + + + CFBundleDevelopmentRegion + en + + + CFBundleExecutable + stocks_app + + CFBundleDisplayName + Stocks + + UILaunchStoryboardName + LaunchScreen + + CFBundleIdentifier + com.google.stocks + + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + game_app + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UIRequiredDeviceCapabilities + + armv7 + + DTPlatformName + iphonesimulator + DTSDKName + iphonesimulator8.3 + LSRequiresIPhoneOS + + MinimumOSVersion + 7.0 + UIDeviceFamily + + 1 + 2 + + CFBundleSupportedPlatforms + + iPhoneSimulator + + + diff --git a/examples/stocks/ios/LaunchScreen.storyboardc/01J-lp-oVM-view-Ze5-6b-2t3.nib b/examples/stocks/ios/LaunchScreen.storyboardc/01J-lp-oVM-view-Ze5-6b-2t3.nib new file mode 100644 index 0000000000..1aa489da11 Binary files /dev/null and b/examples/stocks/ios/LaunchScreen.storyboardc/01J-lp-oVM-view-Ze5-6b-2t3.nib differ diff --git a/examples/stocks/ios/LaunchScreen.storyboardc/Info.plist b/examples/stocks/ios/LaunchScreen.storyboardc/Info.plist new file mode 100644 index 0000000000..32288e88f6 Binary files /dev/null and b/examples/stocks/ios/LaunchScreen.storyboardc/Info.plist differ diff --git a/examples/stocks/ios/LaunchScreen.storyboardc/UIViewController-01J-lp-oVM.nib b/examples/stocks/ios/LaunchScreen.storyboardc/UIViewController-01J-lp-oVM.nib new file mode 100644 index 0000000000..8de9beddcb Binary files /dev/null and b/examples/stocks/ios/LaunchScreen.storyboardc/UIViewController-01J-lp-oVM.nib differ diff --git a/examples/stocks/lib/main.dart b/examples/stocks/lib/main.dart index 61e7d5d4d9..be7b976295 100644 --- a/examples/stocks/lib/main.dart +++ b/examples/stocks/lib/main.dart @@ -81,7 +81,7 @@ class StocksAppState extends State { if (path.length != 3) return null; if (_stocks.containsKey(path[2])) - return (RouteArguments args) => new StockSymbolViewer(args.navigator, _stocks[path[2]]); + return (RouteArguments args) => new StockSymbolViewer(_stocks[path[2]]); return null; } return null; diff --git a/examples/stocks/lib/stock_arrow.dart b/examples/stocks/lib/stock_arrow.dart index f745c242bb..1ae424ea51 100644 --- a/examples/stocks/lib/stock_arrow.dart +++ b/examples/stocks/lib/stock_arrow.dart @@ -25,7 +25,7 @@ class StockArrow extends StatelessComponent { // TODO(jackson): This should change colors with the theme Color color = _colorForPercentChange(percentChange); const double kSize = 40.0; - var arrow = new CustomPaint(callback: (ui.Canvas canvas, Size size) { + var arrow = new CustomPaint(onPaint: (ui.Canvas canvas, Size size) { Paint paint = new Paint()..color = color; paint.strokeWidth = 1.0; const double padding = 2.0; @@ -49,11 +49,11 @@ class StockArrow extends StatelessComponent { path.lineTo(centerX + w, arrowY + h); path.lineTo(centerX - w, arrowY + h); path.close(); - paint.setStyle(ui.PaintingStyle.fill); + paint.style = ui.PaintingStyle.fill; canvas.drawPath(path, paint); // Draw a circle that circumscribes the arrow. - paint.setStyle(ui.PaintingStyle.stroke); + paint.style = ui.PaintingStyle.stroke; canvas.drawCircle(new Point(centerX, centerY), r, paint); }); diff --git a/examples/stocks/lib/stock_home.dart b/examples/stocks/lib/stock_home.dart index 33d9cdd5de..42d5db4776 100644 --- a/examples/stocks/lib/stock_home.dart +++ b/examples/stocks/lib/stock_home.dart @@ -67,7 +67,8 @@ class StockHomeState extends State { } void _handleMenuShow() { - showStockMenu(config.navigator, + showStockMenu( + context: context, autorefresh: _autorefresh, onAutorefreshChanged: _handleAutorefreshChanged ); @@ -75,7 +76,7 @@ class StockHomeState extends State { void _showDrawer() { showDrawer( - navigator: config.navigator, + context: context, child: new Block([ new DrawerHeader(child: new Text('Stocks')), new DrawerItem( @@ -86,8 +87,9 @@ class StockHomeState extends State { new DrawerItem( icon: 'action/account_balance', onPressed: () { - showDialog(config.navigator, (NavigatorState navigator) { - return new Dialog( + showDialog( + context: context, + child: new Dialog( title: new Text('Not Implemented'), content: new Text('This feature has not yet been implemented.'), actions: [ @@ -95,18 +97,18 @@ class StockHomeState extends State { child: new Text('USE IT'), enabled: false, onPressed: () { - navigator.pop(false); + config.navigator.pop(false); } ), new FlatButton( child: new Text('OH WELL'), onPressed: () { - navigator.pop(false); + config.navigator.pop(false); } ), ] - ); - }); + ) + ); }, child: new Text('Account Balance') ), @@ -186,14 +188,16 @@ class StockHomeState extends State { Widget buildStockList(BuildContext context, Iterable stocks) { return new StockList( stocks: stocks.toList(), - onAction: (Stock stock, GlobalKey row, GlobalKey arrowKey, GlobalKey symbolKey, GlobalKey priceKey) { + onAction: (Stock stock, Key arrowKey) { setState(() { stock.percentChange = 100.0 * (1.0 / stock.lastSale); stock.lastSale += 1.0; }); }, - onOpen: (Stock stock, GlobalKey row, GlobalKey arrowKey, GlobalKey symbolKey, GlobalKey priceKey) { - config.navigator.pushNamed('/stock/${stock.symbol}'); + onOpen: (Stock stock, Key arrowKey) { + Set mostValuableKeys = new Set(); + mostValuableKeys.add(arrowKey); + config.navigator.pushNamed('/stock/${stock.symbol}', mostValuableKeys: mostValuableKeys); } ); } @@ -226,7 +230,7 @@ class StockHomeState extends State { return new ToolBar( left: new IconButton( icon: "navigation/arrow_back", - colorFilter: new ui.ColorFilter.mode(Theme.of(context).accentColor, ui.TransferMode.srcATop), + colorFilter: new ColorFilter.mode(Theme.of(context).accentColor, ui.TransferMode.srcATop), onPressed: _handleSearchEnd ), center: new Input( @@ -244,7 +248,7 @@ class StockHomeState extends State { void _handleStockPurchased() { showSnackBar( - navigator: config.navigator, + context: context, placeholderKey: _snackBarPlaceholderKey, content: new Text("Stock purchased!"), actions: [ diff --git a/examples/stocks/lib/stock_list.dart b/examples/stocks/lib/stock_list.dart index c49078626b..8d153f233d 100644 --- a/examples/stocks/lib/stock_list.dart +++ b/examples/stocks/lib/stock_list.dart @@ -12,18 +12,16 @@ class StockList extends StatelessComponent { final StockRowActionCallback onAction; Widget build(BuildContext context) { - return new Material( - child: new ScrollableList( - items: stocks, - itemExtent: StockRow.kHeight, - itemBuilder: (BuildContext context, Stock stock) { - return new StockRow( - stock: stock, - onPressed: onOpen, - onLongPressed: onAction - ); - } - ) + return new ScrollableList( + items: stocks, + itemExtent: StockRow.kHeight, + itemBuilder: (BuildContext context, Stock stock) { + return new StockRow( + stock: stock, + onPressed: onOpen, + onLongPressed: onAction + ); + } ); } } diff --git a/examples/stocks/lib/stock_menu.dart b/examples/stocks/lib/stock_menu.dart index d6ab8b998f..7d976ef19e 100644 --- a/examples/stocks/lib/stock_menu.dart +++ b/examples/stocks/lib/stock_menu.dart @@ -8,44 +8,42 @@ enum _MenuItems { autorefresh, autorefreshCheckbox, add, remove } const double _kMenuMargin = 16.0; // 24.0 on tablet -Future showStockMenu(NavigatorState navigator, { bool autorefresh, ValueChanged onAutorefreshChanged }) async { +Future showStockMenu({BuildContext context, bool autorefresh, ValueChanged onAutorefreshChanged }) async { switch (await showMenu( - navigator: navigator, + context: context, position: new MenuPosition( right: ui.view.paddingRight + _kMenuMargin, top: ui.view.paddingTop + _kMenuMargin ), - builder: (NavigatorState navigator) { - return [ - new PopupMenuItem( - value: _MenuItems.autorefresh, - child: new Row([ - new Flexible(child: new Text('Autorefresh')), - new Checkbox( - value: autorefresh, - onChanged: (bool value) { - navigator.setState(() { - autorefresh = value; - }); - navigator.pop(_MenuItems.autorefreshCheckbox); - } - ) - ] - ) - ), - new PopupMenuItem( - value: _MenuItems.add, - child: new Text('Add stock') - ), - new PopupMenuItem( - value: _MenuItems.remove, - child: new Text('Remove stock') - ), - ]; - } + items: [ + new PopupMenuItem( + value: _MenuItems.autorefresh, + child: new Row([ + new Flexible(child: new Text('Autorefresh')), + new Checkbox( + value: autorefresh, + onChanged: (bool value) { + Navigator.of(context).setState(() { + autorefresh = value; + }); + Navigator.of(context).pop(_MenuItems.autorefreshCheckbox); + } + ) + ] + ) + ), + new PopupMenuItem( + value: _MenuItems.add, + child: new Text('Add stock') + ), + new PopupMenuItem( + value: _MenuItems.remove, + child: new Text('Remove stock') + ), + ] )) { case _MenuItems.autorefresh: - navigator.setState(() { + Navigator.of(context).setState(() { autorefresh = !autorefresh; }); continue autorefreshNotify; @@ -55,8 +53,9 @@ Future showStockMenu(NavigatorState navigator, { bool autorefresh, ValueChanged break; case _MenuItems.add: case _MenuItems.remove: - await showDialog(navigator, (NavigatorState navigator) { - return new Dialog( + await showDialog( + context: context, + child: new Dialog( title: new Text('Not Implemented'), content: new Text('This feature has not yet been implemented.'), actions: [ @@ -76,14 +75,14 @@ Future showStockMenu(NavigatorState navigator, { bool autorefresh, ValueChanged new FlatButton( child: new Text('OH WELL'), onPressed: () { - navigator.pop(false); + Navigator.of(context).pop(false); } ), ] - ); - }); + ) + ); break; default: // menu was canceled. } -} \ No newline at end of file +} diff --git a/examples/stocks/lib/stock_row.dart b/examples/stocks/lib/stock_row.dart index 3014eb21ff..5f2010ce8d 100644 --- a/examples/stocks/lib/stock_row.dart +++ b/examples/stocks/lib/stock_row.dart @@ -4,24 +4,24 @@ part of stocks; -enum StockRowPartKind { arrow, symbol, price } +enum StockRowPartKind { arrow } -class StockRowPartGlobalKey extends GlobalKey { - const StockRowPartGlobalKey(this.stock, this.part) : super.constructor(); +class StockRowPartKey extends Key { + const StockRowPartKey(this.stock, this.part) : super.constructor(); final Stock stock; final StockRowPartKind part; bool operator ==(dynamic other) { - if (other is! StockRowPartGlobalKey) + if (other is! StockRowPartKey) return false; - final StockRowPartGlobalKey typedOther = other; + final StockRowPartKey typedOther = other; return stock == typedOther.stock && part == typedOther.part; } int get hashCode => 37 * (37 * (373) + identityHashCode(stock)) + identityHashCode(part); - String toString() => '[StockRowPartGlobalKey ${stock.symbol}:${part.toString().split(".")[1]})]'; + String toString() => '[StockRowPartKey ${stock.symbol}:${part.toString().split(".")[1]})]'; } -typedef void StockRowActionCallback(Stock stock, GlobalKey row, GlobalKey arrowKey, GlobalKey symbolKey, GlobalKey priceKey); +typedef void StockRowActionCallback(Stock stock, Key arrowKey); class StockRow extends StatelessComponent { StockRow({ @@ -29,38 +29,34 @@ class StockRow extends StatelessComponent { this.onPressed, this.onLongPressed }) : this.stock = stock, - arrowKey = new StockRowPartGlobalKey(stock, StockRowPartKind.arrow), - symbolKey = new StockRowPartGlobalKey(stock, StockRowPartKind.symbol), - priceKey = new StockRowPartGlobalKey(stock, StockRowPartKind.price), - super(key: new GlobalObjectKey(stock)); + _arrowKey = new StockRowPartKey(stock, StockRowPartKind.arrow), + super(key: new ObjectKey(stock)); final Stock stock; final StockRowActionCallback onPressed; final StockRowActionCallback onLongPressed; - final GlobalKey arrowKey; - final GlobalKey symbolKey; - final GlobalKey priceKey; + + final Key _arrowKey; static const double kHeight = 79.0; GestureTapCallback _getTapHandler(StockRowActionCallback callback) { if (callback == null) return null; - return () => callback(stock, key, arrowKey, symbolKey, priceKey); + return () => callback(stock, _arrowKey); } GestureLongPressCallback _getLongPressHandler(StockRowActionCallback callback) { if (callback == null) return null; - return () => callback(stock, key, arrowKey, symbolKey, priceKey); + return () => callback(stock, _arrowKey); } Widget build(BuildContext context) { - String lastSale = "\$${stock.lastSale.toStringAsFixed(2)}"; - + final String lastSale = "\$${stock.lastSale.toStringAsFixed(2)}"; String changeInPrice = "${stock.percentChange.toStringAsFixed(2)}%"; - if (stock.percentChange > 0) changeInPrice = "+" + changeInPrice; - + if (stock.percentChange > 0) + changeInPrice = "+" + changeInPrice; return new InkWell( onTap: _getTapHandler(onPressed), onLongPress: _getLongPressHandler(onLongPressed), @@ -72,39 +68,41 @@ class StockRow extends StatelessComponent { ) ), child: new Row([ - new Container( - key: arrowKey, - child: new StockArrow(percentChange: stock.percentChange), - margin: const EdgeDims.only(right: 5.0) - ), - new Flexible( - child: new Row([ - new Flexible( - flex: 2, - child: new Text( - stock.symbol, - key: symbolKey - ) - ), - new Flexible( - child: new Text( - lastSale, - style: const TextStyle(textAlign: TextAlign.right), - key: priceKey - ) - ), - new Flexible( - child: new Text( - changeInPrice, - style: Theme.of(context).text.caption.copyWith(textAlign: TextAlign.right) - ) - ), - ], - alignItems: FlexAlignItems.baseline, - textBaseline: DefaultTextStyle.of(context).textBaseline - ) - ) - ]) + new Container( + margin: const EdgeDims.only(right: 5.0), + child: new Hero( + tag: StockRowPartKind.arrow, + key: _arrowKey, + child: new StockArrow(percentChange: stock.percentChange) + ) + ), + new Flexible( + child: new Row([ + new Flexible( + flex: 2, + child: new Text( + stock.symbol + ) + ), + new Flexible( + child: new Text( + lastSale, + style: const TextStyle(textAlign: TextAlign.right) + ) + ), + new Flexible( + child: new Text( + changeInPrice, + style: const TextStyle(textAlign: TextAlign.right) + ) + ), + ], + alignItems: FlexAlignItems.baseline, + textBaseline: DefaultTextStyle.of(context).textBaseline + ) + ), + ] + ) ) ); } diff --git a/examples/stocks/lib/stock_settings.dart b/examples/stocks/lib/stock_settings.dart index c0404c7268..c4acd40377 100644 --- a/examples/stocks/lib/stock_settings.dart +++ b/examples/stocks/lib/stock_settings.dart @@ -35,29 +35,30 @@ class StockSettingsState extends State { _handleOptimismChanged(false); break; case StockMode.pessimistic: - showDialog(config.navigator, (NavigatorState navigator) { - return new Dialog( + showDialog( + context: context, + child: new Dialog( title: new Text("Change mode?"), content: new Text("Optimistic mode means everything is awesome. Are you sure you can handle that?"), onDismiss: () { - navigator.pop(false); + config.navigator.pop(false); }, actions: [ new FlatButton( child: new Text('NO THANKS'), onPressed: () { - navigator.pop(false); + config.navigator.pop(false); } ), new FlatButton( child: new Text('AGREE'), onPressed: () { - navigator.pop(true); + config.navigator.pop(true); } ), ] - ); - }).then(_handleOptimismChanged); + ) + ).then(_handleOptimismChanged); break; } } @@ -83,35 +84,33 @@ class StockSettingsState extends State { Widget buildSettingsPane(BuildContext context) { // TODO(ianh): Once we have the gesture API hooked up, fix https://github.com/domokit/mojo/issues/281 // (whereby tapping the widgets below causes both the widget and the menu item to fire their callbacks) - return new Material( - child: new ScrollableViewport( - child: new Container( - padding: const EdgeDims.symmetric(vertical: 20.0), - child: new BlockBody([ - new DrawerItem( - icon: 'action/thumb_up', - onPressed: () => _confirmOptimismChange(), - child: new Row([ - new Flexible(child: new Text('Everything is awesome')), - new Checkbox( - value: config.optimism == StockMode.optimistic, - onChanged: (bool value) => _confirmOptimismChange() - ), - ]) - ), - new DrawerItem( - icon: 'action/backup', - onPressed: () { _handleBackupChanged(!(config.backup == BackupMode.enabled)); }, - child: new Row([ - new Flexible(child: new Text('Back up stock list to the cloud')), - new Switch( - value: config.backup == BackupMode.enabled, - onChanged: _handleBackupChanged - ), - ]) - ), - ]) - ) + return new ScrollableViewport( + child: new Container( + padding: const EdgeDims.symmetric(vertical: 20.0), + child: new BlockBody([ + new DrawerItem( + icon: 'action/thumb_up', + onPressed: () => _confirmOptimismChange(), + child: new Row([ + new Flexible(child: new Text('Everything is awesome')), + new Checkbox( + value: config.optimism == StockMode.optimistic, + onChanged: (bool value) => _confirmOptimismChange() + ), + ]) + ), + new DrawerItem( + icon: 'action/backup', + onPressed: () { _handleBackupChanged(!(config.backup == BackupMode.enabled)); }, + child: new Row([ + new Flexible(child: new Text('Back up stock list to the cloud')), + new Switch( + value: config.backup == BackupMode.enabled, + onChanged: _handleBackupChanged + ), + ]) + ), + ]) ) ); } diff --git a/examples/stocks/lib/stock_symbol_viewer.dart b/examples/stocks/lib/stock_symbol_viewer.dart index ec0dd6c275..4ef3eb697b 100644 --- a/examples/stocks/lib/stock_symbol_viewer.dart +++ b/examples/stocks/lib/stock_symbol_viewer.dart @@ -4,51 +4,59 @@ part of stocks; -class StockSymbolViewer extends StatefulComponent { - StockSymbolViewer(this.navigator, this.stock); +class StockSymbolViewer extends StatelessComponent { + StockSymbolViewer(this.stock); - final NavigatorState navigator; final Stock stock; - StockSymbolViewerState createState() => new StockSymbolViewerState(); -} - -class StockSymbolViewerState extends State { - Widget build(BuildContext context) { - - String lastSale = "\$${config.stock.lastSale.toStringAsFixed(2)}"; - - String changeInPrice = "${config.stock.percentChange.toStringAsFixed(2)}%"; - if (config.stock.percentChange > 0) changeInPrice = "+" + changeInPrice; - + String lastSale = "\$${stock.lastSale.toStringAsFixed(2)}"; + String changeInPrice = "${stock.percentChange.toStringAsFixed(2)}%"; + if (stock.percentChange > 0) + changeInPrice = "+" + changeInPrice; TextStyle headings = Theme.of(context).text.body2; - return new Scaffold( toolBar: new ToolBar( left: new IconButton( icon: 'navigation/arrow_back', - onPressed: config.navigator.pop + onPressed: () { + Navigator.of(context).pop(); + } ), - center: new Text('${config.stock.name} (${config.stock.symbol})') + center: new Text(stock.name) ), - body: new Material( - child: new Block([ + body: new Block([ new Container( - padding: new EdgeDims.all(20.0), - child: new Column([ - new Text('Last Sale', style: headings), - new Text('$lastSale ($changeInPrice)'), - new Container( - height: 8.0 - ), - new Text('Market Cap', style: headings), - new Text('${config.stock.marketCap}'), - ], - alignItems: FlexAlignItems.stretch + margin: new EdgeDims.all(20.0), + child: new Card( + child: new Container( + padding: new EdgeDims.all(20.0), + child: new Column([ + new Row([ + new Text( + '${stock.symbol}', + style: Theme.of(context).text.display2 + ), + new Hero( + tag: StockRowPartKind.arrow, + turns: 2, + child: new StockArrow(percentChange: stock.percentChange) + ), + ], + justifyContent: FlexJustifyContent.spaceBetween + ), + new Text('Last Sale', style: headings), + new Text('$lastSale ($changeInPrice)'), + new Container( + height: 8.0 + ), + new Text('Market Cap', style: headings), + new Text('${stock.marketCap}'), + ]) + ) ) ) - ]) + ] ) ); } diff --git a/examples/stocks/sky.yaml b/examples/stocks/sky.yaml index 7e3bf1d81c..e71bce607a 100644 --- a/examples/stocks/sky.yaml +++ b/examples/stocks/sky.yaml @@ -1,3 +1,6 @@ +name: stocks +version: 0.0.2 +update-url: http://localhost:9888/examples/stocks/ material-design-icons: - name: action/account_balance - name: action/assessment diff --git a/examples/widgets/card_collection.dart b/examples/widgets/card_collection.dart index fd2d17a047..4e4619681d 100644 --- a/examples/widgets/card_collection.dart +++ b/examples/widgets/card_collection.dart @@ -19,10 +19,6 @@ class CardModel { } class CardCollection extends StatefulComponent { - CardCollection({ this.navigator }); - - final NavigatorState navigator; - CardCollectionState createState() => new CardCollectionState(); } @@ -113,7 +109,7 @@ class CardCollectionState extends State { void _showDrawer() { showDrawer( - navigator: config.navigator, + context: context, child: new IconTheme( data: const IconThemeData(color: IconThemeColor.black), child: new Block([ @@ -169,7 +165,7 @@ class CardCollectionState extends State { setState(() { _dismissDirection = newDismissDirection; }); - config.navigator.pop(); + Navigator.of(context).pop(); } Widget buildDrawerCheckbox(String label, bool value, Function callback) { @@ -337,7 +333,7 @@ class CardCollectionState extends State { ]); Widget body = new SizeObserver( - callback: _updateCardCollectionSize, + onSizeChanged: _updateCardCollectionSize, child: new Container( padding: const EdgeDims.symmetric(vertical: 12.0, horizontal: 8.0), decoration: new BoxDecoration(backgroundColor: Theme.of(context).primarySwatch[50]), @@ -348,8 +344,7 @@ class CardCollectionState extends State { if (_snapToCenter) { Widget indicator = new IgnorePointer( child: new Align( - horizontal: 0.0, - vertical: 0.5, + alignment: const FractionalOffset(0.0, 0.5), child: new Container( height: 1.0, decoration: new BoxDecoration(backgroundColor: const Color(0x80FFFFFF)) @@ -375,7 +370,7 @@ void main() { runApp(new MaterialApp( title: 'Cards', routes: { - '/': (RouteArguments args) => new CardCollection(navigator: args.navigator), + '/': (RouteArguments args) => new CardCollection(), } )); } diff --git a/examples/widgets/date_picker.dart b/examples/widgets/date_picker.dart index 8d871dee0d..5537095013 100644 --- a/examples/widgets/date_picker.dart +++ b/examples/widgets/date_picker.dart @@ -34,12 +34,10 @@ class DatePickerDemoState extends State { child: new Stack([ new Scaffold( toolBar: new ToolBar(center: new Text("Date Picker")), - body: new Material( - child: new Row( - [new Text(_dateTime.toString())], - alignItems: FlexAlignItems.end, - justifyContent: FlexJustifyContent.center - ) + body: new Row( + [new Text(_dateTime.toString())], + alignItems: FlexAlignItems.end, + justifyContent: FlexJustifyContent.center ) ), new Dialog( diff --git a/examples/widgets/drag_and_drop.dart b/examples/widgets/drag_and_drop.dart index 63f4d736ad..ac31dc9940 100644 --- a/examples/widgets/drag_and_drop.dart +++ b/examples/widgets/drag_and_drop.dart @@ -103,26 +103,24 @@ class DragAndDropAppState extends State { toolBar: new ToolBar( center: new Text('Drag and Drop Flutter Demo') ), - body: new Material( - child: new DefaultTextStyle( - style: Theme.of(context).text.body1.copyWith(textAlign: TextAlign.center), - child: new Column([ - new Flexible(child: new Row([ - new ExampleDragSource(navigator: config.navigator, name: 'Orange', color: const Color(0xFFFF9000)), - new ExampleDragSource(navigator: config.navigator, name: 'Teal', color: const Color(0xFF00FFFF)), - new ExampleDragSource(navigator: config.navigator, name: 'Yellow', color: const Color(0xFFFFF000)), - ], - alignItems: FlexAlignItems.center, - justifyContent: FlexJustifyContent.spaceAround - )), - new Flexible(child: new Row([ - new Flexible(child: new ExampleDragTarget()), - new Flexible(child: new ExampleDragTarget()), - new Flexible(child: new ExampleDragTarget()), - new Flexible(child: new ExampleDragTarget()), - ])), - ]) - ) + body: new DefaultTextStyle( + style: Theme.of(context).text.body1.copyWith(textAlign: TextAlign.center), + child: new Column([ + new Flexible(child: new Row([ + new ExampleDragSource(navigator: config.navigator, name: 'Orange', color: const Color(0xFFFF9000)), + new ExampleDragSource(navigator: config.navigator, name: 'Teal', color: const Color(0xFF00FFFF)), + new ExampleDragSource(navigator: config.navigator, name: 'Yellow', color: const Color(0xFFFFF000)), + ], + alignItems: FlexAlignItems.center, + justifyContent: FlexJustifyContent.spaceAround + )), + new Flexible(child: new Row([ + new Flexible(child: new ExampleDragTarget()), + new Flexible(child: new ExampleDragTarget()), + new Flexible(child: new ExampleDragTarget()), + new Flexible(child: new ExampleDragTarget()), + ])), + ]) ) ); } diff --git a/examples/widgets/dropdown.dart b/examples/widgets/dropdown.dart new file mode 100644 index 0000000000..1414388507 --- /dev/null +++ b/examples/widgets/dropdown.dart @@ -0,0 +1,57 @@ +// 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:flutter/material.dart'; + +class DropdownDemo extends StatefulComponent { + DropdownDemo(); + + DropdownDemoState createState() => new DropdownDemoState(); +} + +class DropdownDemoState extends State { + dynamic _value = 0; + + List _buildItems() { + return ["One", "Two", "Free", "Four"].map((String label) { + return new DropdownMenuItem(value: label, child: new Text(label)); + }) + .toList(); + } + + Widget build(BuildContext context) { + Widget dropdown = new DropdownButton( + items: _buildItems(), + value: _value, + onChanged: (dynamic newValue) { + setState(() { + if (newValue != null) + _value = newValue; + }); + } + ); + + return new Scaffold( + toolBar: new ToolBar(center: new Text('DropdownDemo Demo')), + body: new Container( + decoration: new BoxDecoration(backgroundColor: Theme.of(context).primarySwatch[50]), + child: new Center(child: dropdown) + ) + ); + } +} + +void main() { + runApp(new MaterialApp( + title: 'DropdownDemo', + theme: new ThemeData( + brightness: ThemeBrightness.light, + primarySwatch: Colors.blue, + accentColor: Colors.redAccent[200] + ), + routes: { + '/': (RouteArguments args) => new DropdownDemo(), + } + )); +} diff --git a/examples/widgets/indexed_stack.dart b/examples/widgets/indexed_stack.dart index 4c0ce83122..7ee88bd074 100644 --- a/examples/widgets/indexed_stack.dart +++ b/examples/widgets/indexed_stack.dart @@ -6,10 +6,6 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class IndexedStackDemo extends StatefulComponent { - IndexedStackDemo({ this.navigator }); - - final NavigatorState navigator; - IndexedStackDemoState createState() => new IndexedStackDemoState(); } @@ -23,7 +19,7 @@ class IndexedStackDemoState extends State { }); } - List _buildMenu(NavigatorState navigator) { + List _buildMenu() { TextStyle style = const TextStyle(fontSize: 18.0, fontWeight: bold); String pad = ''; return new List.generate(_itemCount, (int i) { @@ -33,21 +29,18 @@ class IndexedStackDemoState extends State { } Widget build(BuildContext context) { - List items = _buildMenu(config.navigator); + List items = _buildMenu(); IndexedStack indexedStack = new IndexedStack(items, index: _itemIndex, horizontalAlignment: 0.5); return new Scaffold( toolBar: new ToolBar(center: new Text('IndexedStackDemo Demo')), body: new GestureDetector( onTap: _handleTap, - child: new Container( - decoration: new BoxDecoration(backgroundColor: Theme.of(context).primarySwatch[50]), - child: new Center( - child: new Container( - child: indexedStack, - padding: const EdgeDims.all(8.0), - decoration: new BoxDecoration(border: new Border.all(color: Theme.of(context).accentColor)) - ) + child: new Center( + child: new Container( + child: indexedStack, + padding: const EdgeDims.all(8.0), + decoration: new BoxDecoration(border: new Border.all(color: Theme.of(context).accentColor)) ) ) ) @@ -64,7 +57,7 @@ void main() { accentColor: Colors.redAccent[200] ), routes: { - '/': (RouteArguments args) => new IndexedStackDemo(navigator: args.navigator), + '/': (RouteArguments args) => new IndexedStackDemo(), } )); } diff --git a/examples/widgets/overlay_geometry.dart b/examples/widgets/overlay_geometry.dart index ffde8ff1fd..4d6ee5259d 100644 --- a/examples/widgets/overlay_geometry.dart +++ b/examples/widgets/overlay_geometry.dart @@ -31,15 +31,15 @@ class Marker extends StatelessComponent { final double size; final MarkerType type; - void paintMarker(ui.Canvas canvas, _) { + void paintMarker(PaintingCanvas canvas, _) { Paint paint = new Paint()..color = const Color(0x8000FF00); - paint.setStyle(ui.PaintingStyle.fill); double r = size / 2.0; canvas.drawCircle(new Point(r, r), r, paint); - paint.color = const Color(0xFFFFFFFF); - paint.setStyle(ui.PaintingStyle.stroke); - paint.strokeWidth = 1.0; + paint + ..color = const Color(0xFFFFFFFF) + ..style = ui.PaintingStyle.stroke + ..strokeWidth = 1.0; if (type == MarkerType.topLeft) { canvas.drawLine(new Point(r, r), new Point(r + r - 1.0, r), paint); canvas.drawLine(new Point(r, r), new Point(r, r + r - 1.0), paint); @@ -58,7 +58,7 @@ class Marker extends StatelessComponent { child: new Container( width: size, height: size, - child: new CustomPaint(callback: paintMarker) + child: new CustomPaint(onPaint: paintMarker) ) ) ); @@ -103,7 +103,7 @@ class OverlayGeometryAppState extends State { }); } - void handlePointerDown(GlobalKey target, ui.PointerEvent event) { + void handlePointerDown(GlobalKey target, PointerInputEvent event) { setState(() { markers[MarkerType.touch] = new Point(event.x, event.y); final RenderBox box = target.currentContext.findRenderObject(); @@ -140,7 +140,6 @@ class OverlayGeometryAppState extends State { toolBar: new ToolBar(center: new Text('Tap a Card')), body: new Container( padding: const EdgeDims.symmetric(vertical: 12.0, horizontal: 8.0), - decoration: new BoxDecoration(backgroundColor: Theme.of(context).primarySwatch[50]), child: new ScrollableMixedWidgetList( builder: builder, token: cardModels.length, diff --git a/examples/widgets/pageable_list.dart b/examples/widgets/pageable_list.dart index 8dc8c36d1d..2ee218b78b 100644 --- a/examples/widgets/pageable_list.dart +++ b/examples/widgets/pageable_list.dart @@ -15,10 +15,6 @@ class CardModel { } class PageableListApp extends StatefulComponent { - PageableListApp({ this.navigator }); - - final NavigatorState navigator; - PageableListAppState createState() => new PageableListAppState(); } @@ -89,7 +85,7 @@ class PageableListAppState extends State { void _showDrawer() { showDrawer( - navigator: config.navigator, + context: context, child: new Block([ new DrawerHeader(child: new Text('Options')), new DrawerItem( @@ -136,11 +132,8 @@ class PageableListAppState extends State { : pageSize.width ); return new SizeObserver( - callback: updatePageSize, - child: new Container( - child: list, - decoration: new BoxDecoration(backgroundColor: Theme.of(context).primarySwatch[50]) - ) + onSizeChanged: updatePageSize, + child: list ); } @@ -164,7 +157,7 @@ void main() { accentColor: Colors.redAccent[200] ), routes: { - '/': (RouteArguments args) => new PageableListApp(navigator: args.navigator), + '/': (RouteArguments args) => new PageableListApp(), } )); } diff --git a/examples/widgets/progress_indicator.dart b/examples/widgets/progress_indicator.dart index fdf2338008..b28f6cb674 100644 --- a/examples/widgets/progress_indicator.dart +++ b/examples/widgets/progress_indicator.dart @@ -17,8 +17,8 @@ class ProgressIndicatorAppState extends State { ..variable = new AnimatedValue( 0.0, end: 1.0, - curve: new Interval(0.0, 0.9, curve: ease), - reverseCurve: ease + curve: new Interval(0.0, 0.9, curve: Curves.ease), + reverseCurve: Curves.ease ); valueAnimation.addStatusListener((PerformanceStatus status) { if (status == PerformanceStatus.dismissed || status == PerformanceStatus.completed) @@ -82,7 +82,6 @@ class ProgressIndicatorAppState extends State { onTap: handleTap, child: new Container( padding: const EdgeDims.symmetric(vertical: 12.0, horizontal: 8.0), - decoration: new BoxDecoration(backgroundColor: Theme.of(context).cardColor), child: new BuilderTransition( variables: [valueAnimation.variable], performance: valueAnimation.view, diff --git a/examples/widgets/scale.dart b/examples/widgets/scale.dart index 03c1b92c13..5062846125 100644 --- a/examples/widgets/scale.dart +++ b/examples/widgets/scale.dart @@ -60,12 +60,10 @@ class ScaleAppState extends State { child: new Scaffold( toolBar: new ToolBar( center: new Text('Scale Demo')), - body: new Material( - child: new GestureDetector( - onScaleStart: _handleScaleStart, - onScaleUpdate: _handleScaleUpdate, - child: new CustomPaint(callback: paint, token: "$_zoom $_offset") - ) + body: new GestureDetector( + onScaleStart: _handleScaleStart, + onScaleUpdate: _handleScaleUpdate, + child: new CustomPaint(onPaint: paint, token: "$_zoom $_offset") ) ) ); diff --git a/examples/widgets/scrollbar.dart b/examples/widgets/scrollbar.dart index b488467a24..31a9d0f72e 100644 --- a/examples/widgets/scrollbar.dart +++ b/examples/widgets/scrollbar.dart @@ -6,10 +6,6 @@ import 'package:intl/intl.dart'; import 'package:flutter/material.dart'; class ScrollbarApp extends StatefulComponent { - ScrollbarApp({ this.navigator }); - - final NavigatorState navigator; - ScrollbarAppState createState() => new ScrollbarAppState(); } @@ -23,7 +19,12 @@ class ScrollbarAppState extends State { return new ScrollableList( items: new List.generate(_itemCount, (int i) => i), itemExtent: _itemExtent, - itemBuilder: (BuildContext _, int i) => new Text('Item ${dd.format(i)}', style: Theme.of(context).text.title), + itemBuilder: (_, int i) { + return new Text('Item ${dd.format(i)}', + key: new ValueKey(i), + style: Theme.of(context).text.title + ); + }, scrollableListPainter: _scrollbarPainter ); } @@ -44,7 +45,6 @@ class ScrollbarAppState extends State { return new Scaffold( toolBar: new ToolBar(center: new Text('Scrollbar Demo')), body: new Container( - decoration: new BoxDecoration(backgroundColor: Theme.of(context).primarySwatch[50]), padding: new EdgeDims.all(12.0), child: new Center(child: new Card(child: scrollable)) ) @@ -61,7 +61,7 @@ void main() { accentColor: Colors.redAccent[200] ), routes: { - '/': (RouteArguments args) => new ScrollbarApp(navigator: args.navigator), + '/': (RouteArguments args) => new ScrollbarApp(), } )); } diff --git a/examples/widgets/sector.dart b/examples/widgets/sector.dart index 38bf742021..f0f3c9f3c1 100644 --- a/examples/widgets/sector.dart +++ b/examples/widgets/sector.dart @@ -68,56 +68,54 @@ class SectorAppState extends State { } Widget buildBody() { - return new Material( - child: new Column([ - new Container( - padding: new EdgeDims.symmetric(horizontal: 8.0, vertical: 25.0), - child: new Row([ - new RaisedButton( - enabled: _enabledAdd, - child: new IntrinsicWidth( - child: new Row([ - new Container( - padding: new EdgeDims.all(4.0), - margin: new EdgeDims.only(right: 10.0), - child: new WidgetToRenderBoxAdapter(sectorAddIcon) - ), - new Text('ADD SECTOR'), - ]) - ), - onPressed: addSector + return new Column([ + new Container( + padding: new EdgeDims.symmetric(horizontal: 8.0, vertical: 25.0), + child: new Row([ + new RaisedButton( + enabled: _enabledAdd, + child: new IntrinsicWidth( + child: new Row([ + new Container( + padding: new EdgeDims.all(4.0), + margin: new EdgeDims.only(right: 10.0), + child: new WidgetToRenderBoxAdapter(sectorAddIcon) + ), + new Text('ADD SECTOR'), + ]) ), - new RaisedButton( - enabled: _enabledRemove, - child: new IntrinsicWidth( - child: new Row([ - new Container( - padding: new EdgeDims.all(4.0), - margin: new EdgeDims.only(right: 10.0), - child: new WidgetToRenderBoxAdapter(sectorRemoveIcon) - ), - new Text('REMOVE SECTOR'), - ]) - ), - onPressed: removeSector - ) - ], - justifyContent: FlexJustifyContent.spaceAround - ) - ), - new Flexible( - child: new Container( - margin: new EdgeDims.all(8.0), - decoration: new BoxDecoration( - border: new Border.all(color: new Color(0xFF000000)) + onPressed: addSector ), - padding: new EdgeDims.all(8.0), - child: new WidgetToRenderBoxAdapter(sectors) - ) - ), - ], - justifyContent: FlexJustifyContent.spaceBetween - ) + new RaisedButton( + enabled: _enabledRemove, + child: new IntrinsicWidth( + child: new Row([ + new Container( + padding: new EdgeDims.all(4.0), + margin: new EdgeDims.only(right: 10.0), + child: new WidgetToRenderBoxAdapter(sectorRemoveIcon) + ), + new Text('REMOVE SECTOR'), + ]) + ), + onPressed: removeSector + ) + ], + justifyContent: FlexJustifyContent.spaceAround + ) + ), + new Flexible( + child: new Container( + margin: new EdgeDims.all(8.0), + decoration: new BoxDecoration( + border: new Border.all(color: new Color(0xFF000000)) + ), + padding: new EdgeDims.all(8.0), + child: new WidgetToRenderBoxAdapter(sectors) + ) + ), + ], + justifyContent: FlexJustifyContent.spaceBetween ); } diff --git a/examples/widgets/smooth_resize.dart b/examples/widgets/smooth_resize.dart new file mode 100644 index 0000000000..d493476a92 --- /dev/null +++ b/examples/widgets/smooth_resize.dart @@ -0,0 +1,115 @@ +// 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:flutter/animation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +final List> _kColors = [ + Colors.amber, + Colors.yellow, + Colors.blue, + Colors.purple, + Colors.indigo, + Colors.deepOrange, +]; + +class SmoothBlock extends StatefulComponent { + SmoothBlock({ this.color }); + + final Map color; + + SmoothBlockState createState() => new SmoothBlockState(); +} + +class CardTransition extends StatelessComponent { + CardTransition({ + this.child, + this.performance, + this.x, + this.opacity, + this.scale + }); + + final Widget child; + final Performance performance; + final AnimatedValue x; + final AnimatedValue opacity; + final AnimatedValue scale; + + Widget build(BuildContext context) { + + return new BuilderTransition( + performance: performance, + variables: [x, opacity, scale], + builder: (BuildContext context) { + Matrix4 transform = new Matrix4.identity() + ..translate(x.value) + ..scale(scale.value, scale.value); + return new Opacity( + opacity: opacity.value, + child: new Transform( + transform: transform, + child: child + ) + ); + } + ); + } +} + +class SmoothBlockState extends State { + + double _height = 100.0; + + Widget _handleEnter(PerformanceView performance, Widget child) { + return new CardTransition( + x: new AnimatedValue(-200.0, end: 0.0, curve: Curves.ease), + opacity: new AnimatedValue(0.0, end: 1.0, curve: Curves.ease), + scale: new AnimatedValue(0.8, end: 1.0, curve: Curves.ease), + performance: performance, + child: child + ); + } + + Widget _handleExit(PerformanceView performance, Widget child) { + return new CardTransition( + x: new AnimatedValue(0.0, end: 200.0, curve: Curves.ease), + opacity: new AnimatedValue(1.0, end: 0.0, curve: Curves.ease), + scale: new AnimatedValue(1.0, end: 0.8, curve: Curves.ease), + performance: performance, + child: child + ); + } + + Widget build(BuildContext context) { + return new GestureDetector( + onTap: () { + setState(() { + _height = _height == 100.0 ? 200.0 : 100.0; + }); + }, + child: new EnterExitTransition( + duration: const Duration(milliseconds: 1500), + onEnter: _handleEnter, + onExit: _handleExit, + child: new Container( + key: new ValueKey(_height), + height: _height, + decoration: new BoxDecoration(backgroundColor: config.color[_height.floor() * 4]) + ) + ) + ); + } +} + +class SmoothResizeDemo extends StatelessComponent { + Widget build(BuildContext context) { + return new Block(_kColors.map((Map color) => new SmoothBlock(color: color)).toList()); + } +} + +void main() { + runApp(new SmoothResizeDemo()); +} diff --git a/examples/widgets/tabs.dart b/examples/widgets/tabs.dart index 5a84f93234..b0f97fd633 100644 --- a/examples/widgets/tabs.dart +++ b/examples/widgets/tabs.dart @@ -96,9 +96,8 @@ class TabbedNavigatorAppState extends State { Container _buildCard(BuildContext context, TabNavigator tabNavigator) { return new Container( - child: new Card(child: new Padding(child: tabNavigator, padding: const EdgeDims.all(8.0))), - padding: const EdgeDims.all(12.0), - decoration: new BoxDecoration(backgroundColor: Theme.of(context).primarySwatch[100]) + padding: const EdgeDims.all(12.0), + child: new Card(child: new Padding(child: tabNavigator, padding: const EdgeDims.all(8.0))) ); } diff --git a/packages/flutter/lib/material.dart b/packages/flutter/lib/material.dart index 51bcfafe62..aae1359b89 100644 --- a/packages/flutter/lib/material.dart +++ b/packages/flutter/lib/material.dart @@ -9,6 +9,7 @@ library material; export 'src/material/card.dart'; export 'src/material/checkbox.dart'; +export 'src/material/circle_avatar.dart'; export 'src/material/colors.dart'; export 'src/material/constants.dart'; export 'src/material/date_picker.dart'; @@ -17,17 +18,21 @@ export 'src/material/drawer.dart'; export 'src/material/drawer_divider.dart'; export 'src/material/drawer_header.dart'; export 'src/material/drawer_item.dart'; +export 'src/material/dropdown.dart'; export 'src/material/edges.dart'; export 'src/material/flat_button.dart'; export 'src/material/floating_action_button.dart'; -export 'src/material/icon_button.dart'; export 'src/material/icon.dart'; +export 'src/material/icon_button.dart'; +export 'src/material/icon_theme.dart'; +export 'src/material/icon_theme_data.dart'; export 'src/material/ink_well.dart'; export 'src/material/input.dart'; export 'src/material/list_item.dart'; export 'src/material/material.dart'; export 'src/material/material_app.dart'; export 'src/material/material_button.dart'; +export 'src/material/material_list.dart'; export 'src/material/popup_menu_item.dart'; export 'src/material/popup_menu.dart'; export 'src/material/progress_indicator.dart'; diff --git a/packages/flutter/lib/painting.dart b/packages/flutter/lib/painting.dart index e23302cef3..1ebc1e3e2e 100644 --- a/packages/flutter/lib/painting.dart +++ b/packages/flutter/lib/painting.dart @@ -12,6 +12,7 @@ /// Note: animation.dart depends on the `newton` package. library painting; +export 'src/painting/basic_types.dart'; export 'src/painting/box_painter.dart'; export 'src/painting/shadows.dart'; export 'src/painting/text_painter.dart'; diff --git a/packages/flutter/lib/rendering.dart b/packages/flutter/lib/rendering.dart index 4a9564b7b4..52a57e8e8c 100644 --- a/packages/flutter/lib/rendering.dart +++ b/packages/flutter/lib/rendering.dart @@ -6,6 +6,8 @@ library rendering; export 'src/rendering/auto_layout.dart'; +export 'src/rendering/basic_types.dart'; +export 'src/rendering/binding.dart'; export 'src/rendering/block.dart'; export 'src/rendering/box.dart'; export 'src/rendering/debug.dart'; @@ -18,10 +20,10 @@ export 'src/rendering/image.dart'; export 'src/rendering/layer.dart'; export 'src/rendering/node.dart'; export 'src/rendering/object.dart'; +export 'src/rendering/overflow.dart'; export 'src/rendering/paragraph.dart'; export 'src/rendering/proxy_box.dart'; export 'src/rendering/shifted_box.dart'; -export 'src/rendering/binding.dart'; export 'src/rendering/stack.dart'; export 'src/rendering/statistics_box.dart'; export 'src/rendering/toggleable.dart'; diff --git a/packages/flutter/lib/src/animation/animated_value.dart b/packages/flutter/lib/src/animation/animated_value.dart index 47097d0f12..33fd2ccd1e 100644 --- a/packages/flutter/lib/src/animation/animated_value.dart +++ b/packages/flutter/lib/src/animation/animated_value.dart @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:ui' show Color, Rect; +import 'dart:ui' show Color, Size, Rect; import 'curves.dart'; @@ -104,6 +104,17 @@ class AnimatedColorValue extends AnimatedValue { Color lerp(double t) => Color.lerp(begin, end, t); } +/// An animated variable containing a rectangle +/// +/// This class specializes the interpolation of AnimatedValue to be +/// appropriate for rectangles. +class AnimatedSizeValue extends AnimatedValue { + AnimatedSizeValue(Size begin, { Size end, Curve curve, Curve reverseCurve }) + : super(begin, end: end, curve: curve, reverseCurve: reverseCurve); + + Size lerp(double t) => Size.lerp(begin, end, t); +} + /// An animated variable containing a rectangle /// /// This class specializes the interpolation of AnimatedValue to be diff --git a/packages/flutter/lib/src/animation/curves.dart b/packages/flutter/lib/src/animation/curves.dart index 5b44cc43eb..3d0f6f5702 100644 --- a/packages/flutter/lib/src/animation/curves.dart +++ b/packages/flutter/lib/src/animation/curves.dart @@ -29,7 +29,7 @@ class Linear implements Curve { /// A curve that is 0.0 until start, then curved from 0.0 to 1.0 at end, then 1.0 class Interval implements Curve { - const Interval(this.start, this.end, { this.curve: linear }); + const Interval(this.start, this.end, { this.curve: Curves.linear }); /// The smallest value for which this interval is 0.0 final double start; @@ -153,38 +153,43 @@ class ElasticInOutCurve implements Curve { } } -/// A linear animation curve -const Linear linear = const Linear(); +/// A collection of common animation curves. +class Curves { + Curves._(); -/// A cubic animation curve that speeds up quickly and ends slowly -const Cubic ease = const Cubic(0.25, 0.1, 0.25, 1.0); + /// A linear animation curve + static const Linear linear = const Linear(); -/// A cubic animation curve that starts slowly and ends quickly -const Cubic easeIn = const Cubic(0.42, 0.0, 1.0, 1.0); + /// A cubic animation curve that speeds up quickly and ends slowly + static const Cubic ease = const Cubic(0.25, 0.1, 0.25, 1.0); -/// A cubic animation curve that starts quickly and ends slowly -const Cubic easeOut = const Cubic(0.0, 0.0, 0.58, 1.0); + /// A cubic animation curve that starts slowly and ends quickly + static const Cubic easeIn = const Cubic(0.42, 0.0, 1.0, 1.0); -/// A cubic animation curve that starts slowly, speeds up, and then and ends slowly -const Cubic easeInOut = const Cubic(0.42, 0.0, 0.58, 1.0); + /// A cubic animation curve that starts quickly and ends slowly + static const Cubic easeOut = const Cubic(0.0, 0.0, 0.58, 1.0); -/// An oscillating curve that grows in magnitude -const BounceInCurve bounceIn = const BounceInCurve(); + /// A cubic animation curve that starts slowly, speeds up, and then and ends slowly + static const Cubic easeInOut = const Cubic(0.42, 0.0, 0.58, 1.0); -/// An oscillating curve that first grows and then shrink in magnitude -const BounceOutCurve bounceOut = const BounceOutCurve(); + /// An oscillating curve that grows in magnitude + static const BounceInCurve bounceIn = const BounceInCurve(); -/// An oscillating curve that first grows and then shrink in magnitude -const BounceInOutCurve bounceInOut = const BounceInOutCurve(); + /// An oscillating curve that first grows and then shrink in magnitude + static const BounceOutCurve bounceOut = const BounceOutCurve(); -/// An oscillating curve that grows in magnitude while overshootings its bounds -const ElasticInCurve elasticIn = const ElasticInCurve(); + /// An oscillating curve that first grows and then shrink in magnitude + static const BounceInOutCurve bounceInOut = const BounceInOutCurve(); -/// An oscillating curve that shrinks in magnitude while overshootings its bounds -const ElasticOutCurve elasticOut = const ElasticOutCurve(); + /// An oscillating curve that grows in magnitude while overshootings its bounds + static const ElasticInCurve elasticIn = const ElasticInCurve(); -/// An oscillating curve that grows and then shrinks in magnitude while overshootings its bounds -const ElasticInOutCurve elasticInOut = const ElasticInOutCurve(); + /// An oscillating curve that shrinks in magnitude while overshootings its bounds + static const ElasticOutCurve elasticOut = const ElasticOutCurve(); -/// A curve that starts quickly and eases into its final position. Over the course of the animation, the object spends more time near its final destination. As a result, the user isn’t left waiting for the animation to finish, and the negative effects of motion are minimized. -const Curve fastOutSlowIn = const Cubic(0.4, 0.0, 0.2, 1.0); + /// An oscillating curve that grows and then shrinks in magnitude while overshootings its bounds + static const ElasticInOutCurve elasticInOut = const ElasticInOutCurve(); + + /// A curve that starts quickly and eases into its final position. Over the course of the animation, the object spends more time near its final destination. As a result, the user isn’t left waiting for the animation to finish, and the negative effects of motion are minimized. + static const Curve fastOutSlowIn = const Cubic(0.4, 0.0, 0.2, 1.0); +} diff --git a/packages/flutter/lib/src/animation/performance.dart b/packages/flutter/lib/src/animation/performance.dart index 0b8a020f17..f269e0886d 100644 --- a/packages/flutter/lib/src/animation/performance.dart +++ b/packages/flutter/lib/src/animation/performance.dart @@ -31,6 +31,8 @@ typedef void PerformanceStatusListener(PerformanceStatus status); /// want to watch a performance but should not be able to change the /// performance's state. abstract class PerformanceView { + const PerformanceView(); + /// Update the given variable according to the current progress of the performance void updateVariable(Animatable variable); /// Calls the listener every time the progress of the performance changes @@ -42,9 +44,23 @@ abstract class PerformanceView { /// Stops calling the listener every time the status of the performance changes void removeStatusListener(PerformanceStatusListener listener); - /// The current status of this animation + /// The current status of this animation. PerformanceStatus get status; + /// The current direction of the animation. + AnimationDirection get direction; + + /// The direction used to select the current curve. + /// + /// The curve direction is only reset when we hit the beginning or the end of + /// the timeline to avoid discontinuities in the value of any variables this + /// performance is used to animate. + AnimationDirection get curveDirection; + + /// The current progress of this animation (a value from 0.0 to 1.0). + /// This is the value that is used to update any variables when using updateVariable(). + double get progress; + /// Whether this animation is stopped at the beginning bool get isDismissed => status == PerformanceStatus.dismissed; @@ -52,6 +68,85 @@ abstract class PerformanceView { bool get isCompleted => status == PerformanceStatus.completed; } +class AlwaysCompletePerformance extends PerformanceView { + const AlwaysCompletePerformance(); + + void updateVariable(Animatable variable) { + variable.setProgress(1.0, AnimationDirection.forward); + } + + // this performance never changes state + void addListener(PerformanceListener listener) { } + void removeListener(PerformanceListener listener) { } + void addStatusListener(PerformanceStatusListener listener) { } + void removeStatusListener(PerformanceStatusListener listener) { } + PerformanceStatus get status => PerformanceStatus.completed; + AnimationDirection get direction => AnimationDirection.forward; + AnimationDirection get curveDirection => AnimationDirection.forward; + double get progress => 1.0; +} +const AlwaysCompletePerformance alwaysCompletePerformance = const AlwaysCompletePerformance(); + +class ReversePerformance extends PerformanceView { + ReversePerformance(this.masterPerformance) { + masterPerformance.addStatusListener(_statusChangeHandler); + } + + final PerformanceView masterPerformance; + + void updateVariable(Animatable variable) { + variable.setProgress(progress, curveDirection); + } + + void addListener(PerformanceListener listener) { + masterPerformance.addListener(listener); + } + void removeListener(PerformanceListener listener) { + masterPerformance.removeListener(listener); + } + + final List _statusListeners = new List(); + + /// Calls listener every time the status of this performance changes + void addStatusListener(PerformanceStatusListener listener) { + _statusListeners.add(listener); + } + + /// Stops calling the listener every time the status of this performance changes + void removeStatusListener(PerformanceStatusListener listener) { + _statusListeners.remove(listener); + } + + void _statusChangeHandler(PerformanceStatus status) { + status = _reverseStatus(status); + List localListeners = new List.from(_statusListeners); + for (PerformanceStatusListener listener in localListeners) + listener(status); + } + + PerformanceStatus get status => _reverseStatus(masterPerformance.status); + AnimationDirection get direction => _reverseDirection(masterPerformance.direction); + AnimationDirection get curveDirection => _reverseDirection(masterPerformance.curveDirection); + double get progress => 1.0 - masterPerformance.progress; + + PerformanceStatus _reverseStatus(PerformanceStatus status) { + switch (status) { + case PerformanceStatus.forward: return PerformanceStatus.reverse; + case PerformanceStatus.reverse: return PerformanceStatus.forward; + case PerformanceStatus.completed: return PerformanceStatus.dismissed; + case PerformanceStatus.dismissed: return PerformanceStatus.completed; + } + } + + AnimationDirection _reverseDirection(AnimationDirection direction) { + switch (direction) { + case AnimationDirection.forward: return AnimationDirection.reverse; + case AnimationDirection.reverse: return AnimationDirection.forward; + } + } +} + + /// A timeline that can be reversed and used to update [Animatable]s. /// /// For example, a performance may handle an animation of a menu opening by @@ -61,12 +156,16 @@ abstract class PerformanceView { /// [fling] the timeline causing a physics-based simulation to take over the /// progression. class Performance extends PerformanceView { - Performance({ this.duration, double progress }) { + Performance({ this.duration, double progress, this.debugLabel }) { _timeline = new SimulationStepper(_tick); if (progress != null) _timeline.value = progress.clamp(0.0, 1.0); } + /// A label that is used in the toString() output. Intended to aid with + /// identifying performance instances in debug output. + final String debugLabel; + /// Returns a [PerformanceView] for this performance, /// so that a pointer to this object can be passed around without /// allowing users of that pointer to mutate the AnimationPerformance state. @@ -76,13 +175,9 @@ class Performance extends PerformanceView { Duration duration; SimulationStepper _timeline; + AnimationDirection get direction => _direction; AnimationDirection _direction; - - /// The direction used to select the current curve - /// - /// Curve direction is only reset when we hit the beginning or the end of the - /// timeline to avoid discontinuities in the value of any variables this - /// performance is used to animate. + AnimationDirection get curveDirection => _curveDirection; AnimationDirection _curveDirection; /// If non-null, animate with this timing instead of a linear timing @@ -93,7 +188,6 @@ class Performance extends PerformanceView { /// Note: Setting this value stops the current animation. double get progress => _timeline.value.clamp(0.0, 1.0); void set progress(double t) { - // TODO(mpcomplete): should this affect |direction|? stop(); _timeline.value = t.clamp(0.0, 1.0); _checkStatusChanged(); @@ -220,6 +314,12 @@ class Performance extends PerformanceView { _notifyListeners(); _checkStatusChanged(); } + + String toString() { + if (debugLabel != null) + return '$runtimeType at $progress for $debugLabel'; + return '$runtimeType at $progress'; + } } /// An animation performance with an animated variable with a concrete type diff --git a/packages/flutter/lib/src/animation/scheduler.dart b/packages/flutter/lib/src/animation/scheduler.dart index 699ced4830..c0b41785a6 100644 --- a/packages/flutter/lib/src/animation/scheduler.dart +++ b/packages/flutter/lib/src/animation/scheduler.dart @@ -16,6 +16,13 @@ double timeDilation = 1.0; /// common time base. typedef void SchedulerCallback(Duration timeStamp); +typedef void SchedulerExceptionHandler(dynamic exception, StackTrace stack); +/// This callback is invoked whenever an exception is caught by the scheduler. +/// The 'exception' argument contains the object that was thrown, and the +/// 'stack' argument contains the stack trace. If the callback is set, it is +/// invoked instead of printing the information to the console. +SchedulerExceptionHandler debugSchedulerExceptionHandler; + /// Schedules callbacks to run in concert with the engine's animation system class Scheduler { /// Requires clients to use the [scheduler] singleton @@ -24,35 +31,66 @@ class Scheduler { } bool _haveScheduledVisualUpdate = false; - int _nextCallbackId = 1; + int _nextPrivateCallbackId = 0; // negative + int _nextCallbackId = 0; // positive final List _persistentCallbacks = new List(); Map _transientCallbacks = new LinkedHashMap(); final Set _removedIds = new Set(); + final List _postFrameCallbacks = new List(); + + bool _inFrame = false; + + int get transientCallbackCount => _transientCallbacks.length; /// Called by the engine to produce a new frame. /// /// This function first calls all the callbacks registered by - /// [requestAnimationFrame] and then calls all the callbacks registered by - /// [addPersistentFrameCallback], which typically drive the rendering pipeline. - void beginFrame(double timeStampMS) { - timeStampMS /= timeDilation; - - Duration timeStamp = new Duration(microseconds: (timeStampMS * Duration.MICROSECONDS_PER_MILLISECOND).round()); - + /// [requestAnimationFrame], then calls all the callbacks registered by + /// [addPersistentFrameCallback], which typically drive the rendering pipeline, + /// and finally calls the callbacks registered by [requestPostFrameCallback]. + void beginFrame(double rawTimeStamp) { + assert(!_inFrame); + _inFrame = true; + rawTimeStamp /= timeDilation; + final Duration timeStamp = new Duration( + microseconds: (rawTimeStamp * Duration.MICROSECONDS_PER_MILLISECOND).round() + ); _haveScheduledVisualUpdate = false; + assert(_postFrameCallbacks.length == 0); Map callbacks = _transientCallbacks; _transientCallbacks = new Map(); - callbacks.forEach((int id, SchedulerCallback callback) { if (!_removedIds.contains(id)) - callback(timeStamp); + invokeCallback(callback, timeStamp); }); _removedIds.clear(); for (SchedulerCallback callback in _persistentCallbacks) + invokeCallback(callback, timeStamp); + + for (SchedulerCallback callback in _postFrameCallbacks) + invokeCallback(callback, timeStamp); + _postFrameCallbacks.clear(); + + _inFrame = false; + } + + void invokeCallback(SchedulerCallback callback, Duration timeStamp) { + assert(callback != null); + try { callback(timeStamp); + } catch (exception, stack) { + if (debugSchedulerExceptionHandler != null) { + debugSchedulerExceptionHandler(exception, stack); + } else { + print('-- EXCEPTION IN SCHEDULER CALLBACK --'); + print('$exception'); + print('Stack trace:'); + print('$stack'); + } + } } /// Call callback every frame. @@ -70,20 +108,42 @@ class Scheduler { /// is passed a timeStamp that you can use to determine how far along the /// timeline to advance your animation. /// + /// Callbacks in invoked in an arbitrary order. + /// /// Returns an id that can be used to unschedule this callback. int requestAnimationFrame(SchedulerCallback callback) { - int id = _nextCallbackId++; - _transientCallbacks[id] = callback; + _nextCallbackId += 1; + _transientCallbacks[_nextCallbackId] = callback; ensureVisualUpdate(); - return id; + return _nextCallbackId; } /// Cancel the callback identified by id. void cancelAnimationFrame(int id) { + assert(id > 0); _transientCallbacks.remove(id); _removedIds.add(id); } + /// Schedule a callback for the end of this frame. + /// + /// If a frame is in progress, the callback will be run just after the main + /// rendering pipeline has been flushed. In this case, order is preserved (the + /// callbacks are run in registration order). + /// + /// If no frame is in progress, it will be called at the start of the next + /// frame. In this case, the registration order is not preserved. Callbacks + /// are called in an arbitrary order. + void requestPostFrameCallback(SchedulerCallback callback) { + if (_inFrame) { + _postFrameCallbacks.add(callback); + } else { + _nextPrivateCallbackId -= 1; + _transientCallbacks[_nextPrivateCallbackId] = callback; + ensureVisualUpdate(); + } + } + /// Ensure that a frame will be produced after this function is called. void ensureVisualUpdate() { if (_haveScheduledVisualUpdate) diff --git a/packages/flutter/lib/src/animation/simulation_stepper.dart b/packages/flutter/lib/src/animation/simulation_stepper.dart index 843be0a062..44d6a6acfd 100644 --- a/packages/flutter/lib/src/animation/simulation_stepper.dart +++ b/packages/flutter/lib/src/animation/simulation_stepper.dart @@ -66,7 +66,7 @@ class SimulationStepper { /// /// Returns a future that resolves when the timeline stops animating, /// typically when the timeline arives at the target value. - Future animateTo(double target, { Duration duration, Curve curve: linear }) { + Future animateTo(double target, { Duration duration, Curve curve: Curves.linear }) { assert(duration > Duration.ZERO); assert(!isAnimating); return _start(new _TweenSimulation(value, target, duration, curve)); diff --git a/packages/flutter/lib/src/gestures/events.dart b/packages/flutter/lib/src/gestures/events.dart index 7519440fc1..93afde1fa1 100644 --- a/packages/flutter/lib/src/gestures/events.dart +++ b/packages/flutter/lib/src/gestures/events.dart @@ -24,28 +24,28 @@ class PointerInputEvent extends InputEvent { const PointerInputEvent({ String type, double timeStamp: 0.0, - this.pointer, + this.pointer: 0, this.kind, - this.x, - this.y, - this.dx, - this.dy, - this.buttons, - this.down, - this.primary, - this.obscured, - this.pressure, - this.pressureMin, - this.pressureMax, - this.distance, - this.distanceMin, - this.distanceMax, - this.radiusMajor, - this.radiusMinor, - this.radiusMin, - this.radiusMax, - this.orientation, - this.tilt + this.x: 0.0, + this.y: 0.0, + this.dx: 0.0, + this.dy: 0.0, + this.buttons: 0, + this.down: false, + this.primary: false, + this.obscured: false, + this.pressure: 0.0, + this.pressureMin: 0.0, + this.pressureMax: 0.0, + this.distance: 0.0, + this.distanceMin: 0.0, + this.distanceMax: 0.0, + this.radiusMajor: 0.0, + this.radiusMinor: 0.0, + this.radiusMin: 0.0, + this.radiusMax: 0.0, + this.orientation: 0.0, + this.tilt: 0.0 }) : super(type: type, timeStamp: timeStamp); final int pointer; diff --git a/packages/flutter/lib/src/material/checkbox.dart b/packages/flutter/lib/src/material/checkbox.dart index 4de7ed9f4e..dca9c9775f 100644 --- a/packages/flutter/lib/src/material/checkbox.dart +++ b/packages/flutter/lib/src/material/checkbox.dart @@ -12,8 +12,8 @@ import 'theme.dart'; export 'package:flutter/rendering.dart' show ValueChanged; const double _kMidpoint = 0.5; -const ui.Color _kLightUncheckedColor = const ui.Color(0x8A000000); -const ui.Color _kDarkUncheckedColor = const ui.Color(0xB2FFFFFF); +const Color _kLightUncheckedColor = const Color(0x8A000000); +const Color _kDarkUncheckedColor = const Color(0xB2FFFFFF); const double _kEdgeSize = 18.0; const double _kEdgeRadius = 1.0; const double _kStrokeWidth = 2.0; @@ -126,7 +126,7 @@ class _RenderCheckbox extends RenderToggleable { void paint(PaintingContext context, Offset offset) { final PaintingCanvas canvas = context.canvas; // Choose a color between grey and the theme color - ui.Paint paint = new ui.Paint() + Paint paint = new Paint() ..strokeWidth = _kStrokeWidth ..color = uncheckedColor; @@ -134,27 +134,27 @@ class _RenderCheckbox extends RenderToggleable { // Because we have a stroke size of 2, we should have a minimum 1.0 inset. double inset = 2.0 - (position - _kMidpoint).abs() * 2.0; double rectSize = _kEdgeSize - inset * _kStrokeWidth; - ui.Rect rect = - new ui.Rect.fromLTWH(offset.dx + inset, offset.dy + inset, rectSize, rectSize); + Rect rect = new Rect.fromLTWH(offset.dx + inset, offset.dy + inset, rectSize, rectSize); // Create an inner rectangle to cover inside of rectangle. This is needed to avoid // painting artefacts caused by overlayed paintings. - ui.Rect innerRect = rect.deflate(1.0); + Rect innerRect = rect.deflate(1.0); ui.RRect rrect = new ui.RRect() ..setRectXY(rect, _kEdgeRadius, _kEdgeRadius); // Outline of the empty rrect - paint.setStyle(ui.PaintingStyle.stroke); + paint.style = ui.PaintingStyle.stroke; canvas.drawRRect(rrect, paint); // Radial gradient that changes size if (position > 0) { - paint.setStyle(ui.PaintingStyle.fill); - paint.setShader(new ui.Gradient.radial( + paint + ..style = ui.PaintingStyle.fill + ..shader = new ui.Gradient.radial( new Point(_kEdgeSize / 2.0, _kEdgeSize / 2.0), _kEdgeSize * (_kMidpoint - position) * 8.0, [ - const ui.Color(0x00000000), + const Color(0x00000000), uncheckedColor - ])); + ]); canvas.drawRect(innerRect, paint); } @@ -162,24 +162,25 @@ class _RenderCheckbox extends RenderToggleable { double t = (position - _kMidpoint) / (1.0 - _kMidpoint); // First draw a rounded rect outline then fill inner rectangle with accent color. - paint.color = new Color.fromARGB((t * 255).floor(), _accentColor.red, - _accentColor.green, _accentColor.blue); - paint.setStyle(ui.PaintingStyle.stroke); + paint + ..color = new Color.fromARGB((t * 255).floor(), _accentColor.red, _accentColor.green, _accentColor.blue) + ..style = ui.PaintingStyle.stroke; canvas.drawRRect(rrect, paint); - paint.setStyle(ui.PaintingStyle.fill); + paint.style = ui.PaintingStyle.fill; canvas.drawRect(innerRect, paint); // White inner check - paint.color = const ui.Color(0xFFFFFFFF); - paint.setStyle(ui.PaintingStyle.stroke); - ui.Path path = new ui.Path(); - ui.Point start = new ui.Point(_kEdgeSize * 0.15, _kEdgeSize * 0.45); - ui.Point mid = new ui.Point(_kEdgeSize * 0.4, _kEdgeSize * 0.7); - ui.Point end = new ui.Point(_kEdgeSize * 0.85, _kEdgeSize * 0.25); + paint + ..color = const Color(0xFFFFFFFF) + ..style = ui.PaintingStyle.stroke; + Path path = new Path(); + Point start = new Point(_kEdgeSize * 0.15, _kEdgeSize * 0.45); + Point mid = new Point(_kEdgeSize * 0.4, _kEdgeSize * 0.7); + Point end = new Point(_kEdgeSize * 0.85, _kEdgeSize * 0.25); Point lerp(Point p1, Point p2, double t) => new Point(p1.x * (1.0 - t) + p2.x * t, p1.y * (1.0 - t) + p2.y * t); - ui.Point drawStart = lerp(start, mid, 1.0 - t); - ui.Point drawEnd = lerp(mid, end, t); + Point drawStart = lerp(start, mid, 1.0 - t); + Point drawEnd = lerp(mid, end, t); path.moveTo(offset.dx + drawStart.x, offset.dy + drawStart.y); path.lineTo(offset.dx + mid.x, offset.dy + mid.y); path.lineTo(offset.dx + drawEnd.x, offset.dy + drawEnd.y); diff --git a/packages/flutter/lib/src/material/circle_avatar.dart b/packages/flutter/lib/src/material/circle_avatar.dart new file mode 100644 index 0000000000..7895b87299 --- /dev/null +++ b/packages/flutter/lib/src/material/circle_avatar.dart @@ -0,0 +1,47 @@ +// 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:flutter/painting.dart'; +import 'package:flutter/widgets.dart'; + +import 'constants.dart'; +import 'theme.dart'; +import 'typography.dart'; + +class CircleAvatar extends StatelessComponent { + CircleAvatar({ + Key key, + this.label, + this.backgroundColor, + this.textTheme + }) : super(key: key); + + final String label; + final Color backgroundColor; + final TextTheme textTheme; + + Widget build(BuildContext context) { + Color color = backgroundColor; + TextStyle style = textTheme?.title; + + if (color == null || style == null) { + ThemeData themeData = Theme.of(context); + color ??= themeData.primaryColor; + style ??= themeData.primaryTextTheme.title; + } + + return new AnimatedContainer( + duration: kThemeChangeDuration, + decoration: new BoxDecoration( + backgroundColor: color, + shape: Shape.circle + ), + width: 40.0, + height: 40.0, + child: new Center( + child: new Text(label, style: style) + ) + ); + } +} diff --git a/packages/flutter/lib/src/material/constants.dart b/packages/flutter/lib/src/material/constants.dart index 9b50a30118..6824793b97 100644 --- a/packages/flutter/lib/src/material/constants.dart +++ b/packages/flutter/lib/src/material/constants.dart @@ -19,7 +19,11 @@ const double kSnackBarHeight = 52.0; // https://www.google.com/design/spec/layout/metrics-keylines.html#metrics-keylines-keylines-spacing const double kListTitleHeight = 72.0; const double kListSubtitleHeight = 48.0; -const double kListItemHeight = 72.0; + +const double kOneLineListItemHeight = 48.0; +const double kOneLineListItemWithAvatarHeight = 56.0; +const double kTwoLineListItemHeight = 72.0; +const double kThreeLineListItemHeight = 88.0; const double kMaterialDrawerHeight = 140.0; const double kScrollbarSize = 10.0; diff --git a/packages/flutter/lib/src/material/date_picker.dart b/packages/flutter/lib/src/material/date_picker.dart index 46caf21ff3..c2bdc579ea 100644 --- a/packages/flutter/lib/src/material/date_picker.dart +++ b/packages/flutter/lib/src/material/date_picker.dart @@ -6,7 +6,6 @@ import 'dart:async'; import 'package:intl/date_symbols.dart'; import 'package:intl/intl.dart'; -import 'package:flutter/painting.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; @@ -123,17 +122,15 @@ class _DatePickerHeader extends StatelessComponent { Widget build(BuildContext context) { ThemeData theme = Theme.of(context); - TextTheme headerTheme; + TextTheme headerTheme = theme.primaryTextTheme; Color dayColor; Color yearColor; switch(theme.primaryColorBrightness) { case ThemeBrightness.light: - headerTheme = Typography.black; dayColor = mode == DatePickerMode.day ? Colors.black87 : Colors.black54; yearColor = mode == DatePickerMode.year ? Colors.black87 : Colors.black54; break; case ThemeBrightness.dark: - headerTheme = Typography.white; dayColor = mode == DatePickerMode.day ? Colors.white : Colors.white70; yearColor = mode == DatePickerMode.year ? Colors.white : Colors.white70; break; diff --git a/packages/flutter/lib/src/material/dialog.dart b/packages/flutter/lib/src/material/dialog.dart index 9a39a00578..934b672b34 100644 --- a/packages/flutter/lib/src/material/dialog.dart +++ b/packages/flutter/lib/src/material/dialog.dart @@ -5,7 +5,6 @@ import 'dart:async'; import 'package:flutter/animation.dart'; -import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; @@ -140,11 +139,11 @@ class _DialogRoute extends PerformanceRoute { bool get opaque => false; Duration get transitionDuration => const Duration(milliseconds: 150); - Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance) { + Widget build(RouteArguments args) { return new FadeTransition( - performance: performance, - opacity: new AnimatedValue(0.0, end: 1.0, curve: easeOut), - child: builder(new RouteArguments(navigator: navigator, previousPerformance: this.performance, nextPerformance: nextRoutePerformance)) + performance: args.previousPerformance, + opacity: new AnimatedValue(0.0, end: 1.0, curve: Curves.easeOut), + child: builder(args) ); } @@ -154,15 +153,15 @@ class _DialogRoute extends PerformanceRoute { } } -Future showDialog(NavigatorState navigator, DialogBuilder builder) { +Future showDialog({ BuildContext context, Widget child }) { Completer completer = new Completer(); - navigator.push(new _DialogRoute( + Navigator.of(context).push(new _DialogRoute( completer: completer, builder: (RouteArguments args) { return new Focus( key: new GlobalObjectKey(completer), autofocus: true, - child: builder(args.navigator) + child: child ); } )); diff --git a/packages/flutter/lib/src/material/drawer.dart b/packages/flutter/lib/src/material/drawer.dart index d41e0875de..bfc7796ac1 100644 --- a/packages/flutter/lib/src/material/drawer.dart +++ b/packages/flutter/lib/src/material/drawer.dart @@ -83,7 +83,7 @@ class _Drawer extends StatelessComponent { performance: performance, position: new AnimatedValue(_kClosedPosition, end: _kOpenPosition), child: new AnimatedContainer( - curve: ease, + curve: Curves.ease, duration: _kThemeChangeDuration, decoration: new BoxDecoration( backgroundColor: Theme.of(context).canvasColor, @@ -106,13 +106,13 @@ class _DrawerRoute extends Route { final int level; PerformanceView get performance => _performance?.view; - Performance _performance = new Performance(duration: _kBaseSettleDuration); + Performance _performance = new Performance(duration: _kBaseSettleDuration, debugLabel: 'Drawer'); bool get opaque => false; bool _interactive = true; - Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance) { + Widget build(RouteArguments args) { return new Focus( key: new GlobalObjectKey(this), autofocus: true, @@ -169,7 +169,6 @@ class _DrawerRoute extends Route { } } -void showDrawer({ NavigatorState navigator, Widget child, int level: 3 }) { - assert(navigator != null); - navigator.push(new _DrawerRoute(child: child, level: level)); +void showDrawer({ BuildContext context, Widget child, int level: 3 }) { + Navigator.of(context).push(new _DrawerRoute(child: child, level: level)); } diff --git a/packages/flutter/lib/src/material/drawer_item.dart b/packages/flutter/lib/src/material/drawer_item.dart index 6723b15f1e..5f1fc9d2a9 100644 --- a/packages/flutter/lib/src/material/drawer_item.dart +++ b/packages/flutter/lib/src/material/drawer_item.dart @@ -2,10 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:ui' as ui; - -import 'package:flutter/gestures.dart'; -import 'package:flutter/painting.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; @@ -49,10 +45,10 @@ class _DrawerItemState extends State { return Colors.transparent; } - ui.ColorFilter _getColorFilter(ThemeData themeData) { + ColorFilter _getColorFilter(ThemeData themeData) { if (config.selected) - return new ui.ColorFilter.mode(themeData.primaryColor, ui.TransferMode.srcATop); - return new ui.ColorFilter.mode(const Color(0x73000000), ui.TransferMode.dstIn); + return new ColorFilter.mode(themeData.primaryColor, TransferMode.srcATop); + return new ColorFilter.mode(const Color(0x73000000), TransferMode.dstIn); } Widget build(BuildContext context) { diff --git a/packages/flutter/lib/src/material/dropdown.dart b/packages/flutter/lib/src/material/dropdown.dart new file mode 100644 index 0000000000..391fef03c5 --- /dev/null +++ b/packages/flutter/lib/src/material/dropdown.dart @@ -0,0 +1,257 @@ +// 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:async'; +import 'dart:ui' as ui; + +import 'package:flutter/animation.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +import 'icon.dart'; +import 'ink_well.dart'; +import 'shadows.dart'; +import 'theme.dart'; + +const Duration _kMenuDuration = const Duration(milliseconds: 300); +const double _kMenuItemHeight = 48.0; +const double _kMenuHorizontalPadding = 36.0; +const double _kBaselineOffsetFromBottom = 20.0; +const Border _kDropdownUnderline = const Border(bottom: const BorderSide(color: const Color(0xFFBDBDBD), width: 2.0)); + +class _DropdownMenu extends StatelessComponent { + _DropdownMenu({ + Key key, + this.items, + this.rect, + this.performance, + this.selectedIndex, + this.level: 4 + }) : super(key: key) { + assert(items != null); + assert(performance != null); + } + + final List items; + final Rect rect; + final PerformanceView performance; + final int selectedIndex; + final int level; + + Widget build(BuildContext context) { + // The menu is shown in three stages (unit timing in brackets): + // [0 - 0.25] - Fade in a rect-sized menu container with the selected item. + // [0.25 - 0.5] - Grow the otherwise empty menu container from the center + // until it's big enough for as many items as we're going to show. + // [0.5 - 1.0] Fade in the remaining visible items from top to bottom. + // + // When the menu is dismissed we just fade the entire thing out + // in the first 0.25. + + final double unit = 0.5 / (items.length + 1.5); + final List children = []; + for (int itemIndex = 0; itemIndex < items.length; ++itemIndex) { + AnimatedValue opacity; + if (itemIndex == selectedIndex) { + opacity = new AnimatedValue(0.0, end: 1.0, curve: const Interval(0.0, 0.001), reverseCurve: const Interval(0.75, 1.0)); + } else { + final double start = (0.5 + (itemIndex + 1) * unit).clamp(0.0, 1.0); + final double end = (start + 1.5 * unit).clamp(0.0, 1.0); + opacity = new AnimatedValue(0.0, end: 1.0, curve: new Interval(start, end), reverseCurve: const Interval(0.75, 1.0)); + } + children.add(new FadeTransition( + performance: performance, + opacity: opacity, + child: new InkWell( + child: items[itemIndex], + onTap: () { + Navigator.of(context).pop(items[itemIndex].value); + } + ) + )); + } + + final AnimatedValue menuOpacity = new AnimatedValue(0.0, + end: 1.0, + curve: new Interval(0.0, 0.25), + reverseCurve: new Interval(0.75, 1.0) + ); + + final AnimatedValue menuTop = new AnimatedValue(rect.top, + end: rect.top - selectedIndex * rect.height, + curve: new Interval(0.25, 0.5), + reverseCurve: const Interval(0.0, 0.001) + ); + final AnimatedValue menuBottom = new AnimatedValue(rect.bottom, + end: menuTop.end + items.length * rect.height, + curve: new Interval(0.25, 0.5), + reverseCurve: const Interval(0.0, 0.001) + ); + + final BoxPainter menuPainter = new BoxPainter(new BoxDecoration( + backgroundColor: Theme.of(context).canvasColor, + borderRadius: 2.0, + boxShadow: shadows[level] + )); + + return new FadeTransition( + performance: performance, + opacity: menuOpacity, + child: new BuilderTransition( + performance: performance, + variables: >[menuTop, menuBottom], + builder: (BuildContext context) { + RenderBox renderBox = context.findRenderObject(); + return new CustomPaint( + child: new ScrollableViewport(child: new Container(child: new Column(children))), + onPaint: (ui.Canvas canvas, Size size) { + double top = renderBox.globalToLocal(new Point(0.0, menuTop.value)).y; + double bottom = renderBox.globalToLocal(new Point(0.0, menuBottom.value)).y; + menuPainter.paint(canvas, new Rect.fromLTRB(0.0, top, size.width, bottom)); + } + ); + } + ) + ); + } +} + +class _MenuRoute extends PerformanceRoute { + _MenuRoute({ + this.completer, + this.items, + this.selectedIndex, + this.rect, + this.level: 4 + }); + + final Completer completer; + final Rect rect; + final List items; + final int level; + final int selectedIndex; + + bool get ephemeral => true; + bool get modal => true; + bool get opaque => false; + Duration get transitionDuration => _kMenuDuration; + + Widget build(RouteArguments args) { + final Size navigatorSize = navigator.context.findRenderObject().size; + final RelativeRect menuRect = new RelativeRect.fromSize(rect, navigatorSize); + + return new Positioned( + top: menuRect.top - (selectedIndex * rect.height), + right: menuRect.right - _kMenuHorizontalPadding, + left: menuRect.left - _kMenuHorizontalPadding, + child: new Focus( + key: new GlobalObjectKey(this), + autofocus: true, + child: new _DropdownMenu( + items: items, + selectedIndex: selectedIndex, + rect: rect, + level: level, + performance: performance + ) + ) + ); + } + + void didPop([dynamic result]) { + completer.complete(result); + super.didPop(result); + } +} + +class DropdownMenuItem extends StatelessComponent { + DropdownMenuItem({ + Key key, + this.value, + this.child + }) : super(key: key); + + final Widget child; + final dynamic value; + + Widget build(BuildContext context) { + return new Container( + height: _kMenuItemHeight, + padding: const EdgeDims.only(left: 8.0, right: 8.0, top: 6.0), + child: new DefaultTextStyle( + style: Theme.of(context).text.subhead, + child: new Baseline( + baseline: _kMenuItemHeight - _kBaselineOffsetFromBottom, + child: child + ) + ) + ); + } +} + +class DropdownButton extends StatelessComponent { + DropdownButton({ + Key key, + this.items, + this.value, + this.onChanged, + this.level: 4 + }) : super(key: key); + + final List items; + final dynamic value; + final ValueChanged onChanged; + final int level; + + void _showDropdown(BuildContext context, int selectedIndex, GlobalKey indexedStackKey) { + final RenderBox renderBox = indexedStackKey.currentContext.findRenderObject(); + final Rect rect = renderBox.localToGlobal(Point.origin) & renderBox.size; + final Completer completer = new Completer(); + Navigator.of(context).push(new _MenuRoute( + completer: completer, + items: items, + selectedIndex: selectedIndex, + rect: rect, + level: level + )); + completer.future.then((dynamic newValue) { + if (onChanged != null) + onChanged(newValue); + }); + } + + Widget build(BuildContext context) { + GlobalKey indexedStackKey = new GlobalKey(label: 'DropdownButton.IndexedStack'); + int selectedIndex = 0; + for (int itemIndex = 0; itemIndex < items.length; itemIndex++) { + if (items[itemIndex].value == value) { + selectedIndex = itemIndex; + break; + } + } + + return new GestureDetector( + child: new Container( + decoration: new BoxDecoration(border: _kDropdownUnderline), + child: new IntrinsicWidth( + child: new Row([ + new IndexedStack(items, + key: indexedStackKey, + index: selectedIndex, + horizontalAlignment: 0.5 + ), + new Container( + child: new Icon(type: 'navigation/arrow_drop_down', size: 36), + padding: const EdgeDims.only(top: 6.0) + ) + ]) + ) + ), + onTap: () { + _showDropdown(context, selectedIndex, indexedStackKey); + } + ); + } +} diff --git a/packages/flutter/lib/src/material/flat_button.dart b/packages/flutter/lib/src/material/flat_button.dart index 5def34464a..b078dcddd8 100644 --- a/packages/flutter/lib/src/material/flat_button.dart +++ b/packages/flutter/lib/src/material/flat_button.dart @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; diff --git a/packages/flutter/lib/src/material/floating_action_button.dart b/packages/flutter/lib/src/material/floating_action_button.dart index e9b6d83c88..1a6d7d332f 100644 --- a/packages/flutter/lib/src/material/floating_action_button.dart +++ b/packages/flutter/lib/src/material/floating_action_button.dart @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; -import 'icon.dart'; +import 'icon_theme.dart'; +import 'icon_theme_data.dart'; import 'ink_well.dart'; import 'material.dart'; import 'theme.dart'; diff --git a/packages/flutter/lib/src/material/icon.dart b/packages/flutter/lib/src/material/icon.dart index 8c25d35387..da620a6521 100644 --- a/packages/flutter/lib/src/material/icon.dart +++ b/packages/flutter/lib/src/material/icon.dart @@ -2,50 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:ui' as ui; - import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'theme.dart'; - -enum IconThemeColor { white, black } - -class IconThemeData { - const IconThemeData({ this.color }); - final IconThemeColor color; - - bool operator ==(dynamic other) { - if (other is! IconThemeData) - return false; - final IconThemeData typedOther = other; - return color == typedOther; - } - - int get hashCode => color.hashCode; -} - -class IconTheme extends InheritedWidget { - - IconTheme({ - Key key, - this.data, - Widget child - }) : super(key: key, child: child) { - assert(data != null); - assert(child != null); - } - - final IconThemeData data; - - static IconThemeData of(BuildContext context) { - IconTheme result = context.inheritedWidgetOfType(IconTheme); - return result?.data; - } - - bool updateShouldNotify(IconTheme old) => data != old.data; - -} +import 'icon_theme.dart'; +import 'icon_theme_data.dart'; AssetBundle _initIconBundle() { if (rootBundle != null) @@ -63,12 +25,15 @@ class Icon extends StatelessComponent { this.type: '', this.color, this.colorFilter - }) : super(key: key); + }) : super(key: key) { + assert(size != null); + assert(type != null); + } final int size; final String type; final IconThemeColor color; - final ui.ColorFilter colorFilter; + final ColorFilter colorFilter; String _getColorSuffix(BuildContext context) { IconThemeColor iconThemeColor = color; @@ -108,4 +73,10 @@ class Icon extends StatelessComponent { colorFilter: colorFilter ); } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('$type'); + description.add('size: $size'); + } } diff --git a/packages/flutter/lib/src/material/icon_button.dart b/packages/flutter/lib/src/material/icon_button.dart index 7e8abf6334..96be9d5cb7 100644 --- a/packages/flutter/lib/src/material/icon_button.dart +++ b/packages/flutter/lib/src/material/icon_button.dart @@ -2,12 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:ui' as ui; - -import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import 'icon.dart'; +import 'icon_theme_data.dart'; class IconButton extends StatelessComponent { const IconButton({ @@ -20,7 +18,7 @@ class IconButton extends StatelessComponent { final String icon; final IconThemeColor color; - final ui.ColorFilter colorFilter; + final ColorFilter colorFilter; final GestureTapCallback onPressed; Widget build(BuildContext context) { @@ -37,4 +35,9 @@ class IconButton extends StatelessComponent { ) ); } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('$icon'); + } } diff --git a/packages/flutter/lib/src/material/icon_theme.dart b/packages/flutter/lib/src/material/icon_theme.dart new file mode 100644 index 0000000000..38723ff887 --- /dev/null +++ b/packages/flutter/lib/src/material/icon_theme.dart @@ -0,0 +1,32 @@ +// 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:flutter/widgets.dart'; + +import 'icon_theme_data.dart'; + +class IconTheme extends InheritedWidget { + IconTheme({ + Key key, + this.data, + Widget child + }) : super(key: key, child: child) { + assert(data != null); + assert(child != null); + } + + final IconThemeData data; + + static IconThemeData of(BuildContext context) { + IconTheme result = context.inheritedWidgetOfType(IconTheme); + return result?.data; + } + + bool updateShouldNotify(IconTheme old) => data != old.data; + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('$data'); + } +} diff --git a/packages/flutter/lib/src/material/icon_theme_data.dart b/packages/flutter/lib/src/material/icon_theme_data.dart new file mode 100644 index 0000000000..e4a925c697 --- /dev/null +++ b/packages/flutter/lib/src/material/icon_theme_data.dart @@ -0,0 +1,21 @@ +// 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. + +enum IconThemeColor { white, black } + +class IconThemeData { + const IconThemeData({ this.color }); + final IconThemeColor color; + + bool operator ==(dynamic other) { + if (other is! IconThemeData) + return false; + final IconThemeData typedOther = other; + return color == typedOther.color; + } + + int get hashCode => color.hashCode; + + String toString() => '$color'; +} diff --git a/packages/flutter/lib/src/material/ink_well.dart b/packages/flutter/lib/src/material/ink_well.dart index 161be19e5e..0d5ca2d47b 100644 --- a/packages/flutter/lib/src/material/ink_well.dart +++ b/packages/flutter/lib/src/material/ink_well.dart @@ -4,7 +4,6 @@ import 'dart:async'; import 'dart:math' as math; -import 'dart:ui' as ui; import 'package:flutter/animation.dart'; import 'package:flutter/gestures.dart'; @@ -29,7 +28,7 @@ class _InkSplash { _InkSplash(this.position, this.well) { _targetRadius = _getSplashTargetSize(well.size, position); _radius = new AnimatedValue( - _kSplashInitialSize, end: _targetRadius, curve: easeOut); + _kSplashInitialSize, end: _targetRadius, curve: Curves.easeOut); _performance = new ValuePerformance( variable: _radius, @@ -91,7 +90,7 @@ class _InkSplash { void paint(PaintingCanvas canvas) { int opacity = (_kSplashInitialOpacity * (1.1 - (_radius.value / _targetRadius))).floor(); - ui.Paint paint = new ui.Paint()..color = new ui.Color(opacity << 24); + Paint paint = new Paint()..color = new Color(opacity << 24); double radius = _pinnedRadius == null ? _radius.value : _pinnedRadius; canvas.drawCircle(position, radius, paint); } diff --git a/packages/flutter/lib/src/material/input.dart b/packages/flutter/lib/src/material/input.dart index 3102411485..91914b63e4 100644 --- a/packages/flutter/lib/src/material/input.dart +++ b/packages/flutter/lib/src/material/input.dart @@ -4,8 +4,6 @@ import 'package:flutter/animation.dart'; import 'package:flutter/services.dart'; -import 'package:flutter/painting.dart'; -import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'theme.dart'; @@ -118,7 +116,7 @@ class _InputState extends ScrollableState { return new Listener( child: new SizeObserver( - callback: _handleContainerSizeChanged, + onSizeChanged: _handleContainerSizeChanged, child: new Container( child: new Stack(textChildren), padding: _kTextfieldPadding, diff --git a/packages/flutter/lib/src/material/list_item.dart b/packages/flutter/lib/src/material/list_item.dart index 84377c65ef..0352f301ab 100644 --- a/packages/flutter/lib/src/material/list_item.dart +++ b/packages/flutter/lib/src/material/list_item.dart @@ -2,12 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/gestures.dart'; -import 'package:flutter/painting.dart'; import 'package:flutter/widgets.dart'; import 'ink_well.dart'; -import 'constants.dart'; class ListItem extends StatelessComponent { ListItem({ @@ -44,14 +41,12 @@ class ListItem extends StatelessComponent { if (right != null) { children.add(new Container( - margin: new EdgeDims.only(left: 8.0), - width: 40.0, + margin: new EdgeDims.only(left: 16.0), child: right )); } - return new Container( - height: kListItemHeight, + return new Padding( padding: const EdgeDims.symmetric(horizontal: 16.0), child: new InkWell( onTap: onTap, diff --git a/packages/flutter/lib/src/material/material.dart b/packages/flutter/lib/src/material/material.dart index dcfbd2113a..96ada6ff6e 100644 --- a/packages/flutter/lib/src/material/material.dart +++ b/packages/flutter/lib/src/material/material.dart @@ -3,7 +3,6 @@ // found in the LICENSE file. import 'package:flutter/animation.dart'; -import 'package:flutter/painting.dart'; import 'package:flutter/widgets.dart'; import 'constants.dart'; @@ -68,7 +67,7 @@ class Material extends StatelessComponent { return new DefaultTextStyle( style: Theme.of(context).text.body1, child: new AnimatedContainer( - curve: ease, + curve: Curves.ease, duration: kThemeChangeDuration, decoration: new BoxDecoration( backgroundColor: _getBackgroundColor(context), diff --git a/packages/flutter/lib/src/material/material_app.dart b/packages/flutter/lib/src/material/material_app.dart index 04b3087bd6..afe72df031 100644 --- a/packages/flutter/lib/src/material/material_app.dart +++ b/packages/flutter/lib/src/material/material_app.dart @@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/gestures.dart'; -import 'package:flutter/painting.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; @@ -28,9 +26,7 @@ class MaterialApp extends StatefulComponent { this.theme, this.routes, this.onGenerateRoute - }) : super(key: key) { - assert(routes != null); - } + }) : super(key: key); final String title; final ThemeData theme; diff --git a/packages/flutter/lib/src/material/material_button.dart b/packages/flutter/lib/src/material/material_button.dart index 0a343e9edc..1eb4591493 100644 --- a/packages/flutter/lib/src/material/material_button.dart +++ b/packages/flutter/lib/src/material/material_button.dart @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; @@ -48,6 +47,12 @@ abstract class MaterialButton extends StatefulComponent { final bool enabled; final ButtonColor textColor; final GestureTapCallback onPressed; + + void debugFillDescription(List description) { + super.debugFillDescription(description); + if (!enabled) + description.add('disabled'); + } } abstract class MaterialButtonState extends State { diff --git a/packages/flutter/lib/src/material/material_list.dart b/packages/flutter/lib/src/material/material_list.dart new file mode 100644 index 0000000000..105a8b7c91 --- /dev/null +++ b/packages/flutter/lib/src/material/material_list.dart @@ -0,0 +1,64 @@ +// 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:flutter/widgets.dart'; + +import 'constants.dart'; +import 'scrollbar_painter.dart'; + +enum MaterialListType { + oneLine, + oneLineWithAvatar, + twoLine, + threeLine +} + +Map _kItemExtent = const { + MaterialListType.oneLine: kOneLineListItemHeight, + MaterialListType.oneLineWithAvatar: kOneLineListItemWithAvatarHeight, + MaterialListType.twoLine: kTwoLineListItemHeight, + MaterialListType.threeLine: kThreeLineListItemHeight, +}; + +class MaterialList extends StatefulComponent { + MaterialList({ + Key key, + this.initialScrollOffset, + this.onScroll, + this.items, + this.itemBuilder, + this.type: MaterialListType.twoLine + }) : super(key: key); + + final double initialScrollOffset; + final ScrollListener onScroll; + final List items; + final ItemBuilder itemBuilder; + final MaterialListType type; + + _MaterialListState createState() => new _MaterialListState(); +} + +class _MaterialListState extends State> { + + void initState() { + super.initState(); + _scrollbarPainter = new ScrollbarPainter(); + } + + ScrollbarPainter _scrollbarPainter; + + Widget build(BuildContext context) { + return new ScrollableList( + initialScrollOffset: config.initialScrollOffset, + scrollDirection: ScrollDirection.vertical, + onScroll: config.onScroll, + items: config.items, + itemBuilder: config.itemBuilder, + itemExtent: _kItemExtent[config.type], + padding: const EdgeDims.symmetric(vertical: 8.0), + scrollableListPainter: _scrollbarPainter + ); + } +} diff --git a/packages/flutter/lib/src/material/popup_menu.dart b/packages/flutter/lib/src/material/popup_menu.dart index 10d0c2bab0..8954fe4f94 100644 --- a/packages/flutter/lib/src/material/popup_menu.dart +++ b/packages/flutter/lib/src/material/popup_menu.dart @@ -22,14 +22,11 @@ const double _kMenuMaxWidth = 5.0 * _kMenuWidthStep; const double _kMenuHorizontalPadding = 16.0; const double _kMenuVerticalPadding = 8.0; -typedef List PopupMenuItemsBuilder(NavigatorState navigator); - class PopupMenu extends StatelessComponent { PopupMenu({ Key key, this.items, this.level: 4, - this.navigator, this.performance }) : super(key: key) { assert(items != null); @@ -38,7 +35,6 @@ class PopupMenu extends StatelessComponent { final List items; final int level; - final NavigatorState navigator; final PerformanceView performance; Widget build(BuildContext context) { @@ -58,7 +54,7 @@ class PopupMenu extends StatelessComponent { performance: performance, opacity: new AnimatedValue(0.0, end: 1.0, curve: new Interval(start, end)), child: new InkWell( - onTap: () { navigator.pop(items[i].value); }, + onTap: () { Navigator.of(context).pop(items[i].value); }, child: items[i] )) ); @@ -75,7 +71,7 @@ class PopupMenu extends StatelessComponent { variables: >[width, height], builder: (BuildContext context) { return new CustomPaint( - callback: (ui.Canvas canvas, Size size) { + onPaint: (ui.Canvas canvas, Size size) { double widthValue = width.value * size.width; double heightValue = height.value * size.height; painter.paint(canvas, new Rect.fromLTWH(size.width - widthValue, 0.0, widthValue, heightValue)); @@ -114,11 +110,11 @@ class MenuPosition { } class _MenuRoute extends PerformanceRoute { - _MenuRoute({ this.completer, this.position, this.builder, this.level }); + _MenuRoute({ this.completer, this.position, this.items, this.level }); final Completer completer; final MenuPosition position; - final PopupMenuItemsBuilder builder; + final List items; final int level; Performance createPerformance() { @@ -134,7 +130,7 @@ class _MenuRoute extends PerformanceRoute { bool get opaque => false; Duration get transitionDuration => _kMenuDuration; - Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance) { + Widget build(RouteArguments args) { return new Positioned( top: position?.top, right: position?.right, @@ -144,9 +140,8 @@ class _MenuRoute extends PerformanceRoute { key: new GlobalObjectKey(this), autofocus: true, child: new PopupMenu( - items: builder != null ? builder(navigator) : const [], + items: items, level: level, - navigator: navigator, performance: performance ) ) @@ -159,12 +154,12 @@ class _MenuRoute extends PerformanceRoute { } } -Future showMenu({ NavigatorState navigator, MenuPosition position, PopupMenuItemsBuilder builder, int level: 4 }) { +Future showMenu({ BuildContext context, MenuPosition position, List items, int level: 4 }) { Completer completer = new Completer(); - navigator.push(new _MenuRoute( + Navigator.of(context).push(new _MenuRoute( completer: completer, position: position, - builder: builder, + items: items, level: level )); return completer.future; diff --git a/packages/flutter/lib/src/material/progress_indicator.dart b/packages/flutter/lib/src/material/progress_indicator.dart index 2c20a0af3e..ac41cf2066 100644 --- a/packages/flutter/lib/src/material/progress_indicator.dart +++ b/packages/flutter/lib/src/material/progress_indicator.dart @@ -14,15 +14,15 @@ const double _kLinearProgressIndicatorHeight = 6.0; const double _kMinCircularProgressIndicatorSize = 15.0; const double _kCircularProgressIndicatorStrokeWidth = 3.0; +// TODO(hansmuller) implement the support for buffer indicator + abstract class ProgressIndicator extends StatefulComponent { ProgressIndicator({ Key key, - this.value, - this.bufferValue + this.value }) : super(key: key); final double value; // Null for non-determinate progress indicator. - final double bufferValue; // TODO(hansmuller) implement the support for this. Color _getBackgroundColor(BuildContext context) => Theme.of(context).primarySwatch[200]; Color _getValueColor(BuildContext context) => Theme.of(context).primaryColor; @@ -31,6 +31,11 @@ abstract class ProgressIndicator extends StatefulComponent { Widget _buildIndicator(BuildContext context, double performanceValue); _ProgressIndicatorState createState() => new _ProgressIndicatorState(); + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('${(value.clamp(0.0, 1.0) * 100.0).toStringAsFixed(1)}%'); + } } class _ProgressIndicatorState extends State { @@ -40,7 +45,7 @@ class _ProgressIndicatorState extends State { void initState() { super.initState(); _performance = new ValuePerformance( - variable: new AnimatedValue(0.0, end: 1.0, curve: ease), + variable: new AnimatedValue(0.0, end: 1.0, curve: Curves.ease), duration: const Duration(milliseconds: 1500) ); _performance.addStatusListener((PerformanceStatus status) { @@ -72,14 +77,13 @@ class _ProgressIndicatorState extends State { class LinearProgressIndicator extends ProgressIndicator { LinearProgressIndicator({ Key key, - double value, - double bufferValue - }) : super(key: key, value: value, bufferValue: bufferValue); + double value + }) : super(key: key, value: value); - void _paint(BuildContext context, double performanceValue, ui.Canvas canvas, Size size) { + void _paint(BuildContext context, double performanceValue, Canvas canvas, Size size) { Paint paint = new Paint() ..color = _getBackgroundColor(context) - ..setStyle(ui.PaintingStyle.fill); + ..style = ui.PaintingStyle.fill; canvas.drawRect(Point.origin & size, paint); paint.color = _getValueColor(context); @@ -103,7 +107,7 @@ class LinearProgressIndicator extends ProgressIndicator { ), child: new CustomPaint( token: _getCustomPaintToken(performanceValue), - callback: (ui.Canvas canvas, Size size) { + onPaint: (Canvas canvas, Size size) { _paint(context, performanceValue, canvas, size); } ) @@ -120,19 +124,18 @@ class CircularProgressIndicator extends ProgressIndicator { CircularProgressIndicator({ Key key, - double value, - double bufferValue - }) : super(key: key, value: value, bufferValue: bufferValue); + double value + }) : super(key: key, value: value); - void _paint(BuildContext context, double performanceValue, ui.Canvas canvas, Size size) { + void _paint(BuildContext context, double performanceValue, Canvas canvas, Size size) { Paint paint = new Paint() ..color = _getValueColor(context) ..strokeWidth = _kCircularProgressIndicatorStrokeWidth - ..setStyle(ui.PaintingStyle.stroke); + ..style = ui.PaintingStyle.stroke; if (value != null) { double angle = value.clamp(0.0, 1.0) * _kSweep; - ui.Path path = new ui.Path() + Path path = new Path() ..arcTo(Point.origin & size, _kStartAngle, angle, false); canvas.drawPath(path, paint); } else { @@ -140,7 +143,7 @@ class CircularProgressIndicator extends ProgressIndicator { double endAngle = startAngle + _kTwoPI * 0.75; double arcAngle = startAngle.clamp(0.0, _kTwoPI); double arcSweep = endAngle.clamp(0.0, _kTwoPI) - arcAngle; - ui.Path path = new ui.Path() + Path path = new Path() ..arcTo(Point.origin & size, _kStartAngle + arcAngle, arcSweep, false); canvas.drawPath(path, paint); } @@ -154,7 +157,7 @@ class CircularProgressIndicator extends ProgressIndicator { ), child: new CustomPaint( token: _getCustomPaintToken(performanceValue), - callback: (ui.Canvas canvas, Size size) { + onPaint: (Canvas canvas, Size size) { _paint(context, performanceValue, canvas, size); } ) diff --git a/packages/flutter/lib/src/material/radial_reaction.dart b/packages/flutter/lib/src/material/radial_reaction.dart index ee4748f909..7d550b6885 100644 --- a/packages/flutter/lib/src/material/radial_reaction.dart +++ b/packages/flutter/lib/src/material/radial_reaction.dart @@ -3,10 +3,9 @@ // found in the LICENSE file. import 'dart:async'; -import 'dart:ui' as ui; -import 'dart:ui' show Point, Offset, Color, Paint; import 'package:flutter/animation.dart'; +import 'package:flutter/painting.dart'; const Duration _kShowDuration = const Duration(milliseconds: 300); const Duration _kHideDuration = const Duration(milliseconds: 200); @@ -27,9 +26,9 @@ class RadialReaction { this.radius, Point startPosition }) { - _outerOpacity = new AnimatedValue(0.0, end: _kMaxOpacity, curve: easeOut); - _innerCenter = new AnimatedValue(startPosition, end: center, curve: easeOut); - _innerRadius = new AnimatedValue(0.0, end: radius, curve: easeOut); + _outerOpacity = new AnimatedValue(0.0, end: _kMaxOpacity, curve: Curves.easeOut); + _innerCenter = new AnimatedValue(startPosition, end: center, curve: Curves.easeOut); + _innerRadius = new AnimatedValue(0.0, end: radius, curve: Curves.easeOut); _showPerformance = new Performance(duration: _kShowDuration) ..addListener(() { _showPerformance.updateVariable(_outerOpacity); @@ -37,7 +36,7 @@ class RadialReaction { _showPerformance.updateVariable(_innerRadius); }); _fade = new ValuePerformance( - variable: new AnimatedValue(1.0, end: 0.0, curve: easeIn), + variable: new AnimatedValue(1.0, end: 0.0, curve: Curves.easeIn), duration: _kHideDuration ); } @@ -82,7 +81,7 @@ class RadialReaction { final Paint _innerPaint = new Paint(); /// Paint the reaction onto the given canvas at the given offset - void paint(ui.Canvas canvas, Offset offset) { + void paint(Canvas canvas, Offset offset) { _outerPaint.color = _kOuterColor.withAlpha(_roundOpacity(_outerOpacity.value * _fade.value)); canvas.drawCircle(center + offset, radius, _outerPaint); diff --git a/packages/flutter/lib/src/material/radio.dart b/packages/flutter/lib/src/material/radio.dart index e2e65d80d3..a8c33aabf3 100644 --- a/packages/flutter/lib/src/material/radio.dart +++ b/packages/flutter/lib/src/material/radio.dart @@ -8,8 +8,8 @@ import 'package:flutter/widgets.dart'; import 'theme.dart'; -const ui.Color _kLightOffColor = const ui.Color(0x8A000000); -const ui.Color _kDarkOffColor = const ui.Color(0xB2FFFFFF); +const Color _kLightOffColor = const Color(0x8A000000); +const Color _kDarkOffColor = const Color(0xB2FFFFFF); typedef void RadioValueChanged(Object value); @@ -45,18 +45,18 @@ class Radio extends StatelessComponent { width: kDiameter, height: kDiameter, child: new CustomPaint( - callback: (ui.Canvas canvas, Size size) { - - Paint paint = new Paint()..color = _getColor(context); + onPaint: (Canvas canvas, Size size) { // Draw the outer circle - paint.setStyle(ui.PaintingStyle.stroke); - paint.strokeWidth = 2.0; + Paint paint = new Paint() + ..color = _getColor(context) + ..style = ui.PaintingStyle.stroke + ..strokeWidth = 2.0; canvas.drawCircle(const Point(kOuterRadius, kOuterRadius), kOuterRadius, paint); // Draw the inner circle if (value == groupValue) { - paint.setStyle(ui.PaintingStyle.fill); + paint.style = ui.PaintingStyle.fill; canvas.drawCircle(const Point(kOuterRadius, kOuterRadius), kInnerRadius, paint); } } diff --git a/packages/flutter/lib/src/material/raised_button.dart b/packages/flutter/lib/src/material/raised_button.dart index 2f1d9f7ce4..4b023238dd 100644 --- a/packages/flutter/lib/src/material/raised_button.dart +++ b/packages/flutter/lib/src/material/raised_button.dart @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; diff --git a/packages/flutter/lib/src/material/scaffold.dart b/packages/flutter/lib/src/material/scaffold.dart index a33e754c35..6eb8b39952 100644 --- a/packages/flutter/lib/src/material/scaffold.dart +++ b/packages/flutter/lib/src/material/scaffold.dart @@ -4,10 +4,10 @@ import 'dart:ui' as ui; -import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'constants.dart'; +import 'material.dart'; class Scaffold extends StatelessComponent { Scaffold({ @@ -39,7 +39,9 @@ class Scaffold extends StatelessComponent { if (body != null) { children.add(new Positioned( top: toolBarHeight, right: 0.0, bottom: statusBarHeight, left: 0.0, - child: body + child: new Material( + child: body + ) )); } diff --git a/packages/flutter/lib/src/material/scrollbar_painter.dart b/packages/flutter/lib/src/material/scrollbar_painter.dart index cd839f43f0..5eb8f72ef0 100644 --- a/packages/flutter/lib/src/material/scrollbar_painter.dart +++ b/packages/flutter/lib/src/material/scrollbar_painter.dart @@ -62,7 +62,7 @@ class ScrollbarPainter extends ScrollableListPainter { Future scrollStarted() { _fade ??= new ValuePerformance() ..duration = _kScrollbarThumbFadeDuration - ..variable = new AnimatedValue(0.0, end: 1.0, curve: ease) + ..variable = new AnimatedValue(0.0, end: 1.0, curve: Curves.ease) ..addListener(() { _opacity = _fade.value; renderer?.markNeedsPaint(); diff --git a/packages/flutter/lib/src/material/snack_bar.dart b/packages/flutter/lib/src/material/snack_bar.dart index 3441fa7438..6783836555 100644 --- a/packages/flutter/lib/src/material/snack_bar.dart +++ b/packages/flutter/lib/src/material/snack_bar.dart @@ -3,8 +3,6 @@ // found in the LICENSE file. import 'package:flutter/animation.dart'; -import 'package:flutter/gestures.dart'; -import 'package:flutter/painting.dart'; import 'package:flutter/widgets.dart'; import 'constants.dart'; @@ -69,8 +67,8 @@ class SnackBar extends StatelessComponent { height: new AnimatedValue( 0.0, end: kSnackBarHeight, - curve: easeIn, - reverseCurve: easeOut + curve: Curves.easeIn, + reverseCurve: Curves.easeOut ), child: new ClipRect( child: new OverflowBox( @@ -104,10 +102,10 @@ class _SnackBarRoute extends PerformanceRoute { bool get modal => false; Duration get transitionDuration => const Duration(milliseconds: 200); - Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance) => null; + Widget build(RouteArguments args) => null; } -void showSnackBar({ NavigatorState navigator, GlobalKey placeholderKey, Widget content, List actions }) { +void showSnackBar({ BuildContext context, GlobalKey placeholderKey, Widget content, List actions }) { Route route = new _SnackBarRoute(); SnackBar snackBar = new SnackBar( content: content, @@ -115,5 +113,5 @@ void showSnackBar({ NavigatorState navigator, GlobalKey placeh performance: route.performance ); placeholderKey.currentState.child = snackBar; - navigator.push(route); + Navigator.of(context).push(route); } diff --git a/packages/flutter/lib/src/material/switch.dart b/packages/flutter/lib/src/material/switch.dart index 9de1a2c203..9fbed9b21d 100644 --- a/packages/flutter/lib/src/material/switch.dart +++ b/packages/flutter/lib/src/material/switch.dart @@ -6,7 +6,6 @@ import 'dart:async'; import 'dart:ui' as ui; import 'package:flutter/painting.dart'; -import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -16,8 +15,8 @@ import 'theme.dart'; export 'package:flutter/rendering.dart' show ValueChanged; -const ui.Color _kThumbOffColor = const ui.Color(0xFFFAFAFA); -const ui.Color _kTrackOffColor = const ui.Color(0x42000000); +const Color _kThumbOffColor = const Color(0xFFFAFAFA); +const Color _kTrackOffColor = const Color(0x42000000); const double _kSwitchWidth = 35.0; const double _kThumbRadius = 10.0; const double _kSwitchHeight = _kThumbRadius * 2.0; @@ -113,18 +112,18 @@ class _RenderSwitch extends RenderToggleable { void paint(PaintingContext context, Offset offset) { final PaintingCanvas canvas = context.canvas; - ui.Color thumbColor = _kThumbOffColor; - ui.Color trackColor = _kTrackOffColor; + Color thumbColor = _kThumbOffColor; + Color trackColor = _kTrackOffColor; if (value) { thumbColor = _thumbColor; - trackColor = new ui.Color(_thumbColor.value & 0x80FFFFFF); + trackColor = new Color(_thumbColor.value & 0x80FFFFFF); } // Draw the track rrect - ui.Paint paint = new ui.Paint() + Paint paint = new Paint() ..color = trackColor ..style = ui.PaintingStyle.fill; - ui.Rect rect = new ui.Rect.fromLTWH(offset.dx, + Rect rect = new Rect.fromLTWH(offset.dx, offset.dy + _kSwitchHeight / 2.0 - _kTrackHeight / 2.0, _kTrackWidth, _kTrackHeight); ui.RRect rrect = new ui.RRect() diff --git a/packages/flutter/lib/src/material/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index 695708b531..da976a08fa 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -3,21 +3,19 @@ // found in the LICENSE file. import 'dart:math' as math; -import 'dart:ui' as ui; import 'package:newton/newton.dart'; import 'package:flutter/animation.dart'; -import 'package:flutter/gestures.dart'; -import 'package:flutter/painting.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; import 'constants.dart'; import 'icon.dart'; +import 'icon_theme.dart'; +import 'icon_theme_data.dart'; import 'ink_well.dart'; import 'theme.dart'; -import 'typography.dart'; typedef void TabSelectedIndexChanged(int selectedIndex); typedef void TabLayoutChanged(Size size, List widths); @@ -283,6 +281,16 @@ class TabLabel { final String text; final String icon; + + String toString() { + if (text != null && icon != null) + return '"$text" ($icon)'; + if (text != null) + return '"$text"'; + if (icon != null) + return '$icon'; + return 'EMPTY TAB LABEL'; + } } class Tab extends StatelessComponent { @@ -312,7 +320,7 @@ class Tab extends StatelessComponent { Widget _buildLabelIcon() { assert(label.icon != null); Color iconColor = selected ? selectedColor : color; - ui.ColorFilter filter = new ui.ColorFilter.mode(iconColor, ui.TransferMode.srcATop); + ColorFilter filter = new ColorFilter.mode(iconColor, TransferMode.srcATop); return new Icon(type: label.icon, size: _kTabIconSize, colorFilter: filter); } @@ -337,7 +345,7 @@ class Tab extends StatelessComponent { } Container centeredLabel = new Container( - child: new Center(child: labelContent), + child: new Center(child: labelContent, shrinkWrap: ShrinkWrap.both), constraints: new BoxConstraints(minWidth: _kMinTabWidth), padding: _kTabLabelPadding ); @@ -347,6 +355,11 @@ class Tab extends StatelessComponent { child: centeredLabel ); } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('$label'); + } } class _TabsScrollBehavior extends BoundedBehavior { @@ -391,7 +404,7 @@ class _TabBarState extends ScrollableState { super.initState(); _indicatorAnimation = new ValuePerformance() ..duration = _kTabBarScroll - ..variable = new AnimatedRectValue(null, curve: ease); + ..variable = new AnimatedRectValue(null, curve: Curves.ease); scrollBehavior.isScrollable = config.isScrollable; } @@ -496,18 +509,8 @@ class _TabBarState extends ScrollableState { indicatorColor = Colors.white; } - TextStyle textStyle; - IconThemeColor iconThemeColor; - switch (themeData.primaryColorBrightness) { - case ThemeBrightness.light: - textStyle = Typography.black.body1; - iconThemeColor = IconThemeColor.black; - break; - case ThemeBrightness.dark: - textStyle = Typography.white.body1; - iconThemeColor = IconThemeColor.white; - break; - } + TextStyle textStyle = themeData.primaryTextTheme.body1; + IconThemeData iconTheme = themeData.primaryIconTheme; List tabs = []; bool textAndIcons = false; @@ -519,7 +522,7 @@ class _TabBarState extends ScrollableState { } Widget content = new IconTheme( - data: new IconThemeData(color: iconThemeColor), + data: iconTheme, child: new DefaultTextStyle( style: textStyle, child: new BuilderTransition( @@ -542,7 +545,7 @@ class _TabBarState extends ScrollableState { if (config.isScrollable) { content = new SizeObserver( - callback: _handleViewportSizeChanged, + onSizeChanged: _handleViewportSizeChanged, child: new Viewport( scrollDirection: ScrollDirection.horizontal, scrollOffset: new Offset(scrollOffset, 0.0), diff --git a/packages/flutter/lib/src/material/theme.dart b/packages/flutter/lib/src/material/theme.dart index aeff56fb43..7d9233a7c5 100644 --- a/packages/flutter/lib/src/material/theme.dart +++ b/packages/flutter/lib/src/material/theme.dart @@ -28,4 +28,9 @@ class Theme extends InheritedWidget { } bool updateShouldNotify(Theme old) => data != old.data; + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('$data'); + } } diff --git a/packages/flutter/lib/src/material/theme_data.dart b/packages/flutter/lib/src/material/theme_data.dart index f5a8e1fabd..8e79255b9f 100644 --- a/packages/flutter/lib/src/material/theme_data.dart +++ b/packages/flutter/lib/src/material/theme_data.dart @@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:ui'; +import 'dart:ui' show Color; -import 'package:flutter/src/material/typography.dart'; -import 'package:flutter/src/material/colors.dart'; +import 'colors.dart'; +import 'icon_theme_data.dart'; +import 'typography.dart'; enum ThemeBrightness { dark, light } @@ -82,6 +83,19 @@ class ThemeData { /// icons placed on top of the primary color (e.g. toolbar text). final ThemeBrightness primaryColorBrightness; + /// A text theme that contrasts with the primary color. + TextTheme get primaryTextTheme { + if (primaryColorBrightness == ThemeBrightness.dark) + return Typography.white; + return Typography.black; + } + + IconThemeData get primaryIconTheme { + if (primaryColorBrightness == ThemeBrightness.dark) + return const IconThemeData(color: IconThemeColor.white); + return const IconThemeData(color: IconThemeColor.black); + } + /// The foreground color for widgets (knobs, text, etc) Color get accentColor => _accentColor; Color _accentColor; @@ -124,4 +138,6 @@ class ThemeData { value = 37 * value + accentColorBrightness.hashCode; return value; } + + String toString() => '$primaryColor $brightness etc...'; } diff --git a/packages/flutter/lib/src/material/title.dart b/packages/flutter/lib/src/material/title.dart index deca5d18b8..293320c1a6 100644 --- a/packages/flutter/lib/src/material/title.dart +++ b/packages/flutter/lib/src/material/title.dart @@ -17,4 +17,9 @@ class Title extends StatelessComponent { updateTaskDescription(title, Theme.of(context).primaryColor); return child; } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('"$title"'); + } } diff --git a/packages/flutter/lib/src/material/tool_bar.dart b/packages/flutter/lib/src/material/tool_bar.dart index cdcbe9ccac..c4ac519c5a 100644 --- a/packages/flutter/lib/src/material/tool_bar.dart +++ b/packages/flutter/lib/src/material/tool_bar.dart @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/painting.dart'; import 'package:flutter/widgets.dart'; import 'constants.dart'; -import 'icon.dart'; +import 'icon_theme.dart'; +import 'icon_theme_data.dart'; import 'shadows.dart'; import 'theme.dart'; import 'typography.dart'; @@ -18,7 +18,8 @@ class ToolBar extends StatelessComponent { this.center, this.right, this.level: 2, - this.backgroundColor + this.backgroundColor, + this.textTheme }) : super(key: key); final Widget left; @@ -26,22 +27,22 @@ class ToolBar extends StatelessComponent { final List right; final int level; final Color backgroundColor; + final TextTheme textTheme; Widget build(BuildContext context) { Color color = backgroundColor; IconThemeData iconThemeData; - TextStyle centerStyle = Typography.white.title; - TextStyle sideStyle = Typography.white.body1; - if (color == null) { + TextStyle centerStyle = textTheme?.title; + TextStyle sideStyle = textTheme?.body1; + + if (color == null || iconThemeData == null || textTheme == null) { ThemeData themeData = Theme.of(context); - color = themeData.primaryColor; - if (themeData.primaryColorBrightness == ThemeBrightness.light) { - centerStyle = Typography.black.title; - sideStyle = Typography.black.body2; - iconThemeData = const IconThemeData(color: IconThemeColor.black); - } else { - iconThemeData = const IconThemeData(color: IconThemeColor.white); - } + color ??= themeData.primaryColor; + iconThemeData ??= themeData.primaryIconTheme; + + TextTheme primaryTextTheme = themeData.primaryTextTheme; + centerStyle ??= primaryTextTheme.title; + sideStyle ??= primaryTextTheme.body2; } List children = new List(); diff --git a/packages/flutter/lib/src/material/typography.dart b/packages/flutter/lib/src/material/typography.dart index 396b0acd1f..b9eb2061f6 100644 --- a/packages/flutter/lib/src/material/typography.dart +++ b/packages/flutter/lib/src/material/typography.dart @@ -7,7 +7,8 @@ import 'dart:ui' show Color; import 'package:flutter/painting.dart'; -import 'package:flutter/src/material/colors.dart'; + +import 'colors.dart'; // TODO(eseidel): Font weights are supposed to be language relative! // TODO(jackson): Baseline should be language relative! diff --git a/packages/flutter/lib/src/painting/basic_types.dart b/packages/flutter/lib/src/painting/basic_types.dart new file mode 100644 index 0000000000..e2edd579b2 --- /dev/null +++ b/packages/flutter/lib/src/painting/basic_types.dart @@ -0,0 +1,20 @@ +// 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. + +export 'dart:ui' show + Canvas, + Color, + ColorFilter, + FontStyle, + FontWeight, + Offset, + Paint, + Path, + Point, + Rect, + Size, + TextAlign, + TextBaseline, + TextDecoration, + TextDecorationStyle; diff --git a/packages/flutter/lib/src/painting/box_painter.dart b/packages/flutter/lib/src/painting/box_painter.dart index 117c71823b..0980795733 100644 --- a/packages/flutter/lib/src/painting/box_painter.dart +++ b/packages/flutter/lib/src/painting/box_painter.dart @@ -4,10 +4,10 @@ import 'dart:math' as math; import 'dart:ui' as ui; -import 'dart:ui' show Point, Offset, Size, Rect, Color, Paint, Path; import 'package:flutter/services.dart'; +import 'basic_types.dart'; import 'shadows.dart'; /// An immutable set of offsets in each of the four cardinal directions. @@ -51,7 +51,7 @@ class EdgeDims { /// The size that this edge dims would occupy with an empty interior. Size get collapsedSize => new Size(left + right, top + bottom); - EdgeDims operator-(EdgeDims other) { + EdgeDims operator -(EdgeDims other) { return new EdgeDims.TRBL( top - other.top, right - other.right, @@ -60,7 +60,7 @@ class EdgeDims { ); } - EdgeDims operator+(EdgeDims other) { + EdgeDims operator +(EdgeDims other) { return new EdgeDims.TRBL( top + other.top, right + other.right, @@ -69,7 +69,7 @@ class EdgeDims { ); } - EdgeDims operator*(double other) { + EdgeDims operator *(double other) { return new EdgeDims.TRBL( top * other, right * other, @@ -78,7 +78,7 @@ class EdgeDims { ); } - EdgeDims operator/(double other) { + EdgeDims operator /(double other) { return new EdgeDims.TRBL( top / other, right / other, @@ -87,7 +87,7 @@ class EdgeDims { ); } - EdgeDims operator~/(double other) { + EdgeDims operator ~/(double other) { return new EdgeDims.TRBL( (top ~/ other).toDouble(), (right ~/ other).toDouble(), @@ -96,7 +96,7 @@ class EdgeDims { ); } - EdgeDims operator%(double other) { + EdgeDims operator %(double other) { return new EdgeDims.TRBL( top % other, right % other, @@ -166,12 +166,23 @@ class BorderSide { /// A black border side of zero width static const none = const BorderSide(width: 0.0); + bool operator ==(dynamic other) { + if (identical(this, other)) + return true; + if (other is! BorderSide) + return false; + final BorderSide typedOther = other; + return color == typedOther.color && + width == typedOther.width; + } + int get hashCode { int value = 373; - value = 37 * value * color.hashCode; - value = 37 * value * width.hashCode; + value = 37 * value + color.hashCode; + value = 37 * value + width.hashCode; return value; } + String toString() => 'BorderSide($color, $width)'; } @@ -210,14 +221,27 @@ class Border { return new EdgeDims.TRBL(top.width, right.width, bottom.width, left.width); } + bool operator ==(dynamic other) { + if (identical(this, other)) + return true; + if (other is! Border) + return false; + final Border typedOther = other; + return top == typedOther.top && + right == typedOther.right && + bottom == typedOther.bottom && + left == typedOther.left; + } + int get hashCode { int value = 373; - value = 37 * value * top.hashCode; - value = 37 * value * right.hashCode; - value = 37 * value * bottom.hashCode; - value = 37 * value * left.hashCode; + value = 37 * value + top.hashCode; + value = 37 * value + right.hashCode; + value = 37 * value + bottom.hashCode; + value = 37 * value + left.hashCode; return value; } + String toString() => 'Border($top, $right, $bottom, $left)'; } @@ -290,25 +314,43 @@ class BoxShadow { return result; } + bool operator ==(dynamic other) { + if (identical(this, other)) + return true; + if (other is! BoxShadow) + return false; + final BoxShadow typedOther = other; + return color == typedOther.color && + offset == typedOther.offset && + blur == typedOther.blur; + } + + int get hashCode { + int value = 373; + value = 37 * value + color.hashCode; + value = 37 * value + offset.hashCode; + value = 37 * value + blur.hashCode; + return value; + } + String toString() => 'BoxShadow($color, $offset, $blur)'; } /// A 2D gradient abstract class Gradient { + const Gradient(); ui.Shader createShader(); } /// A 2D linear gradient class LinearGradient extends Gradient { - LinearGradient({ + const LinearGradient({ this.begin, this.end, this.colors, this.stops, this.tileMode: ui.TileMode.clamp - }) { - assert(colors.length == stops.length); - } + }); /// The point at which stop 0.0 of the gradient is placed final Point begin; @@ -323,7 +365,8 @@ class LinearGradient extends Gradient { /// A list of values from 0.0 to 1.0 that denote fractions of the vector from start to end /// - /// Note: This list must have the same length as [colors]. + /// Note: If specified, this list must have the same length as [colors]. Otherwise the colors + /// are distributed evenly between [begin] and [end]. final List stops; /// How this gradient should tile the plane @@ -333,6 +376,57 @@ class LinearGradient extends Gradient { return new ui.Gradient.linear([begin, end], this.colors, this.stops, this.tileMode); } + bool operator ==(dynamic other) { + if (identical(this, other)) + return true; + if (other is! LinearGradient) + return false; + final LinearGradient typedOther = other; + if (begin != typedOther.begin || + end != typedOther.end || + tileMode != typedOther.tileMode || + colors?.length != typedOther.colors?.length || + stops?.length != typedOther.stops?.length) + return false; + if (colors != null) { + assert(typedOther.colors != null); + assert(colors.length == typedOther.colors.length); + for (int i = 0; i < colors.length; i += 1) { + if (colors[i] != typedOther.colors[i]) + return false; + } + } + if (stops != null) { + assert(typedOther.stops != null); + assert(stops.length == typedOther.stops.length); + for (int i = 0; i < stops.length; i += 1) { + if (stops[i] != typedOther.stops[i]) + return false; + } + } + return true; + } + + int get hashCode { + int value = 373; + value = 37 * value + begin.hashCode; + value = 37 * value + end.hashCode; + value = 37 * value + tileMode.hashCode; + if (colors != null) { + for (int i = 0; i < colors.length; i += 1) + value = 37 * value + colors[i].hashCode; + } else { + value = 37 * value + null.hashCode; + } + if (stops != null) { + for (int i = 0; i < stops.length; i += 1) + value = 37 * value + stops[i].hashCode; + } else { + value = 37 * value + null.hashCode; + } + return value; + } + String toString() { return 'LinearGradient($begin, $end, $colors, $stops, $tileMode)'; } @@ -340,7 +434,7 @@ class LinearGradient extends Gradient { /// A 2D radial gradient class RadialGradient extends Gradient { - RadialGradient({ + const RadialGradient({ this.center, this.radius, this.colors, @@ -374,6 +468,57 @@ class RadialGradient extends Gradient { return new ui.Gradient.radial(center, radius, colors, stops, tileMode); } + bool operator ==(dynamic other) { + if (identical(this, other)) + return true; + if (other is! RadialGradient) + return false; + final RadialGradient typedOther = other; + if (center != typedOther.center || + radius != typedOther.radius || + tileMode != typedOther.tileMode || + colors?.length != typedOther.colors?.length || + stops?.length != typedOther.stops?.length) + return false; + if (colors != null) { + assert(typedOther.colors != null); + assert(colors.length == typedOther.colors.length); + for (int i = 0; i < colors.length; i += 1) { + if (colors[i] != typedOther.colors[i]) + return false; + } + } + if (stops != null) { + assert(typedOther.stops != null); + assert(stops.length == typedOther.stops.length); + for (int i = 0; i < stops.length; i += 1) { + if (stops[i] != typedOther.stops[i]) + return false; + } + } + return true; + } + + int get hashCode { + int value = 373; + value = 37 * value + center.hashCode; + value = 37 * value + radius.hashCode; + value = 37 * value + tileMode.hashCode; + if (colors != null) { + for (int i = 0; i < colors.length; i += 1) + value = 37 * value + colors[i].hashCode; + } else { + value = 37 * value + null.hashCode; + } + if (stops != null) { + for (int i = 0; i < stops.length; i += 1) + value = 37 * value + stops[i].hashCode; + } else { + value = 37 * value + null.hashCode; + } + return value; + } + String toString() { return 'RadialGradient($center, $radius, $colors, $stops, $tileMode)'; } @@ -416,10 +561,10 @@ enum ImageRepeat { /// Paint an image into the given rectangle in the canvas void paintImage({ - ui.Canvas canvas, + Canvas canvas, Rect rect, ui.Image image, - ui.ColorFilter colorFilter, + ColorFilter colorFilter, ImageFit fit, repeat: ImageRepeat.noRepeat, Rect centerSlice, @@ -499,6 +644,14 @@ typedef void BackgroundImageChangeListener(); /// A background image for a box. class BackgroundImage { + BackgroundImage({ + ImageResource image, + this.fit, + this.repeat: ImageRepeat.noRepeat, + this.centerSlice, + this.colorFilter + }) : _imageResource = image; + /// How the background image should be inscribed into the box. final ImageFit fit; @@ -515,24 +668,16 @@ class BackgroundImage { final Rect centerSlice; /// A color filter to apply to the background image before painting it. - final ui.ColorFilter colorFilter; - - BackgroundImage({ - ImageResource image, - this.fit, - this.repeat: ImageRepeat.noRepeat, - this.centerSlice, - this.colorFilter - }) : _imageResource = image; + final ColorFilter colorFilter; /// The image to be painted into the background. ui.Image get image => _image; ui.Image _image; - ImageResource _imageResource; + final ImageResource _imageResource; final List _listeners = - new List(); + new List(); /// Call listener when the background images changes (e.g., arrives from the network). void addChangeListener(BackgroundImageChangeListener listener) { @@ -558,10 +703,32 @@ class BackgroundImage { return; _image = resolvedImage; final List localListeners = - new List.from(_listeners); - for (BackgroundImageChangeListener listener in localListeners) { + new List.from(_listeners); + for (BackgroundImageChangeListener listener in localListeners) listener(); - } + } + + bool operator ==(dynamic other) { + if (identical(this, other)) + return true; + if (other is! BackgroundImage) + return false; + final BackgroundImage typedOther = other; + return fit == typedOther.fit && + repeat == typedOther.repeat && + centerSlice == typedOther.centerSlice && + colorFilter == typedOther.colorFilter && + _imageResource == typedOther._imageResource; + } + + int get hashCode { + int value = 373; + value = 37 * value + fit.hashCode; + value = 37 * value + repeat.hashCode; + value = 37 * value + centerSlice.hashCode; + value = 37 * value + colorFilter.hashCode; + value = 37 * value + _imageResource.hashCode; + return value; } String toString() => 'BackgroundImage($fit, $repeat)'; @@ -651,6 +818,33 @@ class BoxDecoration { ); } + bool operator ==(dynamic other) { + if (identical(this, other)) + return true; + if (other is! BoxDecoration) + return false; + final BoxDecoration typedOther = other; + return backgroundColor == typedOther.backgroundColor && + backgroundImage == typedOther.backgroundImage && + border == typedOther.border && + borderRadius == typedOther.borderRadius && + boxShadow == typedOther.boxShadow && + gradient == typedOther.gradient && + shape == typedOther.shape; + } + + int get hashCode { + int value = 373; + value = 37 * value + backgroundColor.hashCode; + value = 37 * value + backgroundImage.hashCode; + value = 37 * value + border.hashCode; + value = 37 * value + borderRadius.hashCode; + value = 37 * value + boxShadow.hashCode; + value = 37 * value + gradient.hashCode; + value = 37 * value + shape.hashCode; + return value; + } + String toString([String prefix = '']) { List result = []; if (backgroundColor != null) @@ -867,7 +1061,7 @@ class BoxPainter { Paint paint = new Paint() ..color = _decoration.border.top.color ..strokeWidth = width - ..setStyle(ui.PaintingStyle.stroke); + ..style = ui.PaintingStyle.stroke; Point center = rect.center; double radius = (rect.shortestSide - width) / 2.0; canvas.drawCircle(center, radius, paint); diff --git a/packages/flutter/lib/src/painting/text_painter.dart b/packages/flutter/lib/src/painting/text_painter.dart index 710a11f11d..b5140f3bbd 100644 --- a/packages/flutter/lib/src/painting/text_painter.dart +++ b/packages/flutter/lib/src/painting/text_painter.dart @@ -4,10 +4,9 @@ import 'dart:ui' as ui; +import 'basic_types.dart'; import 'text_style.dart'; -export 'text_style.dart'; - /// An immutable span of text abstract class TextSpan { // This class must be immutable, because we won't notice when it changes diff --git a/packages/flutter/lib/src/painting/text_style.dart b/packages/flutter/lib/src/painting/text_style.dart index cf241df700..86aa5febd0 100644 --- a/packages/flutter/lib/src/painting/text_style.dart +++ b/packages/flutter/lib/src/painting/text_style.dart @@ -3,9 +3,8 @@ // found in the LICENSE file. import 'dart:ui' as ui; -import 'dart:ui' show Point, Offset, Size, Rect, Color, Paint, Path, FontWeight, FontStyle, TextAlign, TextBaseline, TextDecoration, TextDecorationStyle; -export 'dart:ui' show FontWeight, FontStyle, TextAlign, TextBaseline, TextDecoration, TextDecorationStyle; +import 'basic_types.dart'; /// A normal font weight const normal = FontWeight.w400; diff --git a/packages/flutter/lib/src/rendering/basic_types.dart b/packages/flutter/lib/src/rendering/basic_types.dart new file mode 100644 index 0000000000..acc920dd37 --- /dev/null +++ b/packages/flutter/lib/src/rendering/basic_types.dart @@ -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. + +export 'dart:ui' show + Canvas, + Color, + ColorFilter, + Offset, + Paint, + Path, + Point, + Rect, + Size, + TransferMode; diff --git a/packages/flutter/lib/src/rendering/binding.dart b/packages/flutter/lib/src/rendering/binding.dart index e501ff39fa..d62d9bec2a 100644 --- a/packages/flutter/lib/src/rendering/binding.dart +++ b/packages/flutter/lib/src/rendering/binding.dart @@ -6,6 +6,7 @@ import 'dart:ui' as ui; import 'package:flutter/animation.dart'; import 'package:flutter/gestures.dart'; +import 'package:flutter/rendering.dart'; import 'box.dart'; import 'hit_test.dart'; @@ -61,7 +62,8 @@ class _UiEventConverter { Point position = new Point(event.x, event.y); _PointerState state = _stateForPointer[event.pointer]; - double dx, dy; + double dx = 0.0; + double dy = 0.0; switch (event.type) { case 'pointerdown': if (state == null) { @@ -252,5 +254,5 @@ class FlutterBinding extends HitTestTarget { /// Prints a textual representation of the entire render tree void debugDumpRenderTree() { - FlutterBinding.instance.renderView.toStringDeep().split('\n').forEach(print); + debugPrint(FlutterBinding.instance.renderView.toStringDeep()); } diff --git a/packages/flutter/lib/src/rendering/box.dart b/packages/flutter/lib/src/rendering/box.dart index 25bb5d8829..db5655459c 100644 --- a/packages/flutter/lib/src/rendering/box.dart +++ b/packages/flutter/lib/src/rendering/box.dart @@ -254,7 +254,21 @@ class BoxConstraints extends Constraints { return value; } - String toString() => "BoxConstraints($minWidth<=w<=$maxWidth, $minHeight<=h<=$maxHeight)"; + String toString() { + if (minWidth == double.INFINITY && minHeight == double.INFINITY) + return 'BoxConstraints(biggest)'; + if (minWidth == 0 && maxWidth == double.INFINITY && + minHeight == 0 && maxHeight == double.INFINITY) + return 'BoxConstraints(unconstrained)'; + String describe(double min, double max, String dim) { + if (min == max) + return '$dim=${min.toStringAsFixed(1)}'; + return '${min.toStringAsFixed(1)}<=$dim<=${max.toStringAsFixed(1)}'; + } + final String width = describe(minWidth, maxWidth, 'w'); + final String height = describe(minHeight, maxHeight, 'h'); + return 'BoxConstraints($width, $height)'; + } } /// A hit test entry used by [RenderBox] @@ -359,9 +373,11 @@ abstract class RenderBox extends RenderObject { final _DebugSize _size = this._size; assert(_size._owner == this); if (RenderObject.debugActiveLayout != null) { - // we are always allowed to access our own size (for print debugging and asserts if nothing else) - // other than us, the only object that's allowed to read our size is our parent, if they're said they will - // if you hit this assert trying to access a child's size, pass parentUsesSize: true in layout() + // We are always allowed to access our own size (for print debugging + // and asserts if nothing else). Other than us, the only object that's + // allowed to read our size is our parent, if they've said they will. + // If you hit this assert trying to access a child's size, pass + // "parentUsesSize: true" to that child's layout(). assert(debugDoingThisResize || debugDoingThisLayout || (RenderObject.debugActiveLayout == parent && _size._canBeUsedByParent)); } @@ -377,8 +393,12 @@ abstract class RenderBox extends RenderObject { assert((sizedByParent && debugDoingThisResize) || (!sizedByParent && debugDoingThisLayout)); assert(() { - if (value is _DebugSize) - return value._canBeUsedByParent && value._owner.parent == this; + if (value is _DebugSize) { + if (value._owner != this) { + assert(value._owner.parent == this); + assert(value._canBeUsedByParent); + } + } return true; }); _size = value; @@ -389,6 +409,11 @@ abstract class RenderBox extends RenderObject { assert(debugDoesMeetConstraints()); } + void debugResetSize() { + // updates the value of size._canBeUsedByParent if necessary + size = size; + } + Map _cachedBaselines; bool _ancestorUsesBaseline = false; static bool _debugDoingBaseline = false; @@ -473,7 +498,7 @@ abstract class RenderBox extends RenderObject { }); bool result = constraints.isSatisfiedBy(_size); if (!result) - print("${this.runtimeType} does not meet its constraints. Constraints: $constraints, size: $_size"); + debugPrint("${this.runtimeType} does not meet its constraints. Constraints: $constraints, size: $_size"); return result; } @@ -602,16 +627,16 @@ abstract class RenderBox extends RenderObject { debugPaintBaselines(context, offset); } void debugPaintSize(PaintingContext context, Offset offset) { - Paint paint = new Paint(); - paint.setStyle(ui.PaintingStyle.stroke); - paint.strokeWidth = 1.0; - paint.color = debugPaintSizeColor; + Paint paint = new Paint() + ..style = ui.PaintingStyle.stroke + ..strokeWidth = 1.0 + ..color = debugPaintSizeColor; context.canvas.drawRect(offset & size, paint); } void debugPaintBaselines(PaintingContext context, Offset offset) { - Paint paint = new Paint(); - paint.setStyle(ui.PaintingStyle.stroke); - paint.strokeWidth = 0.25; + Paint paint = new Paint() + ..style = ui.PaintingStyle.stroke + ..strokeWidth = 0.25; Path path; // ideographic baseline double baselineI = getDistanceToBaseline(TextBaseline.ideographic, onlyReal: true); @@ -712,3 +737,27 @@ abstract class RenderBoxContainerDefaultsMixin '$runtimeType($x, $y)'; +} diff --git a/packages/flutter/lib/src/rendering/debug.dart b/packages/flutter/lib/src/rendering/debug.dart index cf2df69323..403fd76933 100644 --- a/packages/flutter/lib/src/rendering/debug.dart +++ b/packages/flutter/lib/src/rendering/debug.dart @@ -3,6 +3,8 @@ // found in the LICENSE file. import 'dart:ui' as ui; +import 'dart:async'; +import 'dart:collection'; /// Causes each RenderBox to paint a box around its bounds. bool debugPaintSizeEnabled = false; @@ -30,3 +32,43 @@ bool debugPaintBoundsEnabled = false; /// The color to use when painting RenderError boxes in checked mode. ui.Color debugErrorBoxColor = const ui.Color(0xFFFF0000); + +/// Prints a message to the console, which you can access using the "flutter" +/// tool's "logs" command ("flutter logs"). +/// +/// This function very crudely attempts to throttle the rate at which messages +/// are sent to avoid data loss on Android. This means that interleaving calls +/// to this function (directly or indirectly via [debugDumpRenderTree] or +/// [debugDumpApp]) and to the Dart [print] method can result in out-of-order +/// messages in the logs. +void debugPrint(String message) { + _debugPrintBuffer.addAll(message.split('\n')); + if (!_debugPrintScheduled) + _debugPrintTask(); +} +int _debugPrintedCharacters = 0; +int _kDebugPrintCapacity = 16 * 1024; +Duration _kDebugPrintPauseTime = const Duration(seconds: 1); +Queue _debugPrintBuffer = new Queue(); +Stopwatch _debugPrintStopwatch = new Stopwatch(); +bool _debugPrintScheduled = false; +void _debugPrintTask() { + _debugPrintScheduled = false; + if (_debugPrintStopwatch.elapsed > _kDebugPrintPauseTime) { + _debugPrintStopwatch.stop(); + _debugPrintStopwatch.reset(); + _debugPrintedCharacters = 0; + } + while (_debugPrintedCharacters < _kDebugPrintCapacity && _debugPrintBuffer.length > 0) { + String line = _debugPrintBuffer.removeFirst(); + _debugPrintedCharacters += line.length; // TODO(ianh): Use the UTF-8 byte length instead + print(line); + } + if (_debugPrintBuffer.length > 0) { + _debugPrintScheduled = true; + _debugPrintedCharacters = 0; + new Timer(_kDebugPrintPauseTime, _debugPrintTask); + } else { + _debugPrintStopwatch.start(); + } +} diff --git a/packages/flutter/lib/src/rendering/image.dart b/packages/flutter/lib/src/rendering/image.dart index 3863cc0f22..079e4dfdf4 100644 --- a/packages/flutter/lib/src/rendering/image.dart +++ b/packages/flutter/lib/src/rendering/image.dart @@ -9,6 +9,10 @@ import 'package:flutter/painting.dart'; import 'box.dart'; import 'object.dart'; +export 'package:flutter/painting.dart' show + ImageFit, + ImageRepeat; + /// An image in the render tree. /// /// The render image attempts to find a size for itself that fits in the given @@ -18,7 +22,7 @@ class RenderImage extends RenderBox { ui.Image image, double width, double height, - ui.ColorFilter colorFilter, + ColorFilter colorFilter, ImageFit fit, repeat: ImageRepeat.noRepeat, Rect centerSlice @@ -63,9 +67,9 @@ class RenderImage extends RenderBox { } /// If non-null, apply this color filter to the image before painint. - ui.ColorFilter get colorFilter => _colorFilter; - ui.ColorFilter _colorFilter; - void set colorFilter (ui.ColorFilter value) { + ColorFilter get colorFilter => _colorFilter; + ColorFilter _colorFilter; + void set colorFilter (ColorFilter value) { if (value == _colorFilter) return; _colorFilter = value; diff --git a/packages/flutter/lib/src/rendering/layer.dart b/packages/flutter/lib/src/rendering/layer.dart index 0434fd8332..3da0d16087 100644 --- a/packages/flutter/lib/src/rendering/layer.dart +++ b/packages/flutter/lib/src/rendering/layer.dart @@ -3,10 +3,13 @@ // found in the LICENSE file. import 'dart:ui' as ui; -import 'dart:ui' show Point, Offset, Size, Rect, Color, Paint, Path; import 'package:vector_math/vector_math_64.dart'; +import 'basic_types.dart'; + +export 'basic_types.dart'; + /// A composited layer /// /// During painting, the render tree generates a tree of composited layers that @@ -304,29 +307,3 @@ class OpacityLayer extends ContainerLayer { builder.pop(); } } - -/// A composited layer that applies a color filter to its children -class ColorFilterLayer extends ContainerLayer { - ColorFilterLayer({ - Offset offset: Offset.zero, - this.bounds, - this.color, - this.transferMode - }) : super(offset: offset); - - /// Unused - Rect bounds; - // TODO(abarth): Remove. - - /// The color to use as input to the color filter - Color color; - - /// The transfer mode to use to combine [color] with the children's painting - ui.TransferMode transferMode; - - void addToScene(ui.SceneBuilder builder, Offset layerOffset) { - builder.pushColorFilter(color, transferMode, bounds.shift(offset)); - addChildrenToScene(builder, offset + layerOffset); - builder.pop(); - } -} diff --git a/packages/flutter/lib/src/rendering/object.dart b/packages/flutter/lib/src/rendering/object.dart index be74fec813..db6435636e 100644 --- a/packages/flutter/lib/src/rendering/object.dart +++ b/packages/flutter/lib/src/rendering/object.dart @@ -4,7 +4,6 @@ import 'dart:math' as math; import 'dart:ui' as ui; -import 'dart:ui' show Point, Offset, Size, Rect, Color, Paint, Path; import 'package:flutter/animation.dart'; import 'package:flutter/gestures.dart'; @@ -15,8 +14,8 @@ import 'hit_test.dart'; import 'layer.dart'; import 'node.dart'; -export 'dart:ui' show Point, Offset, Size, Rect, Color, Paint, Path; -export 'hit_test.dart' show HitTestTarget, HitTestEntry, HitTestResult; +export 'layer.dart'; +export 'hit_test.dart'; typedef ui.Shader ShaderCallback(Rect bounds); @@ -39,7 +38,7 @@ class ParentData { } /// Obsolete class that will be removed eventually -class PaintingCanvas extends ui.Canvas { +class PaintingCanvas extends Canvas { PaintingCanvas(ui.PictureRecorder recorder, Rect bounds) : super(recorder, bounds); // TODO(ianh): Just use ui.Canvas everywhere instead } @@ -247,7 +246,7 @@ class PaintingContext { static Paint _getPaintForAlpha(int alpha) { return new Paint() ..color = new Color.fromARGB(alpha, 0, 0, 0) - ..setTransferMode(ui.TransferMode.srcOver) + ..transferMode = TransferMode.srcOver ..isAntiAlias = false; } @@ -277,46 +276,9 @@ class PaintingContext { } } - static Paint _getPaintForColorFilter(Color color, ui.TransferMode transferMode) { - return new Paint() - ..colorFilter = new ui.ColorFilter.mode(color, transferMode) - ..isAntiAlias = false; - } - - /// Paint a child with a color filter - /// - /// The color filter is constructed by combining the given color and the given - /// transfer mode, as if they were passed to the [ColorFilter.mode] constructor. - /// - /// If the child needs compositing, the blending operation will be applied by - /// a compositing layer. Otherwise, the blending operation will be applied by - /// the canvas. - void paintChildWithColorFilter(RenderObject child, - Point childPosition, - Rect bounds, - Color color, - ui.TransferMode transferMode) { - assert(debugCanPaintChild(child)); - final Offset childOffset = childPosition.toOffset(); - if (!child.needsCompositing) { - canvas.saveLayer(bounds, _getPaintForColorFilter(color, transferMode)); - canvas.translate(childOffset.dx, childOffset.dy); - insertChild(child, Offset.zero); - canvas.restore(); - } else { - ColorFilterLayer paintLayer = new ColorFilterLayer( - offset: childOffset, - bounds: bounds, - color: color, - transferMode: transferMode); - _containerLayer.append(paintLayer); - compositeChild(child, parentLayer: paintLayer); - } - } - static Paint _getPaintForShaderMask(Rect bounds, ShaderCallback shaderCallback, - ui.TransferMode transferMode) { + TransferMode transferMode) { return new Paint() ..transferMode = transferMode ..shader = shaderCallback(bounds); @@ -326,7 +288,7 @@ class PaintingContext { Point childPosition, Rect bounds, ShaderCallback shaderCallback, - ui.TransferMode transferMode) { + TransferMode transferMode) { assert(debugCanPaintChild(child)); final Offset childOffset = childPosition.toOffset(); if (!child.needsCompositing) { @@ -514,14 +476,14 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget { dynamic debugExceptionContext = ''; void _debugReportException(String method, dynamic exception, StackTrace stack) { - print('-- EXCEPTION --'); - print('The following exception was raised during $method():'); - print('$exception'); - print('Stack trace:'); - print('$stack'); - print('The following RenderObject was being processed when the exception was fired:\n${this}'); + debugPrint('-- EXCEPTION --'); + debugPrint('The following exception was raised during $method():'); + debugPrint('$exception'); + debugPrint('Stack trace:'); + debugPrint('$stack'); + debugPrint('The following RenderObject was being processed when the exception was fired:\n${this}'); if (debugExceptionContext != '') - 'That RenderObject had the following exception context:\n$debugExceptionContext'.split('\n').forEach(print); + debugPrint('That RenderObject had the following exception context:\n$debugExceptionContext'); if (debugRenderingExceptionHandler != null) debugRenderingExceptionHandler(this, method, exception, stack); } @@ -724,15 +686,30 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget { else relayoutSubtreeRoot = parent._relayoutSubtreeRoot; assert(parent == this.parent); - if (!needsLayout && constraints == _constraints && relayoutSubtreeRoot == _relayoutSubtreeRoot) + assert(() { + _debugCanParentUseSize = parentUsesSize; + return true; + }); + if (!needsLayout && constraints == _constraints && relayoutSubtreeRoot == _relayoutSubtreeRoot) { + assert(() { + // in case parentUsesSize changed since the last invocation, set size + // to itself, so it has the right internal debug values. + _debugDoingThisLayout = true; + RenderObject debugPreviousActiveLayout = _debugActiveLayout; + _debugActiveLayout = this; + debugResetSize(); + _debugActiveLayout = debugPreviousActiveLayout; + _debugDoingThisLayout = false; + return true; + }); return; + } _constraints = constraints; _relayoutSubtreeRoot = relayoutSubtreeRoot; assert(!_debugMutationsLocked); assert(!_doingThisLayoutWithCallback); assert(() { _debugMutationsLocked = true; - _debugCanParentUseSize = parentUsesSize; return true; }); if (sizedByParent) { @@ -769,6 +746,14 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget { assert(parent == this.parent); } + /// If a subclass has a "size" (the state controlled by "parentUsesSize", + /// whatever it is in the subclass, e.g. the actual "size" property of + /// RenderBox), and the subclass verifies that in checked mode this "size" + /// property isn't used when debugCanParentUseSize isn't set, then that + /// subclass should override debugResetSize() to reapply the current values of + /// debugCanParentUseSize to that state. + void debugResetSize() { } + /// Whether the constraints are the only input to the sizing algorithm (in /// particular, child nodes have no impact) /// diff --git a/packages/flutter/lib/src/rendering/overflow.dart b/packages/flutter/lib/src/rendering/overflow.dart new file mode 100644 index 0000000000..24b3ec081b --- /dev/null +++ b/packages/flutter/lib/src/rendering/overflow.dart @@ -0,0 +1,237 @@ +// 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 'box.dart'; +import 'object.dart'; + +export 'package:flutter/src/painting/box_painter.dart'; + +/// A render object that imposes different constraints on its child than it gets +/// from its parent, possibly allowing the child to overflow the parent. +/// +/// A render overflow box proxies most functions in the render box protocol to +/// its child, except that when laying out its child, it passes constraints +/// based on the minWidth, maxWidth, minHeight, and maxHeight fields instead of +/// just passing the parent's constraints in. Specifically, it overrides any of +/// the equivalent fields on the constraints given by the parent with the +/// constraints given by these fields for each such field that is not null. It +/// then sizes itself based on the parent's constraints' maxWidth and maxHeight, +/// ignoring the child's dimensions. +/// +/// For example, if you wanted a box to always render 50 pixels high, regardless +/// of where it was rendered, you would wrap it in a RenderOverflow with +/// minHeight and maxHeight set to 50.0. Generally speaking, to avoid confusing +/// behaviour around hit testing, a RenderOverflowBox should usually be wrapped +/// in a RenderClipRect. +/// +/// The child is positioned at the top left of the box. To position a smaller +/// child inside a larger parent, use [RenderPositionedBox] and +/// [RenderConstrainedBox] rather than RenderOverflowBox. +class RenderOverflowBox extends RenderBox with RenderObjectWithChildMixin { + RenderOverflowBox({ + RenderBox child, + double minWidth, + double maxWidth, + double minHeight, + double maxHeight + }) : _minWidth = minWidth, _maxWidth = maxWidth, _minHeight = minHeight, _maxHeight = maxHeight { + this.child = child; + } + + /// The minimum width constraint to give the child. Set this to null (the + /// default) to use the constraint from the parent instead. + double get minWidth => _minWidth; + double _minWidth; + void set minWidth (double value) { + if (_minWidth == value) + return; + _minWidth = value; + markNeedsLayout(); + } + + /// The maximum width constraint to give the child. Set this to null (the + /// default) to use the constraint from the parent instead. + double get maxWidth => _maxWidth; + double _maxWidth; + void set maxWidth (double value) { + if (_maxWidth == value) + return; + _maxWidth = value; + markNeedsLayout(); + } + + /// The minimum height constraint to give the child. Set this to null (the + /// default) to use the constraint from the parent instead. + double get minHeight => _minHeight; + double _minHeight; + void set minHeight (double value) { + if (_minHeight == value) + return; + _minHeight = value; + markNeedsLayout(); + } + + /// The maximum height constraint to give the child. Set this to null (the + /// default) to use the constraint from the parent instead. + double get maxHeight => _maxHeight; + double _maxHeight; + void set maxHeight (double value) { + if (_maxHeight == value) + return; + _maxHeight = value; + markNeedsLayout(); + } + + BoxConstraints _getInnerConstraints(BoxConstraints constraints) { + return new BoxConstraints( + minWidth: _minWidth ?? constraints.minWidth, + maxWidth: _maxWidth ?? constraints.maxWidth, + minHeight: _minHeight ?? constraints.minHeight, + maxHeight: _maxHeight ?? constraints.maxHeight + ); + } + + double getMinIntrinsicWidth(BoxConstraints constraints) { + return constraints.constrainWidth(); + } + + double getMaxIntrinsicWidth(BoxConstraints constraints) { + return constraints.constrainWidth(); + } + + double getMinIntrinsicHeight(BoxConstraints constraints) { + return constraints.constrainHeight(); + } + + double getMaxIntrinsicHeight(BoxConstraints constraints) { + return constraints.constrainHeight(); + } + + double computeDistanceToActualBaseline(TextBaseline baseline) { + if (child != null) + return child.getDistanceToActualBaseline(baseline); + return super.computeDistanceToActualBaseline(baseline); + } + + bool get sizedByParent => true; + + void performResize() { + size = constraints.biggest; + } + + void performLayout() { + if (child != null) + child.layout(_getInnerConstraints(constraints)); + } + + void hitTestChildren(HitTestResult result, { Point position }) { + if (child != null) + child.hitTest(result, position: position); + else + super.hitTestChildren(result, position: position); + } + + void paint(PaintingContext context, Offset offset) { + if (child != null) + context.paintChild(child, offset.toPoint()); + } + + String debugDescribeSettings(String prefix) { + return '${super.debugDescribeSettings(prefix)}' + + '${prefix}minWidth: ${minWidth ?? "use parent minWidth constraint"}\n' + + '${prefix}maxWidth: ${maxWidth ?? "use parent maxWidth constraint"}\n' + + '${prefix}minHeight: ${minHeight ?? "use parent minHeight constraint"}\n' + + '${prefix}maxHeight: ${maxHeight ?? "use parent maxHeight constraint"}\n'; + } +} + +/// A render box that's a specific size but passes its original constraints through to its child, which will probably overflow +class RenderSizedOverflowBox extends RenderBox with RenderObjectWithChildMixin { + RenderSizedOverflowBox({ + RenderBox child, + Size requestedSize + }) : _requestedSize = requestedSize { + assert(requestedSize != null); + this.child = child; + } + + /// The size this render box should attempt to be. + Size get requestedSize => _requestedSize; + Size _requestedSize; + void set requestedSize (Size value) { + assert(value != null); + if (_requestedSize == value) + return; + _requestedSize = value; + markNeedsLayout(); + } + + double getMinIntrinsicWidth(BoxConstraints constraints) { + return constraints.constrainWidth(_requestedSize.width); + } + + double getMaxIntrinsicWidth(BoxConstraints constraints) { + return constraints.constrainWidth(_requestedSize.width); + } + + double getMinIntrinsicHeight(BoxConstraints constraints) { + return constraints.constrainWidth(_requestedSize.height); + } + + double getMaxIntrinsicHeight(BoxConstraints constraints) { + return constraints.constrainWidth(_requestedSize.height); + } + + double computeDistanceToActualBaseline(TextBaseline baseline) { + if (child != null) + return child.getDistanceToActualBaseline(baseline); + return super.computeDistanceToActualBaseline(baseline); + } + + void performLayout() { + size = constraints.constrain(_requestedSize); + if (child != null) + child.layout(constraints); + } + + void hitTestChildren(HitTestResult result, { Point position }) { + if (child != null) + child.hitTest(result, position: position); + else + super.hitTestChildren(result, position: position); + } + + void paint(PaintingContext context, Offset offset) { + if (child != null) + context.paintChild(child, offset.toPoint()); + } +} + +/// Lays the child out as if it was in the tree, but without painting anything, +/// without making the child available for hit testing, and without taking any +/// room in the parent. +class RenderOffStage extends RenderBox with RenderObjectWithChildMixin { + RenderOffStage({ RenderBox child }) { + this.child = child; + } + + double getMinIntrinsicWidth(BoxConstraints constraints) => constraints.minWidth; + double getMaxIntrinsicWidth(BoxConstraints constraints) => constraints.minWidth; + double getMinIntrinsicHeight(BoxConstraints constraints) => constraints.minHeight; + double getMaxIntrinsicHeight(BoxConstraints constraints) => constraints.minHeight; + + bool get sizedByParent => true; + + void performResize() { + size = constraints.smallest; + } + + void performLayout() { + if (child != null) + child.layout(constraints); + } + + bool hitTest(HitTestResult result, { Point position }) => false; + void paint(PaintingContext context, Offset offset) { } +} diff --git a/packages/flutter/lib/src/rendering/paragraph.dart b/packages/flutter/lib/src/rendering/paragraph.dart index 67bbfc0baa..b12309eb7d 100644 --- a/packages/flutter/lib/src/rendering/paragraph.dart +++ b/packages/flutter/lib/src/rendering/paragraph.dart @@ -7,7 +7,22 @@ import 'package:flutter/painting.dart'; import 'box.dart'; import 'object.dart'; -export 'package:flutter/src/painting/text_painter.dart'; +export 'package:flutter/painting.dart' show + FontStyle, + FontWeight, + PlainTextSpan, + StyledTextSpan, + TextAlign, + TextBaseline, + TextDecoration, + TextDecorationStyle, + TextSpan, + TextStyle, + normal, + bold, + underline, + overline, + lineThrough; /// A render object that displays a paragraph of text class RenderParagraph extends RenderBox { diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index 5dffe9a5cf..1b50c2b4a9 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -12,6 +12,7 @@ import 'box.dart'; import 'object.dart'; export 'package:flutter/src/painting/box_painter.dart'; +export 'package:flutter/gestures.dart' show InputEvent, PointerInputEvent; /// A base class for render objects that resemble their children /// @@ -189,7 +190,7 @@ class RenderFractionallySizedBox extends RenderProxyBox { markNeedsLayout(); } - BoxConstraints _computeChildConstraints(BoxConstraints constraints) { + BoxConstraints _getInnerConstraints(BoxConstraints constraints) { return new BoxConstraints( minWidth: _widthFactor == null ? constraints.minWidth : constraints.maxWidth * _widthFactor, maxWidth: _widthFactor == null ? constraints.maxWidth : constraints.maxWidth * _widthFactor, @@ -200,34 +201,34 @@ class RenderFractionallySizedBox extends RenderProxyBox { double getMinIntrinsicWidth(BoxConstraints constraints) { if (child != null) - return child.getMinIntrinsicWidth(_computeChildConstraints(constraints)); - return _computeChildConstraints(constraints).constrainWidth(0.0); + return child.getMinIntrinsicWidth(_getInnerConstraints(constraints)); + return _getInnerConstraints(constraints).constrainWidth(0.0); } double getMaxIntrinsicWidth(BoxConstraints constraints) { if (child != null) - return child.getMaxIntrinsicWidth(_computeChildConstraints(constraints)); - return _computeChildConstraints(constraints).constrainWidth(0.0); + return child.getMaxIntrinsicWidth(_getInnerConstraints(constraints)); + return _getInnerConstraints(constraints).constrainWidth(0.0); } double getMinIntrinsicHeight(BoxConstraints constraints) { if (child != null) - return child.getMinIntrinsicHeight(_computeChildConstraints(constraints)); - return _computeChildConstraints(constraints).constrainHeight(0.0); + return child.getMinIntrinsicHeight(_getInnerConstraints(constraints)); + return _getInnerConstraints(constraints).constrainHeight(0.0); } double getMaxIntrinsicHeight(BoxConstraints constraints) { if (child != null) - return child.getMaxIntrinsicHeight(_computeChildConstraints(constraints)); - return _computeChildConstraints(constraints).constrainHeight(0.0); + return child.getMaxIntrinsicHeight(_getInnerConstraints(constraints)); + return _getInnerConstraints(constraints).constrainHeight(0.0); } void performLayout() { if (child != null) { - child.layout(_computeChildConstraints(constraints), parentUsesSize: true); + child.layout(_getInnerConstraints(constraints), parentUsesSize: true); size = child.size; } else { - size = _computeChildConstraints(constraints).constrain(Size.zero); + size = _getInnerConstraints(constraints).constrain(Size.zero); } } @@ -238,125 +239,6 @@ class RenderFractionallySizedBox extends RenderProxyBox { } } -/// A render object that imposes different constraints on its child than it gets -/// from its parent, possibly allowing the child to overflow the parent. -/// -/// A render overflow box proxies most functions in the render box protocol to -/// its child, except that when laying out its child, it passes constraints -/// based on the minWidth, maxWidth, minHeight, and maxHeight fields instead of -/// just passing the parent's constraints in. Specifically, it overrides any of -/// the equivalent fields on the constraints given by the parent with the -/// constraints given by these fields for each such field that is not null. It -/// then sizes itself based on the parent's constraints' maxWidth and maxHeight, -/// ignoring the child's dimensions. -/// -/// For example, if you wanted a box to always render 50 pixels high, regardless -/// of where it was rendered, you would wrap it in a RenderOverflow with -/// minHeight and maxHeight set to 50.0. Generally speaking, to avoid confusing -/// behaviour around hit testing, a RenderOverflowBox should usually be wrapped -/// in a RenderClipRect. -/// -/// The child is positioned at the top left of the box. To position a smaller -/// child inside a larger parent, use [RenderPositionedBox] and -/// [RenderConstrainedBox] rather than RenderOverflowBox. -class RenderOverflowBox extends RenderProxyBox { - RenderOverflowBox({ - RenderBox child, - double minWidth, - double maxWidth, - double minHeight, - double maxHeight - }) : _minWidth = minWidth, _maxWidth = maxWidth, _minHeight = minHeight, _maxHeight = maxHeight, super(child); - - /// The minimum width constraint to give the child. Set this to null (the - /// default) to use the constraint from the parent instead. - double get minWidth => _minWidth; - double _minWidth; - void set minWidth (double value) { - if (_minWidth == value) - return; - _minWidth = value; - markNeedsLayout(); - } - - /// The maximum width constraint to give the child. Set this to null (the - /// default) to use the constraint from the parent instead. - double get maxWidth => _maxWidth; - double _maxWidth; - void set maxWidth (double value) { - if (_maxWidth == value) - return; - _maxWidth = value; - markNeedsLayout(); - } - - /// The minimum height constraint to give the child. Set this to null (the - /// default) to use the constraint from the parent instead. - double get minHeight => _minHeight; - double _minHeight; - void set minHeight (double value) { - if (_minHeight == value) - return; - _minHeight = value; - markNeedsLayout(); - } - - /// The maximum height constraint to give the child. Set this to null (the - /// default) to use the constraint from the parent instead. - double get maxHeight => _maxHeight; - double _maxHeight; - void set maxHeight (double value) { - if (_maxHeight == value) - return; - _maxHeight = value; - markNeedsLayout(); - } - - BoxConstraints childConstraints(BoxConstraints constraints) { - return new BoxConstraints( - minWidth: _minWidth ?? constraints.minWidth, - maxWidth: _maxWidth ?? constraints.maxWidth, - minHeight: _minHeight ?? constraints.minHeight, - maxHeight: _maxHeight ?? constraints.maxHeight - ); - } - - double getMinIntrinsicWidth(BoxConstraints constraints) { - return constraints.constrainWidth(); - } - - double getMaxIntrinsicWidth(BoxConstraints constraints) { - return constraints.constrainWidth(); - } - - double getMinIntrinsicHeight(BoxConstraints constraints) { - return constraints.constrainHeight(); - } - - double getMaxIntrinsicHeight(BoxConstraints constraints) { - return constraints.constrainHeight(); - } - - bool get sizedByParent => true; - - void performResize() { - size = constraints.biggest; - } - - void performLayout() { - if (child != null) - child.layout(childConstraints(constraints)); - } - - String debugDescribeSettings(String prefix) { - return '${super.debugDescribeSettings(prefix)}' + - '${prefix}minWidth: ${minWidth ?? "use parent minWidth constraint"}\n' + - '${prefix}maxWidth: ${maxWidth ?? "use parent maxWidth constraint"}\n' + - '${prefix}minHeight: ${minHeight ?? "use parent minHeight constraint"}\n' + - '${prefix}maxHeight: ${maxHeight ?? "use parent maxHeight constraint"}\n'; - } -} - /// Forces child to layout at a specific aspect ratio /// /// The width of this render object is the largest width permited by the layout @@ -620,47 +502,8 @@ class RenderOpacity extends RenderProxyBox { } } -/// Applies a color filter when painting its child -/// -/// This class paints its child into an intermediate buffer and then blends the -/// child back into the scene using a color filter. -/// -/// Note: This class is relatively expensive because it requires painting the -/// child into an intermediate buffer. -class RenderColorFilter extends RenderProxyBox { - RenderColorFilter({ RenderBox child, Color color, ui.TransferMode transferMode }) - : _color = color, _transferMode = transferMode, super(child); - - /// The color to use as input to the color filter - Color get color => _color; - Color _color; - void set color (Color newColor) { - assert(newColor != null); - if (_color == newColor) - return; - _color = newColor; - markNeedsPaint(); - } - - /// The transfer mode to use when combining the child's painting and the [color] - ui.TransferMode get transferMode => _transferMode; - ui.TransferMode _transferMode; - void set transferMode (ui.TransferMode newTransferMode) { - assert(newTransferMode != null); - if (_transferMode == newTransferMode) - return; - _transferMode = newTransferMode; - markNeedsPaint(); - } - - void paint(PaintingContext context, Offset offset) { - if (child != null) - context.paintChildWithColorFilter(child, offset.toPoint(), offset & size, _color, _transferMode); - } -} - class RenderShaderMask extends RenderProxyBox { - RenderShaderMask({ RenderBox child, ShaderCallback shaderCallback, ui.TransferMode transferMode }) + RenderShaderMask({ RenderBox child, ShaderCallback shaderCallback, TransferMode transferMode }) : _shaderCallback = shaderCallback, _transferMode = transferMode, super(child); ShaderCallback get shaderCallback => _shaderCallback; @@ -673,9 +516,9 @@ class RenderShaderMask extends RenderProxyBox { markNeedsPaint(); } - ui.TransferMode get transferMode => _transferMode; - ui.TransferMode _transferMode; - void set transferMode (ui.TransferMode newTransferMode) { + TransferMode get transferMode => _transferMode; + TransferMode _transferMode; + void set transferMode (TransferMode newTransferMode) { assert(newTransferMode != null); if (_transferMode == newTransferMode) return; @@ -862,30 +705,6 @@ class RenderDecoratedBox extends RenderProxyBox { String debugDescribeSettings(String prefix) => '${super.debugDescribeSettings(prefix)}${prefix}decoration:\n${_painter.decoration.toString(prefix + " ")}\n'; } -/// An offset that's expressed as a fraction of a Size. -/// -/// FractionalOffset(0.0, 0.0) represents the top left of the Size, -/// FractionalOffset(1.0, 1.0) represents the bottom right of the Size. -class FractionalOffset { - const FractionalOffset(this.x, this.y); - final double x; - final double y; - bool operator ==(dynamic other) { - if (other is! FractionalOffset) - return false; - final FractionalOffset typedOther = other; - return x == typedOther.x && - y == typedOther.y; - } - int get hashCode { - int value = 373; - value = 37 * value + x.hashCode; - value = 37 * value + y.hashCode; - return value; - } - String toString() => '$runtimeType($x, $y)'; -} - /// Applies a transformation before painting its child class RenderTransform extends RenderProxyBox { RenderTransform({ @@ -1017,40 +836,44 @@ class RenderTransform extends RenderProxyBox { String debugDescribeSettings(String prefix) { List result = _transform.toString().split('\n').map((String s) => '$prefix $s\n').toList(); result.removeLast(); - return '${super.debugDescribeSettings(prefix)}${prefix}transform matrix:\n${result.join()}\n${prefix}origin: $origin\nalignment: $alignment\n'; + return '${super.debugDescribeSettings(prefix)}${prefix}transform matrix:\n${result.join()}\n${prefix}origin: $origin\n${prefix}alignment: $alignment\n'; } } /// Called when a size changes typedef void SizeChangedCallback(Size newSize); -/// Calls [callback] whenever the child's layout size changes +/// Calls [onSizeChanged] whenever the child's layout size changes /// /// Note: Size observer calls its callback during layout, which means you cannot /// dirty layout information during the callback. class RenderSizeObserver extends RenderProxyBox { RenderSizeObserver({ - this.callback, + this.onSizeChanged, RenderBox child }) : super(child) { - assert(callback != null); + assert(onSizeChanged != null); } /// The callback to call whenever the child's layout size changes - SizeChangedCallback callback; + SizeChangedCallback onSizeChanged; void performLayout() { Size oldSize = hasSize ? size : null; super.performLayout(); - if (oldSize != size) - callback(size); + if (oldSize != size) { + // We make a copy of the Size object here because if we leak a _DebugSize + // object out of the render tree, we can get confused later if it comes + // back and gets set as the size property of a RenderBox. + onSizeChanged(new Size(size.width, size.height)); + } } } /// Called when its time to paint into the given canvas typedef void CustomPaintCallback(PaintingCanvas canvas, Size size); -/// Delegates its painting to [callback] +/// Delegates its painting to [onPaint] /// /// When asked to paint, custom paint first calls its callback with the current /// canvas and then paints its children. The coodinate system of the canvas @@ -1065,36 +888,36 @@ typedef void CustomPaintCallback(PaintingCanvas canvas, Size size); class RenderCustomPaint extends RenderProxyBox { RenderCustomPaint({ - CustomPaintCallback callback, + CustomPaintCallback onPaint, RenderBox child }) : super(child) { - assert(callback != null); - _callback = callback; + assert(onPaint != null); + _onPaint = onPaint; } /// The callback to which this render object delegates its painting /// /// The callback must be non-null whenever the render object is attached to /// the render tree. - CustomPaintCallback get callback => _callback; - CustomPaintCallback _callback; - void set callback (CustomPaintCallback newCallback) { + CustomPaintCallback get onPaint => _onPaint; + CustomPaintCallback _onPaint; + void set onPaint (CustomPaintCallback newCallback) { assert(newCallback != null || !attached); - if (_callback == newCallback) + if (_onPaint == newCallback) return; - _callback = newCallback; + _onPaint = newCallback; markNeedsPaint(); } void attach() { - assert(_callback != null); + assert(_onPaint != null); super.attach(); } void paint(PaintingContext context, Offset offset) { - assert(_callback != null); + assert(_onPaint != null); context.canvas.translate(offset.dx, offset.dy); - _callback(context.canvas, size); + _onPaint(context.canvas, size); // TODO(abarth): We should translate back before calling super because in // the future, super.paint might switch our compositing layer. super.paint(context, Offset.zero); diff --git a/packages/flutter/lib/src/rendering/shifted_box.dart b/packages/flutter/lib/src/rendering/shifted_box.dart index 89eacfb5ce..581fbbdbec 100644 --- a/packages/flutter/lib/src/rendering/shifted_box.dart +++ b/packages/flutter/lib/src/rendering/shifted_box.dart @@ -155,35 +155,22 @@ class RenderPositionedBox extends RenderShiftedBox { RenderPositionedBox({ RenderBox child, - double horizontal: 0.5, - double vertical: 0.5, + FractionalOffset alignment: const FractionalOffset(0.5, 0.5), ShrinkWrap shrinkWrap: ShrinkWrap.none - }) : _horizontal = horizontal, - _vertical = vertical, + }) : _alignment = alignment, _shrinkWrap = shrinkWrap, super(child) { - assert(horizontal != null); - assert(vertical != null); + assert(alignment != null); assert(shrinkWrap != null); } - double _horizontal; - double get horizontal => _horizontal; - void set horizontal (double value) { - assert(value != null); - if (_horizontal == value) + FractionalOffset get alignment => _alignment; + FractionalOffset _alignment; + void set alignment (FractionalOffset newAlignment) { + assert(newAlignment == null || (newAlignment.x != null && newAlignment.y != null)); + if (_alignment == newAlignment) return; - _horizontal = value; - markNeedsLayout(); - } - - double _vertical; - double get vertical => _vertical; - void set vertical (double value) { - assert(value != null); - if (_vertical == value) - return; - _vertical = value; + _alignment = newAlignment; markNeedsLayout(); } @@ -208,14 +195,14 @@ class RenderPositionedBox extends RenderShiftedBox { _shinkWrapHeight ? child.size.height : double.INFINITY)); Offset delta = size - child.size; final BoxParentData childParentData = child.parentData; - childParentData.position = (delta.scale(horizontal, vertical)).toPoint(); + childParentData.position = (delta.scale(_alignment.x, _alignment.y)).toPoint(); } else { size = constraints.constrain(new Size(_shinkWrapWidth ? 0.0 : double.INFINITY, _shinkWrapHeight ? 0.0 : double.INFINITY)); } } - String debugDescribeSettings(String prefix) => '${super.debugDescribeSettings(prefix)}${prefix}horizontal: $horizontal\n${prefix}vertical: $vertical\n'; + String debugDescribeSettings(String prefix) => '${super.debugDescribeSettings(prefix)}${prefix}alignment: $alignment\n'; } class RenderBaseline extends RenderShiftedBox { diff --git a/packages/flutter/lib/src/rendering/stack.dart b/packages/flutter/lib/src/rendering/stack.dart index 2382411e69..54b329b41b 100644 --- a/packages/flutter/lib/src/rendering/stack.dart +++ b/packages/flutter/lib/src/rendering/stack.dart @@ -3,10 +3,138 @@ // found in the LICENSE file. import 'dart:math' as math; +import 'dart:ui' show lerpDouble; import 'box.dart'; import 'object.dart'; +/// An immutable 2D, axis-aligned, floating-point rectangle whose coordinates +/// are given relative to another rectangle's edges, known as the container. +/// Since the dimensions of the rectangle are relative to those of the +/// container, this class has no width and height members. To determine the +/// width or height of the rectangle, convert it to a [Rect] using [toRect()] +/// (passing the container's own Rect), and then examine that object. +class RelativeRect { + + /// Creates a RelativeRect with the given values. + const RelativeRect.fromLTRB(this.left, this.top, this.right, this.bottom); + + /// Creates a RelativeRect from a Rect and a Size. The Rect (first argument) + /// and the RelativeRect (the output) are in the coordinate space of the + /// rectangle described by the Size, with 0,0 being at the top left. + factory RelativeRect.fromSize(Rect rect, Size container) { + return new RelativeRect.fromLTRB(rect.left, rect.top, container.width - rect.right, container.height - rect.bottom); + } + + /// Creates a RelativeRect from two Rects. The second Rect provides the + /// container, the first provides the rectangle, in the same coordinate space, + /// that is to be converted to a RelativeRect. The output will be in the + /// container's coordinate space. + /// + /// For example, if the top left of the rect is at 0,0, and the top left of + /// the container is at 100,100, then the top left of the output will be at + /// -100,-100. + /// + /// If the first rect is actually in the container's coordinate space, then + /// use [RelativeRect.fromSize] and pass the container's size as the second + /// argument instead. + factory RelativeRect.fromRect(Rect rect, Rect container) { + return new RelativeRect.fromLTRB( + rect.left - container.left, + rect.top - container.top, + container.right - rect.right, + container.bottom - rect.bottom + ); + } + + static final RelativeRect fill = new RelativeRect.fromLTRB(0.0, 0.0, 0.0, 0.0); + + /// Distance from the left side of the container to the left side of this rectangle. + final double left; + + /// Distance from the top side of the container to the top side of this rectangle. + final double top; + + /// Distance from the right side of the container to the right side of this rectangle. + final double right; + + /// Distance from the bottom side of the container to the bottom side of this rectangle. + final double bottom; + + /// Returns a new rectangle object translated by the given offset. + RelativeRect shift(Offset offset) { + return new RelativeRect.fromLTRB(left + offset.dx, top + offset.dy, right + offset.dx, bottom + offset.dy); + } + + /// Returns a new rectangle with edges moved outwards by the given delta. + RelativeRect inflate(double delta) { + return new RelativeRect.fromLTRB(left - delta, top - delta, right + delta, bottom + delta); + } + + /// Returns a new rectangle with edges moved inwards by the given delta. + RelativeRect deflate(double delta) { + return inflate(-delta); + } + + /// Returns a new rectangle that is the intersection of the given rectangle and this rectangle. + RelativeRect intersect(RelativeRect other) { + return new RelativeRect.fromLTRB( + math.max(left, other.left), + math.max(top, other.top), + math.max(right, other.right), + math.max(bottom, other.bottom) + ); + } + + /// Convert this RelativeRect to a Rect, in the coordinate space of the container. + Rect toRect(Rect container) { + return new Rect.fromLTRB(left, top, container.width - right, container.height - bottom); + } + + /// Linearly interpolate between two RelativeRects. + /// + /// If either rect is null, this function interpolates from [RelativeRect.fill]. + static RelativeRect lerp(RelativeRect a, RelativeRect b, double t) { + if (a == null && b == null) + return null; + if (a == null) + return new RelativeRect.fromLTRB(b.left * t, b.top * t, b.right * t, b.bottom * t); + if (b == null) { + double k = 1.0 - t; + return new RelativeRect.fromLTRB(b.left * k, b.top * k, b.right * k, b.bottom * k); + } + return new RelativeRect.fromLTRB( + lerpDouble(a.left, b.left, t), + lerpDouble(a.top, b.top, t), + lerpDouble(a.right, b.right, t), + lerpDouble(a.bottom, b.bottom, t) + ); + } + + bool operator ==(dynamic other) { + if (identical(this, other)) + return true; + if (other is! RelativeRect) + return false; + final RelativeRect typedOther = other; + return left == typedOther.left && + top == typedOther.top && + right == typedOther.right && + bottom == typedOther.bottom; + } + + int get hashCode { + int value = 373; + value = 37 * value + left.hashCode; + value = 37 * value + top.hashCode; + value = 37 * value + right.hashCode; + value = 37 * value + bottom.hashCode; + return value; + } + + String toString() => "RelativeRect.fromLTRB(${left.toStringAsFixed(1)}, ${top.toStringAsFixed(1)}, ${right.toStringAsFixed(1)}, ${bottom.toStringAsFixed(1)})"; +} + /// Parent data for use with [RenderStack] class StackParentData extends ContainerBoxParentDataMixin { /// The offset of the child's top edge from the top of the stack @@ -21,6 +149,15 @@ class StackParentData extends ContainerBoxParentDataMixin { /// The offset of the child's left edge from the left of the stack double left; + /// Get or set the current values in terms of a RelativeRect object. + RelativeRect get rect => new RelativeRect.fromLTRB(left, top, right, bottom); + void set rect(RelativeRect value) { + left = value.left; + top = value.top; + right = value.right; + bottom = value.bottom; + } + void merge(StackParentData other) { if (other.top != null) top = other.top; diff --git a/packages/flutter/lib/src/rendering/toggleable.dart b/packages/flutter/lib/src/rendering/toggleable.dart index f6e7879993..658f65d71d 100644 --- a/packages/flutter/lib/src/rendering/toggleable.dart +++ b/packages/flutter/lib/src/rendering/toggleable.dart @@ -24,7 +24,7 @@ abstract class RenderToggleable extends RenderConstrainedBox { _onChanged = onChanged, super(additionalConstraints: new BoxConstraints.tight(size)) { _performance = new ValuePerformance( - variable: new AnimatedValue(0.0, end: 1.0, curve: easeIn, reverseCurve: easeOut), + variable: new AnimatedValue(0.0, end: 1.0, curve: Curves.easeIn, reverseCurve: Curves.easeOut), duration: _kToggleDuration, progress: _value ? 1.0 : 0.0 )..addListener(markNeedsPaint); diff --git a/packages/flutter/lib/src/rendering/view.dart b/packages/flutter/lib/src/rendering/view.dart index 7b0d3548ef..a9b739bc83 100644 --- a/packages/flutter/lib/src/rendering/view.dart +++ b/packages/flutter/lib/src/rendering/view.dart @@ -23,6 +23,8 @@ class ViewConstraints { /// The orientation of the output surface (aspirational) final int orientation; + + String toString() => '$size'; } /// The root of the render tree @@ -53,7 +55,7 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin ViewConstraints get rootConstraints => _rootConstraints; ViewConstraints _rootConstraints; void set rootConstraints(ViewConstraints value) { - if (_rootConstraints == value) + if (rootConstraints == value) return; _rootConstraints = value; markNeedsLayout(); @@ -80,12 +82,12 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin } void performLayout() { - if (_rootConstraints.orientation != _orientation) { + if (rootConstraints.orientation != _orientation) { if (_orientation != null && child != null) - child.rotate(oldAngle: _orientation, newAngle: _rootConstraints.orientation, time: timeForRotation); - _orientation = _rootConstraints.orientation; + child.rotate(oldAngle: _orientation, newAngle: rootConstraints.orientation, time: timeForRotation); + _orientation = rootConstraints.orientation; } - _size = _rootConstraints.size; + _size = rootConstraints.size; assert(!_size.isInfinite); if (child != null) @@ -127,4 +129,7 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin } Rect get paintBounds => Point.origin & size; + + String debugDescribeSettings(String prefix) => '${prefix}view width: ${ui.view.width} (in device pixels)\n${prefix}view height: ${ui.view.height} (in device pixels)\n${prefix}device pixel ratio: ${ui.view.devicePixelRatio} (device pixels per logical pixel)\n${prefix}root constraints: $rootConstraints (in logical pixels)\n'; + // call to ${super.debugDescribeSettings(prefix)} is omitted because the root superclasses don't include any interesting information for this class } diff --git a/packages/flutter/lib/src/rendering/viewport.dart b/packages/flutter/lib/src/rendering/viewport.dart index be961ea7fb..a447779867 100644 --- a/packages/flutter/lib/src/rendering/viewport.dart +++ b/packages/flutter/lib/src/rendering/viewport.dart @@ -32,7 +32,7 @@ class RenderViewport extends RenderBox with RenderObjectWithChildMixin fetch(UrlRequest request) async { + UrlLoaderProxy loader = new UrlLoaderProxy.unbound(); try { - UrlLoaderProxy loader = new UrlLoaderProxy.unbound(); _networkService.ptr.createUrlLoader(loader); UrlResponse response = (await loader.ptr.start(request)).response; - loader.close(); return response; } catch (e) { print("NetworkService unavailable $e"); return new UrlResponse()..statusCode = 500; + } finally { + loader.close(); } } -Future fetchUrl(String relativeUrl) async { +Future fetchUrl(String relativeUrl) { String url = Uri.base.resolve(relativeUrl).toString(); UrlRequest request = new UrlRequest() ..url = url ..autoFollowRedirects = true; - return await fetch(request); + return fetch(request); } Future fetchBody(String relativeUrl) async { diff --git a/packages/flutter/lib/src/widgets/animated_container.dart b/packages/flutter/lib/src/widgets/animated_container.dart index 307fdd431f..8a1831b457 100644 --- a/packages/flutter/lib/src/widgets/animated_container.dart +++ b/packages/flutter/lib/src/widgets/animated_container.dart @@ -56,7 +56,7 @@ class AnimatedContainer extends StatefulComponent { this.transform, this.width, this.height, - this.curve: linear, + this.curve: Curves.linear, this.duration }) : super(key: key) { assert(margin == null || margin.isNonNegative); @@ -66,6 +66,7 @@ class AnimatedContainer extends StatefulComponent { } final Widget child; + final BoxConstraints constraints; final BoxDecoration decoration; final BoxDecoration foregroundDecoration; @@ -95,7 +96,7 @@ class _AnimatedContainerState extends State { void initState() { super.initState(); - _performance = new Performance(duration: config.duration) + _performance = new Performance(duration: config.duration, debugLabel: '${config.toStringShort()}') ..timing = new AnimationTiming(curve: config.curve) ..addListener(_updateAllVariables); _configAllVariables(); @@ -123,7 +124,6 @@ class _AnimatedContainerState extends State { void _updateAllVariables() { setState(() { - _updateVariable(_constraints); _updateVariable(_constraints); _updateVariable(_decoration); _updateVariable(_foregroundDecoration); @@ -224,4 +224,24 @@ class _AnimatedContainerState extends State { height: _height?.value ); } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + if (_constraints != null) + description.add('has constraints'); + if (_decoration != null) + description.add('has background'); + if (_foregroundDecoration != null) + description.add('has foreground'); + if (_margin != null) + description.add('has margin'); + if (_padding != null) + description.add('has padding'); + if (_transform != null) + description.add('has transform'); + if (_width != null) + description.add('has width'); + if (_height != null) + description.add('has height'); + } } diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index 1ef3bd88f4..c9ed90652a 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -18,23 +18,48 @@ export 'package:flutter/rendering.dart' show BoxDecoration, BoxDecorationPosition, BoxShadow, + Canvas, Color, + ColorFilter, EdgeDims, FlexAlignItems, FlexDirection, FlexJustifyContent, + FontStyle, + FontWeight, FractionalOffset, + Gradient, + ImageFit, + ImageRepeat, + InputEvent, + LinearGradient, Matrix4, Offset, Paint, Path, + PlainTextSpan, Point, + PointerInputEvent, + RadialGradient, Rect, ScrollDirection, Shape, ShrinkWrap, Size, - ValueChanged; + StyledTextSpan, + TextAlign, + TextBaseline, + TextDecoration, + TextDecorationStyle, + TextSpan, + TextStyle, + TransferMode, + ValueChanged, + normal, + bold, + underline, + overline, + lineThrough; // PAINTING NODES @@ -52,23 +77,10 @@ class Opacity extends OneChildRenderObjectWidget { void updateRenderObject(RenderOpacity renderObject, Opacity oldWidget) { renderObject.opacity = opacity; } -} -class ColorFilter extends OneChildRenderObjectWidget { - ColorFilter({ Key key, this.color, this.transferMode, Widget child }) - : super(key: key, child: child) { - assert(color != null); - assert(transferMode != null); - } - - final Color color; - final ui.TransferMode transferMode; - - RenderColorFilter createRenderObject() => new RenderColorFilter(color: color, transferMode: transferMode); - - void updateRenderObject(RenderColorFilter renderObject, ColorFilter oldWidget) { - renderObject.color = color; - renderObject.transferMode = transferMode; + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('opacity: $opacity'); } } @@ -76,7 +88,7 @@ class ShaderMask extends OneChildRenderObjectWidget { ShaderMask({ Key key, this.shaderCallback, - this.transferMode: ui.TransferMode.modulate, + this.transferMode: TransferMode.modulate, Widget child }) : super(key: key, child: child) { assert(shaderCallback != null); @@ -84,7 +96,7 @@ class ShaderMask extends OneChildRenderObjectWidget { } final ShaderCallback shaderCallback; - final ui.TransferMode transferMode; + final TransferMode transferMode; RenderShaderMask createRenderObject() { return new RenderShaderMask( @@ -122,24 +134,24 @@ class DecoratedBox extends OneChildRenderObjectWidget { } class CustomPaint extends OneChildRenderObjectWidget { - CustomPaint({ Key key, this.callback, this.token, Widget child }) + CustomPaint({ Key key, this.onPaint, this.token, Widget child }) : super(key: key, child: child) { - assert(callback != null); + assert(onPaint != null); } - final CustomPaintCallback callback; + final CustomPaintCallback onPaint; final Object token; // set this to be repainted automatically when the token changes - RenderCustomPaint createRenderObject() => new RenderCustomPaint(callback: callback); + RenderCustomPaint createRenderObject() => new RenderCustomPaint(onPaint: onPaint); void updateRenderObject(RenderCustomPaint renderObject, CustomPaint oldWidget) { if (oldWidget != null && oldWidget.token != token) renderObject.markNeedsPaint(); - renderObject.callback = callback; + renderObject.onPaint = onPaint; } void didUnmountRenderObject(RenderCustomPaint renderObject) { - renderObject.callback = null; + renderObject.onPaint = null; } } @@ -208,25 +220,20 @@ class Padding extends OneChildRenderObjectWidget { class Align extends OneChildRenderObjectWidget { Align({ Key key, - this.horizontal: 0.5, - this.vertical: 0.5, + this.alignment: const FractionalOffset(0.5, 0.5), this.shrinkWrap: ShrinkWrap.none, Widget child }) : super(key: key, child: child) { - assert(horizontal != null); - assert(vertical != null); assert(shrinkWrap != null); } - final double horizontal; - final double vertical; + final FractionalOffset alignment; final ShrinkWrap shrinkWrap; - RenderPositionedBox createRenderObject() => new RenderPositionedBox(horizontal: horizontal, vertical: vertical, shrinkWrap: shrinkWrap); + RenderPositionedBox createRenderObject() => new RenderPositionedBox(alignment: alignment, shrinkWrap: shrinkWrap); void updateRenderObject(RenderPositionedBox renderObject, Align oldWidget) { - renderObject.horizontal = horizontal; - renderObject.vertical = vertical; + renderObject.alignment = alignment; renderObject.shrinkWrap = shrinkWrap; } } @@ -259,6 +266,14 @@ class SizedBox extends OneChildRenderObjectWidget { void updateRenderObject(RenderConstrainedBox renderObject, SizedBox oldWidget) { renderObject.additionalConstraints = _additionalConstraints; } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + if (width != null) + description.add('width: $width'); + if (height != null) + description.add('height: $height'); + } } class ConstrainedBox extends OneChildRenderObjectWidget { @@ -274,6 +289,11 @@ class ConstrainedBox extends OneChildRenderObjectWidget { void updateRenderObject(RenderConstrainedBox renderObject, ConstrainedBox oldWidget) { renderObject.additionalConstraints = constraints; } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('$constraints'); + } } class FractionallySizedBox extends OneChildRenderObjectWidget { @@ -292,6 +312,14 @@ class FractionallySizedBox extends OneChildRenderObjectWidget { renderObject.widthFactor = width; renderObject.heightFactor = height; } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + if (width != null) + description.add('width: $width'); + if (height != null) + description.add('height: $height'); + } } class OverflowBox extends OneChildRenderObjectWidget { @@ -318,6 +346,26 @@ class OverflowBox extends OneChildRenderObjectWidget { } } +class SizedOverflowBox extends OneChildRenderObjectWidget { + SizedOverflowBox({ Key key, this.size, Widget child }) + : super(key: key, child: child); + + final Size size; + + RenderSizedOverflowBox createRenderObject() => new RenderSizedOverflowBox(requestedSize: size); + + void updateRenderObject(RenderSizedOverflowBox renderObject, SizedOverflowBox oldWidget) { + renderObject.requestedSize = size; + } +} + +class OffStage extends OneChildRenderObjectWidget { + OffStage({ Key key, Widget child }) + : super(key: key, child: child); + + RenderOffStage createRenderObject() => new RenderOffStage(); +} + class AspectRatio extends OneChildRenderObjectWidget { AspectRatio({ Key key, this.aspectRatio, Widget child }) : super(key: key, child: child) { @@ -331,6 +379,11 @@ class AspectRatio extends OneChildRenderObjectWidget { void updateRenderObject(RenderAspectRatio renderObject, AspectRatio oldWidget) { renderObject.aspectRatio = aspectRatio; } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('aspectRatio: $aspectRatio'); + } } class IntrinsicWidth extends OneChildRenderObjectWidget { @@ -395,21 +448,21 @@ class Viewport extends OneChildRenderObjectWidget { } class SizeObserver extends OneChildRenderObjectWidget { - SizeObserver({ Key key, this.callback, Widget child }) + SizeObserver({ Key key, this.onSizeChanged, Widget child }) : super(key: key, child: child) { - assert(callback != null); + assert(onSizeChanged != null); } - final SizeChangedCallback callback; + final SizeChangedCallback onSizeChanged; - RenderSizeObserver createRenderObject() => new RenderSizeObserver(callback: callback); + RenderSizeObserver createRenderObject() => new RenderSizeObserver(onSizeChanged: onSizeChanged); void updateRenderObject(RenderSizeObserver renderObject, SizeObserver oldWidget) { - renderObject.callback = callback; + renderObject.onSizeChanged = onSizeChanged; } void didUnmountRenderObject(RenderSizeObserver renderObject) { - renderObject.callback = null; + renderObject.onSizeChanged = null; } } @@ -494,6 +547,26 @@ class Container extends StatelessComponent { return current; } + void debugFillDescription(List description) { + super.debugFillDescription(description); + if (constraints != null) + description.add('$constraints'); + if (decoration != null) + description.add('has background'); + if (foregroundDecoration != null) + description.add('has foreground'); + if (margin != null) + description.add('margin: $margin'); + if (padding != null) + description.add('padding: $padding'); + if (transform != null) + description.add('has transform'); + if (width != null) + description.add('width: $width'); + if (height != null) + description.add('height: $height'); + } + } @@ -617,8 +690,23 @@ class Positioned extends ParentDataWidget { needsLayout = true; } - if (needsLayout) - renderObject.markNeedsLayout(); + if (needsLayout) { + AbstractNode targetParent = renderObject.parent; + if (targetParent is RenderObject) + targetParent.markNeedsLayout(); + } + } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + if (left != null) + description.add('left: $left'); + if (top != null) + description.add('top: $top'); + if (right != null) + description.add('right: $right'); + if (bottom != null) + description.add('bottom: $bottom'); } } @@ -701,9 +789,16 @@ class Flexible extends ParentDataWidget { final FlexParentData parentData = renderObject.parentData; if (parentData.flex != flex) { parentData.flex = flex; - renderObject.markNeedsLayout(); + AbstractNode targetParent = renderObject.parent; + if (targetParent is RenderObject) + targetParent.markNeedsLayout(); } } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('flex: $flex'); + } } class Paragraph extends LeafRenderObjectWidget { @@ -820,7 +915,7 @@ class Image extends LeafRenderObjectWidget { final ui.Image image; final double width; final double height; - final ui.ColorFilter colorFilter; + final ColorFilter colorFilter; final ImageFit fit; final ImageRepeat repeat; final Rect centerSlice; @@ -862,7 +957,7 @@ class ImageListener extends StatefulComponent { final ImageResource image; final double width; final double height; - final ui.ColorFilter colorFilter; + final ColorFilter colorFilter; final ImageFit fit; final ImageRepeat repeat; final Rect centerSlice; @@ -924,7 +1019,7 @@ class NetworkImage extends StatelessComponent { final String src; final double width; final double height; - final ui.ColorFilter colorFilter; + final ColorFilter colorFilter; final ImageFit fit; final ImageRepeat repeat; final Rect centerSlice; @@ -959,7 +1054,7 @@ class AssetImage extends StatelessComponent { final AssetBundle bundle; final double width; final double height; - final ui.ColorFilter colorFilter; + final ColorFilter colorFilter; final ImageFit fit; final ImageRepeat repeat; final Rect centerSlice; @@ -1053,6 +1148,11 @@ class MetaData extends OneChildRenderObjectWidget { void updateRenderObject(RenderMetaData renderObject, MetaData oldWidget) { renderObject.metaData = metaData; } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('$metaData'); + } } class KeyedSubtree extends StatelessComponent { diff --git a/packages/flutter/lib/src/widgets/binding.dart b/packages/flutter/lib/src/widgets/binding.dart index 8ceeb73244..dcead3da1c 100644 --- a/packages/flutter/lib/src/widgets/binding.dart +++ b/packages/flutter/lib/src/widgets/binding.dart @@ -94,8 +94,8 @@ void debugDumpApp() { assert(WidgetFlutterBinding.instance.renderViewElement != null); String mode = 'RELEASE MODE'; assert(() { mode = 'CHECKED MODE'; return true; }); - print('${WidgetFlutterBinding.instance.runtimeType} - $mode'); - WidgetFlutterBinding.instance.renderViewElement.toStringDeep().split('\n').forEach(print); + debugPrint('${WidgetFlutterBinding.instance.runtimeType} - $mode'); + debugPrint(WidgetFlutterBinding.instance.renderViewElement.toStringDeep()); } /// This class provides a bridge from a RenderObject to an Element tree. The diff --git a/packages/flutter/lib/src/widgets/dismissable.dart b/packages/flutter/lib/src/widgets/dismissable.dart index 69f76a8a98..a59c01fea3 100644 --- a/packages/flutter/lib/src/widgets/dismissable.dart +++ b/packages/flutter/lib/src/widgets/dismissable.dart @@ -13,7 +13,7 @@ import 'gesture_detector.dart'; const Duration _kCardDismissFadeout = const Duration(milliseconds: 200); const Duration _kCardDismissResize = const Duration(milliseconds: 300); -const Curve _kCardDismissResizeCurve = const Interval(0.4, 1.0, curve: ease); +const Curve _kCardDismissResizeCurve = const Interval(0.4, 1.0, curve: Curves.ease); const double _kMinFlingVelocity = 700.0; const double _kMinFlingVelocityDelta = 400.0; const double _kFlingVelocityScale = 1.0 / 300.0; @@ -251,7 +251,7 @@ class _DismissableState extends State { onVerticalDragUpdate: _directionIsYAxis ? _handleDragUpdate : null, onVerticalDragEnd: _directionIsYAxis ? _handleDragEnd : null, child: new SizeObserver( - callback: _handleSizeChanged, + onSizeChanged: _handleSizeChanged, child: new FadeTransition( performance: _fadePerformance.view, opacity: new AnimatedValue(1.0, end: 0.0), diff --git a/packages/flutter/lib/src/widgets/drag_target.dart b/packages/flutter/lib/src/widgets/drag_target.dart index 6de530d648..45590155fe 100644 --- a/packages/flutter/lib/src/widgets/drag_target.dart +++ b/packages/flutter/lib/src/widgets/drag_target.dart @@ -4,8 +4,6 @@ import 'dart:collection'; -import 'package:flutter/animation.dart'; -import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'basic.dart'; @@ -258,7 +256,7 @@ class DragRoute extends Route { bool get modal => false; bool get opaque => false; - Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance) { + Widget build(RouteArguments args) { return new Positioned( left: _lastOffset.dx, top: _lastOffset.dy, diff --git a/packages/flutter/lib/src/widgets/enter_exit_transition.dart b/packages/flutter/lib/src/widgets/enter_exit_transition.dart new file mode 100644 index 0000000000..7b6dbee953 --- /dev/null +++ b/packages/flutter/lib/src/widgets/enter_exit_transition.dart @@ -0,0 +1,185 @@ +// 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:async'; + +import 'package:flutter/animation.dart'; + +import 'basic.dart'; +import 'framework.dart'; + +class SmoothlyResizingOverflowBox extends StatefulComponent { + SmoothlyResizingOverflowBox({ + Key key, + this.child, + this.size, + this.duration, + this.curve: Curves.linear + }) : super(key: key) { + assert(duration != null); + assert(curve != null); + } + + final Widget child; + final Size size; + final Duration duration; + final Curve curve; + + _SmoothlyResizingOverflowBoxState createState() => new _SmoothlyResizingOverflowBoxState(); +} + +class _SmoothlyResizingOverflowBoxState extends State { + ValuePerformance _size; + + void initState() { + super.initState(); + _size = new ValuePerformance( + variable: new AnimatedSizeValue(config.size, curve: config.curve), + duration: config.duration + )..addListener(() { + setState(() {}); + }); + } + + void didUpdateConfig(SmoothlyResizingOverflowBox oldConfig) { + _size.duration = config.duration; + _size.variable.curve = config.curve; + if (config.size != oldConfig.size) { + AnimatedSizeValue variable = _size.variable; + variable.begin = variable.value; + variable.end = config.size; + _size.progress = 0.0; + _size.play(); + } + } + + void dispose() { + _size.stop(); + super.dispose(); + } + + Widget build(BuildContext context) { + return new SizedOverflowBox( + size: _size.value, + child: config.child + ); + } +} + +class _Entry { + _Entry({ + this.child, + this.enterPerformance, + this.enterTransition + }); + + final Widget child; + final Performance enterPerformance; + final Widget enterTransition; + + Size childSize = Size.zero; + + Performance exitPerformance; + Widget exitTransition; + + Widget get currentTransition => exitTransition ?? enterTransition; + + void dispose() { + enterPerformance?.stop(); + exitPerformance?.stop(); + } +} + +typedef Widget TransitionBuilderCallback(PerformanceView performance, Widget child); + +class EnterExitTransition extends StatefulComponent { + EnterExitTransition({ + Key key, + this.child, + this.duration, + this.curve: Curves.linear, + this.onEnter, + this.onExit + }) : super(key: key) { + assert(child != null); + assert(duration != null); + assert(curve != null); + assert(onEnter != null); + assert(onExit != null); + } + + final Widget child; + final Duration duration; + final Curve curve; + final TransitionBuilderCallback onEnter; + final TransitionBuilderCallback onExit; + + _EnterExitTransitionState createState() => new _EnterExitTransitionState(); +} + +class _EnterExitTransitionState extends State { + final List<_Entry> _entries = new List<_Entry>(); + + void initState() { + super.initState(); + _entries.add(_createEnterTransition()); + } + + _Entry _createEnterTransition() { + Performance enterPerformance = new Performance(duration: config.duration)..play(); + return new _Entry( + child: config.child, + enterPerformance: enterPerformance, + enterTransition: config.onEnter(enterPerformance, new KeyedSubtree( + key: new GlobalKey(), + child: config.child + )) + ); + } + + Future _createExitTransition(_Entry entry) async { + Performance exitPerformance = new Performance(duration: config.duration); + entry + ..exitPerformance = exitPerformance + ..exitTransition = config.onExit(exitPerformance, entry.enterTransition); + await exitPerformance.play(); + if (!mounted) + return; + setState(() { + _entries.remove(entry); + }); + } + + void didUpdateConfig(EnterExitTransition oldConfig) { + if (config.child.key != oldConfig.child.key) { + _createExitTransition(_entries.last); + _entries.add(_createEnterTransition()); + } + } + + void dispose() { + for (_Entry entry in new List<_Entry>.from(_entries)) + entry.dispose(); + super.dispose(); + } + + Widget build(BuildContext context) { + return new SmoothlyResizingOverflowBox( + size: _entries.last.childSize, + duration: config.duration, + curve: config.curve, + child: new Stack(_entries.map((_Entry entry) { + return new SizeObserver( + key: new ObjectKey(entry), + onSizeChanged: (Size newSize) { + setState(() { + entry.childSize = newSize; + }); + }, + child: entry.currentTransition + ); + }).toList()) + ); + } +} diff --git a/packages/flutter/lib/src/widgets/focus.dart b/packages/flutter/lib/src/widgets/focus.dart index 5f2f129d3d..c5592b0310 100644 --- a/packages/flutter/lib/src/widgets/focus.dart +++ b/packages/flutter/lib/src/widgets/focus.dart @@ -22,8 +22,8 @@ class _FocusScope extends InheritedWidget { Widget child }) : super(key: key, child: child); - final bool scopeFocused; final FocusState focusState; + final bool scopeFocused; // These are mutable because we implicitly change them when they're null in // certain cases, basically pretending retroactively that we were constructed @@ -61,6 +61,15 @@ class _FocusScope extends InheritedWidget { return false; } + void debugFillDescription(List description) { + super.debugFillDescription(description); + if (scopeFocused) + description.add('this scope has focus'); + if (focusedScope != null) + description.add('focused subscope: $focusedScope'); + if (focusedWidget != null) + description.add('focused widget: $focusedWidget'); + } } class Focus extends StatefulComponent { diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index 1cfd022b49..a3b6409d8d 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -7,6 +7,8 @@ import 'dart:collection'; import 'package:flutter/rendering.dart'; +export 'package:flutter/rendering.dart' show debugPrint; + // KEYS /// A Key is an identifier for [Widget]s and [Element]s. A new Widget will only @@ -40,6 +42,12 @@ class ValueKey extends Key { String toString() => '[\'$value\']'; } +/// A [Key] that is only equal to itself. +class UniqueKey extends Key { + const UniqueKey() : super.constructor(); + String toString() => '[$hashCode]'; +} + /// A kind of [Key] that takes its identity from the object used as its value. /// /// Used to tie the identity of a Widget to the identity of an object used to @@ -184,7 +192,7 @@ class GlobalObjectKey extends GlobalKey { return identical(value, typedOther.value); } int get hashCode => identityHashCode(value); - String toString() => '[GlobalKey ${value.runtimeType}(${value.hashCode})]'; + String toString() => '[$runtimeType ${value.runtimeType}(${value.hashCode})]'; } @@ -200,8 +208,12 @@ abstract class Widget { /// Inflates this configuration to a concrete instance. Element createElement(); + String toStringShort() { + return key == null ? '$runtimeType' : '$runtimeType-$key'; + } + String toString() { - final String name = key == null ? '$runtimeType' : '$runtimeType-$key'; + final String name = toStringShort(); final List data = []; debugFillDescription(data); if (data.isEmpty) @@ -823,10 +835,13 @@ abstract class Element implements BuildContext { void debugFillDescription(List description) { if (depth == null) description.add('no depth'); - if (widget == null) + if (widget == null) { description.add('no widget'); - else + } else { + if (widget.key != null) + description.add('${widget.key}'); widget.debugFillDescription(description); + } } String toStringDeep([String prefixLineOne = '', String prefixOtherLines = '']) { @@ -1090,7 +1105,7 @@ class StatefulComponentElement> assert(() { if (_state._debugLifecycleState == _StateLifecycle.initialized) return true; - print('${_state.runtimeType}.initState failed to call super.initState'); + debugPrint('${_state.runtimeType}.initState failed to call super.initState'); return false; }); assert(() { _state._debugLifecycleState = _StateLifecycle.ready; return true; }); @@ -1123,7 +1138,7 @@ class StatefulComponentElement> assert(() { if (_state._debugLifecycleState == _StateLifecycle.defunct) return true; - print('${_state.runtimeType}.dispose failed to call super.dispose'); + debugPrint('${_state.runtimeType}.dispose failed to call super.dispose'); return false; }); assert(!dirty); // See BuildableElement.unmount for why this is important. @@ -1267,7 +1282,7 @@ abstract class RenderObjectElement extends Buildab // dirty, e.g. if they have a builder callback. (Builder callbacks have a // 'BuildContext' argument which you can pass to Theme.of() and other // InheritedWidget APIs which eventually trigger a rebuild.) - print('$runtimeType failed to implement reinvokeBuilders(), but got marked dirty'); + debugPrint('$runtimeType failed to implement reinvokeBuilders(), but got marked dirty'); assert(() { 'reinvokeBuilders() not implemented'; return false; @@ -1609,11 +1624,11 @@ void _debugReportException(String context, dynamic exception, StackTrace stack) if (debugWidgetsExceptionHandler != null) { debugWidgetsExceptionHandler(context, exception, stack); } else { - print('------------------------------------------------------------------------'); - 'Exception caught while $context'.split('\n').forEach(print); - print('$exception'); - print('Stack trace:'); - '$stack'.split('\n').forEach(print); - print('------------------------------------------------------------------------'); + debugPrint('------------------------------------------------------------------------'); + debugPrint('Exception caught while $context'); + debugPrint('$exception'); + debugPrint('Stack trace:'); + debugPrint('$stack'); + debugPrint('------------------------------------------------------------------------'); } } diff --git a/packages/flutter/lib/src/widgets/gesture_detector.dart b/packages/flutter/lib/src/widgets/gesture_detector.dart index 6f9571953e..36e818c3b5 100644 --- a/packages/flutter/lib/src/widgets/gesture_detector.dart +++ b/packages/flutter/lib/src/widgets/gesture_detector.dart @@ -8,6 +8,25 @@ import 'package:flutter/rendering.dart'; import 'basic.dart'; import 'framework.dart'; +export 'package:flutter/gestures.dart' show + GestureTapCallback, + GestureTapCallback, + GestureTapCallback, + GestureShowPressCallback, + GestureLongPressCallback, + GestureDragStartCallback, + GestureDragUpdateCallback, + GestureDragEndCallback, + GestureDragStartCallback, + GestureDragUpdateCallback, + GestureDragEndCallback, + GesturePanStartCallback, + GesturePanUpdateCallback, + GesturePanEndCallback, + GestureScaleStartCallback, + GestureScaleUpdateCallback, + GestureScaleEndCallback; + class GestureDetector extends StatefulComponent { const GestureDetector({ Key key, diff --git a/packages/flutter/lib/src/widgets/gridpaper.dart b/packages/flutter/lib/src/widgets/gridpaper.dart new file mode 100644 index 0000000000..25d22e3a35 --- /dev/null +++ b/packages/flutter/lib/src/widgets/gridpaper.dart @@ -0,0 +1,36 @@ +// 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:flutter/rendering.dart'; + +import 'basic.dart'; +import 'framework.dart'; + +class GridPaper extends StatelessComponent { + GridPaper({ + Key key, + this.color: const Color(0xFF000000), + this.interval: 100.0 + }) : super(key: key); + + final Color color; + final double interval; + + Widget build(BuildContext context) { + return new IgnorePointer(child: new CustomPaint( + onPaint: (PaintingCanvas canvas, Size size) { + Paint linePaint = new Paint() + ..color = color; + for (double x = 0.0; x <= size.width; x += interval / 10.0) { + linePaint.strokeWidth = (x % interval == 0.0) ? 1.0 : (x % (interval / 2.0) == 0.0) ? 0.5: 0.25; + canvas.drawLine(new Point(x, 0.0), new Point(x, size.height), linePaint); + } + for (double y = 0.0; y <= size.height; y += interval / 10.0) { + linePaint.strokeWidth = (y % interval == 0.0) ? 1.0 : (y % (interval / 2.0) == 0.0) ? 0.5: 0.25; + canvas.drawLine(new Point(0.0, y), new Point(size.width, y), linePaint); + } + }) + ); + } +} diff --git a/packages/flutter/lib/src/widgets/heroes.dart b/packages/flutter/lib/src/widgets/heroes.dart new file mode 100644 index 0000000000..49723869ab --- /dev/null +++ b/packages/flutter/lib/src/widgets/heroes.dart @@ -0,0 +1,386 @@ +// 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:flutter/animation.dart'; +import 'package:flutter/rendering.dart'; + +import 'basic.dart'; +import 'framework.dart'; +import 'transitions.dart'; + +// Heroes are the parts of an application's screen-to-screen transitions where a +// component from one screen shifts to a position on the other. For example, +// album art from a list of albums growing to become the centerpiece of the +// album's details view. In this context, a screen is a navigator Route. + +// To get this effect, all you have to do is wrap each hero on each route with a +// Hero widget, and give each hero a tag. Tag must either be unique within the +// current route's widget subtree, or all the Heroes with that tag on a +// particular route must have a key. When the app transitions from one route to +// another, each tag present is animated. When there's exactly one hero with +// that tag, that hero will be animated for that tag. When there are multiple +// heroes in a route with the same tag, then whichever hero has a key that +// matches one of the keys in the "most important key" list given to the +// navigator when the route was pushed will be animated. If a hero is only +// present on one of the routes and not the other, then it will be made to +// appear or disappear as needed. + +// TODO(ianh): Make the appear/disappear animations pretty. Right now they're +// pretty crude (just rotate and shrink the constraints). They should probably +// involve actually scaling and fading, at a minimum. + +// Heroes and the Navigator's Stack must be axis-aligned for all this to work. +// The top left and bottom right coordinates of each animated Hero will be +// converted to global coordinates and then from there converted to the +// Navigator Stack's coordinate space, and the entire Hero subtree will, for the +// duration of the animation, be lifted out of its original place, and +// positioned on that stack. If the Hero isn't axis aligned, this is going to +// fail in a rather ugly fashion. Don't rotate your heroes! + +// To make the animations look good, it's critical that the widget tree for the +// hero in both locations be essentially identical. The widget of the target is +// used to do the transition: when going from route A to route B, route B's +// hero's widget is placed over route A's hero's widget, and route A's hero is +// hidden. Then the widget is animated to route B's hero's position, and then +// the widget is inserted into route B. When going back from B to A, route A's +// hero's widget is placed over where route B's hero's widget was, and then the +// animation goes the other way. + +// TODO(ianh): If the widgets use Inherited properties, they are taken from the +// Navigator's position in the widget hierarchy, not the source or target. We +// should interpolate the inherited properties from their value at the source to +// their value at the target. See: https://github.com/flutter/engine/issues/1698 + +final Object centerOfAttentionHeroTag = new Object(); + +class _HeroManifest { + const _HeroManifest({ + this.key, + this.config, + this.sourceStates, + this.currentRect, + this.currentTurns + }); + final GlobalKey key; + final Widget config; + final Set sourceStates; + final RelativeRect currentRect; + final double currentTurns; +} + +abstract class HeroHandle { + _HeroManifest _takeChild(Rect animationArea); +} + +class Hero extends StatefulComponent { + Hero({ + Key key, + this.tag, + this.child, + this.turns: 1 + }) : super(key: key) { + assert(tag != null); + } + + final Object tag; + final Widget child; + final int turns; + + static Map of(BuildContext context, Set mostValuableKeys) { + mostValuableKeys ??= new Set(); + assert(!mostValuableKeys.contains(null)); + // first we collect ALL the heroes, sorted by their tags + Map> heroes = >{}; + void visitor(Element element) { + if (element.widget is Hero) { + StatefulComponentElement hero = element; + Object tag = hero.widget.tag; + assert(tag != null); + Key key = hero.widget.key; + final Map tagHeroes = heroes.putIfAbsent(tag, () => {}); + assert(!tagHeroes.containsKey(key)); + tagHeroes[key] = hero.state; + } + element.visitChildren(visitor); + } + context.visitChildElements(visitor); + // next, for each tag, we're going to decide on the one hero we care about for that tag + Map result = {}; + for (Object tag in heroes.keys) { + assert(tag != null); + if (heroes[tag].length == 1) { + result[tag] = heroes[tag].values.first; + } else { + assert(heroes[tag].length > 1); + assert(!heroes[tag].containsKey(null)); + assert(heroes[tag].keys.where((Key key) => mostValuableKeys.contains(key)).length <= 1); + Key mostValuableKey = mostValuableKeys.firstWhere((Key key) => heroes[tag].containsKey(key), orElse: () => null); + if (mostValuableKey != null) + result[tag] = heroes[tag][mostValuableKey]; + } + } + assert(!result.containsKey(null)); + return result; + } + + HeroState createState() => new HeroState(); +} + +enum _HeroMode { constructing, initialized, measured, taken } + +class HeroState extends State implements HeroHandle { + + void initState() { + assert(_mode == _HeroMode.constructing); + super.initState(); + _key = new GlobalKey(); + _mode = _HeroMode.initialized; + } + + GlobalKey _key; + + _HeroMode _mode = _HeroMode.constructing; + Size _size; + + _HeroManifest _takeChild(Rect animationArea) { + assert(_mode == _HeroMode.measured || _mode == _HeroMode.taken); + final RenderBox renderObject = context.findRenderObject(); + final Point heroTopLeft = renderObject.localToGlobal(Point.origin); + final Point heroBottomRight = renderObject.localToGlobal(renderObject.size.bottomRight(Point.origin)); + final Rect heroArea = new Rect.fromLTRB(heroTopLeft.x, heroTopLeft.y, heroBottomRight.x, heroBottomRight.y); + final RelativeRect startRect = new RelativeRect.fromRect(heroArea, animationArea); + _HeroManifest result = new _HeroManifest( + key: _key, + config: config, + sourceStates: new Set.from([this]), + currentRect: startRect, + currentTurns: config.turns.toDouble() + ); + setState(() { + _key = null; + _mode = _HeroMode.taken; + }); + return result; + } + + void _setChild(GlobalKey value) { + assert(_mode == _HeroMode.taken); + assert(_key == null); + assert(_size != null); + if (mounted) + setState(() { _key = value; }); + _size = null; + _mode = _HeroMode.initialized; + } + + void _resetChild() { + assert(_mode == _HeroMode.taken); + assert(_key == null); + assert(_size != null); + if (mounted) + setState(() { _key = new GlobalKey(); }); + _size = null; + _mode = _HeroMode.initialized; + } + + Widget build(BuildContext context) { + switch (_mode) { + case _HeroMode.constructing: + assert(false); + return null; + case _HeroMode.initialized: + case _HeroMode.measured: + return new SizeObserver( + onSizeChanged: (Size size) { + assert(_mode == _HeroMode.initialized || _mode == _HeroMode.measured); + _size = size; + _mode = _HeroMode.measured; + }, + child: new KeyedSubtree( + key: _key, + child: config.child + ) + ); + case _HeroMode.taken: + return new SizedBox(width: _size.width, height: _size.height); + } + } + +} + + +class _HeroQuestState implements HeroHandle { + _HeroQuestState({ + this.tag, + this.key, + this.child, + this.sourceStates, + this.targetRect, + this.targetTurns, + this.targetState, + this.currentRect, + this.currentTurns + }) { + assert(tag != null); + } + + final Object tag; + final GlobalKey key; + final Widget child; + final Set sourceStates; + final RelativeRect targetRect; + final int targetTurns; + final HeroState targetState; + final AnimatedRelativeRectValue currentRect; + final AnimatedValue currentTurns; + + bool get taken => _taken; + bool _taken = false; + _HeroManifest _takeChild(Rect animationArea) { + assert(!taken); + _taken = true; + Set states = sourceStates; + if (targetState != null) + states = states.union(new Set.from([targetState])); + return new _HeroManifest( + key: key, + config: child, + sourceStates: states, + currentRect: currentRect.value, + currentTurns: currentTurns.value + ); + } + + Widget build(BuildContext context, PerformanceView performance) { + return new PositionedTransition( + rect: currentRect, + performance: performance, + child: new RotationTransition( + turns: currentTurns, + performance: performance, + child: new KeyedSubtree( + key: key, + child: child + ) + ) + ); + } +} + +class _HeroMatch { + const _HeroMatch(this.from, this.to, this.tag); + final HeroHandle from; + final HeroHandle to; + final Object tag; +} + +typedef void QuestFinishedHandler(); + +class HeroParty { + HeroParty({ this.onQuestFinished }); + + final QuestFinishedHandler onQuestFinished; + + List<_HeroQuestState> _heroes = <_HeroQuestState>[]; + bool get isEmpty => _heroes.isEmpty; + + Map getHeroesToAnimate() { + Map result = new Map(); + for (_HeroQuestState hero in _heroes) + result[hero.tag] = hero; + assert(!result.containsKey(null)); + return result; + } + + AnimatedRelativeRectValue createAnimatedRelativeRect(RelativeRect begin, RelativeRect end, Curve curve) { + return new AnimatedRelativeRectValue(begin, end: end, curve: curve); + } + + AnimatedValue createAnimatedTurns(double begin, double end, Curve curve) { + assert(end.floor() == end); + return new AnimatedValue(begin, end: end, curve: curve); + } + + void animate(Map heroesFrom, Map heroesTo, Rect animationArea, Curve curve) { + assert(!heroesFrom.containsKey(null)); + assert(!heroesTo.containsKey(null)); + + // make a list of pairs of heroes, based on the from and to lists + Map heroes = {}; + for (Object tag in heroesFrom.keys) + heroes[tag] = new _HeroMatch(heroesFrom[tag], heroesTo[tag], tag); + for (Object tag in heroesTo.keys) { + if (!heroes.containsKey(tag)) + heroes[tag] = new _HeroMatch(heroesFrom[tag], heroesTo[tag], tag); + } + + // create a heroating hero out of each pair + final List<_HeroQuestState> _newHeroes = <_HeroQuestState>[]; + for (_HeroMatch heroPair in heroes.values) { + assert(heroPair.from != null || heroPair.to != null); + _HeroManifest from = heroPair.from?._takeChild(animationArea); + assert(heroPair.to == null || heroPair.to is HeroState); + _HeroManifest to = heroPair.to?._takeChild(animationArea); + assert(from != null || to != null); + assert(to == null || to.sourceStates.length == 1); + assert(to == null || to.currentTurns.floor() == to.currentTurns); + HeroState targetState = to != null ? to.sourceStates.elementAt(0) : null; + Set sourceStates = from != null ? from.sourceStates : new Set(); + sourceStates.remove(targetState); + RelativeRect sourceRect = from != null ? from.currentRect : + new RelativeRect.fromRect(to.currentRect.toRect(animationArea).center & Size.zero, animationArea); + RelativeRect targetRect = to != null ? to.currentRect : + new RelativeRect.fromRect(from.currentRect.toRect(animationArea).center & Size.zero, animationArea); + double sourceTurns = from != null ? from.currentTurns : 0.0; + double targetTurns = to != null ? to.currentTurns : 0.0; + _newHeroes.add(new _HeroQuestState( + tag: heroPair.tag, + key: from != null ? from.key : to.key, + child: to != null ? to.config : from.config, + sourceStates: sourceStates, + targetRect: targetRect, + targetTurns: targetTurns.floor(), + targetState: targetState, + currentRect: createAnimatedRelativeRect(sourceRect, targetRect, curve), + currentTurns: createAnimatedTurns(sourceTurns, targetTurns, curve) + )); + } + + assert(!_heroes.any((_HeroQuestState hero) => !hero.taken)); + _heroes = _newHeroes; + } + + PerformanceView _currentPerformance; + + Iterable getWidgets(BuildContext context, PerformanceView performance) sync* { + assert(performance != null || _heroes.length == 0); + if (performance != _currentPerformance) { + if (_currentPerformance != null) + _currentPerformance.removeStatusListener(_handleUpdate); + _currentPerformance = performance; + if (_currentPerformance != null) + _currentPerformance.addStatusListener(_handleUpdate); + } + for (_HeroQuestState hero in _heroes) + yield hero.build(context, performance); + } + + void _handleUpdate(PerformanceStatus status) { + if (status == PerformanceStatus.completed || + status == PerformanceStatus.dismissed) { + for (_HeroQuestState hero in _heroes) { + if (hero.targetState != null) + hero.targetState._setChild(hero.key); + for (HeroState source in hero.sourceStates) + source._resetChild(); + if (onQuestFinished != null) + onQuestFinished(); + } + _heroes.clear(); + _currentPerformance = null; + } + } + + String toString() => '$_heroes'; +} diff --git a/packages/flutter/lib/src/widgets/homogeneous_viewport.dart b/packages/flutter/lib/src/widgets/homogeneous_viewport.dart index 3ee2735afa..749488dac8 100644 --- a/packages/flutter/lib/src/widgets/homogeneous_viewport.dart +++ b/packages/flutter/lib/src/widgets/homogeneous_viewport.dart @@ -5,8 +5,9 @@ import 'dart:math' as math; import 'package:flutter/rendering.dart'; -import 'package:flutter/src/widgets/framework.dart'; -import 'package:flutter/src/widgets/basic.dart'; + +import 'framework.dart'; +import 'basic.dart'; typedef List ListBuilder(BuildContext context, int startIndex, int count); diff --git a/packages/flutter/lib/src/widgets/mimic.dart b/packages/flutter/lib/src/widgets/mimic.dart index 6170daa36e..d3419e9c46 100644 --- a/packages/flutter/lib/src/widgets/mimic.dart +++ b/packages/flutter/lib/src/widgets/mimic.dart @@ -81,7 +81,7 @@ class MimicableState extends State { ); } return new SizeObserver( - callback: _handleSizeChanged, + onSizeChanged: _handleSizeChanged, child: config.child ); } diff --git a/packages/flutter/lib/src/widgets/mixed_viewport.dart b/packages/flutter/lib/src/widgets/mixed_viewport.dart index 2965054988..95e8cdfabc 100644 --- a/packages/flutter/lib/src/widgets/mixed_viewport.dart +++ b/packages/flutter/lib/src/widgets/mixed_viewport.dart @@ -333,7 +333,7 @@ class _MixedViewportElement extends RenderObjectElement { double newExtent = _getElementExtent(element, innerConstraints); bool result = _childExtents[index] == newExtent; if (!result) - print("Element $element at index $index was size ${_childExtents[index]} but is now size $newExtent yet no invalidate() was received to that effect"); + debugPrint("Element $element at index $index was size ${_childExtents[index]} but is now size $newExtent yet no invalidate() was received to that effect"); return result; } diff --git a/packages/flutter/lib/src/widgets/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index c326efd747..b8c072a77a 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -3,14 +3,25 @@ // found in the LICENSE file. import 'package:flutter/animation.dart'; +import 'package:flutter/rendering.dart'; import 'basic.dart'; import 'focus.dart'; import 'framework.dart'; +import 'heroes.dart'; import 'transitions.dart'; +import 'gridpaper.dart'; + +/// Set this to true to overlay a pixel grid on the screen, with every 100 +/// pixels marked with a thick maroon line and every 10 pixels marked with a +/// thin maroon line. This can help with verifying widget positions. +bool debugShowGrid = false; +Color debugGridColor = const Color(0x7F7F2020); + +const String kDefaultRouteName = '/'; class RouteArguments { - const RouteArguments({ this.navigator, this.previousPerformance, this.nextPerformance }); + const RouteArguments(this.navigator, { this.previousPerformance, this.nextPerformance }); final NavigatorState navigator; final PerformanceView previousPerformance; final PerformanceView nextPerformance; @@ -28,56 +39,130 @@ class Navigator extends StatefulComponent { this.onUnknownRoute // 404 generator. You only need to implement this if you have a way to navigate to arbitrary names. }) : super(key: key) { // To use a navigator, you must at a minimum define the route with the name '/'. - assert(routes.containsKey('/')); + assert(routes != null); + assert(routes.containsKey(kDefaultRouteName)); } final Map routes; final RouteGenerator onGenerateRoute; final RouteBuilder onUnknownRoute; + static NavigatorState of(BuildContext context) { + NavigatorState result; + bool visitor(Element element) { + if (element is StatefulComponentElement) { + if (element.state is NavigatorState) { + result = element.state; + return false; + } + } + return true; + } + if (visitor(context)) + context.visitAncestorElements(visitor); + return result; + } + NavigatorState createState() => new NavigatorState(); } +// The navigator tracks which "page" we are on. +// It also animates between these pages. +// Pages can have "heroes", which are UI elements that animate from point to point. +// These animations are called journeys. +// +// Journeys can start in two conditions: +// - Everything is calm, and we have no heroes in flight. In this case, we will +// have to collect the heroes from the route we're starting at and the route +// we're going to, and try to transition from one set to the other. +// - We already have heroes in flight. In that case, we just want to look at +// the heroes of our destination, and then try to transition to them from the +// in-flight heroes. + +class _HeroTransitionInstruction { + Route from; + Route to; + void update(Route newFrom, Route newTo) { + assert(newFrom != null); + assert(newTo != null); + if (!newFrom.canHaveHeroes || !newTo.canHaveHeroes) + return; + assert(newFrom.performance != null); + assert(newTo.performance != null); + if (from == null) + from = newFrom; + to = newTo; + if (from == to) + reset(); + } + void reset() { + assert(hasInstructions); + from = null; + to = null; + } + bool get hasInstructions => from != null || to != null; +} + class NavigatorState extends State { List _history = new List(); - int _currentPosition = 0; + int _currentPosition = 0; // which route is "current" Route get currentRoute => _history[_currentPosition]; bool get hasPreviousRoute => _history.length > 1; void initState() { super.initState(); - PageRoute route = new PageRoute(config.routes['/']); - assert(route != null); + _activeHeroes = new HeroParty(onQuestFinished: _handleHeroQuestFinished); + PageRoute route = new PageRoute(config.routes[kDefaultRouteName], name: kDefaultRouteName); + assert(route.hasContent); assert(!route.ephemeral); _insertRoute(route); } - void pushState(State owner, Function callback) { + void pushState(State owner, StateRouteCallback onPop) { push(new StateRoute( route: currentRoute, owner: owner, - callback: callback + onPop: onPop )); } - void pushNamed(String name) { + void pushNamed(String name, { Set mostValuableKeys }) { RouteBuilder generateRoute() { assert(config.onGenerateRoute != null); return config.onGenerateRoute(name); } - RouteBuilder builder = config.routes[name] ?? generateRoute() ?? config.onUnknownRoute; - push(new PageRoute(builder)); + final RouteBuilder builder = config.routes[name] ?? generateRoute() ?? config.onUnknownRoute; + assert(builder != null); // 404 getting your 404! + push(new PageRoute(builder, name: name, mostValuableKeys: mostValuableKeys)); + } + + final _HeroTransitionInstruction _desiredHeroes = new _HeroTransitionInstruction(); + HeroParty _activeHeroes; + + void _handleHeroQuestFinished() { + for (Route route in _history) + route._hasActiveHeroes = false; } void push(Route route) { assert(!_debugCurrentlyHaveRoute(route)); setState(() { + // pop ephemeral routes (like popup menus) while (currentRoute.ephemeral) { currentRoute.didPop(null); _currentPosition -= 1; } + // find the most recent active route that might have heroes + if (route.hasContent) { + int index = _currentPosition; + while (index > 0 && !_history[index].hasContent) + index -= 1; + assert(_history[index].hasContent); + _desiredHeroes.update(_history[index], route); + } + // add the new route _currentPosition += 1; _insertRoute(route); }); @@ -87,21 +172,29 @@ class NavigatorState extends State { assert(_debugCurrentlyHaveRoute(route)); assert(_currentPosition > 0); setState(() { + // pop any routes above this one (they must be ephemeral, otherwise there's an error) while (currentRoute != route) { assert(currentRoute.ephemeral); currentRoute.didPop(null); _currentPosition -= 1; } - assert(_currentPosition > 0); - currentRoute.didPop(result); - _currentPosition -= 1; }); + pop(result); assert(!_debugCurrentlyHaveRoute(route)); } void pop([dynamic result]) { setState(() { assert(_currentPosition > 0); + // find the most recent previous route that might have heroes + if (currentRoute.hasContent) { + int index = _currentPosition - 1; + while (index > 0 && !_history[index].hasContent) + index -= 1; + assert(_history[index].hasContent); + _desiredHeroes.update(currentRoute, _history[index]); + } + // pop the route currentRoute.didPop(result); _currentPosition -= 1; }); @@ -136,44 +229,112 @@ class NavigatorState extends State { void _removeRoute(Route route) { assert(_history.contains(route)); setState(() { + if (_desiredHeroes.hasInstructions) { + if (_desiredHeroes.from == route || _desiredHeroes.to == route) + _desiredHeroes.reset(); + } _history.remove(route); }); } + PerformanceView _currentHeroPerformance; + Widget build(BuildContext context) { - List visibleRoutes = new List(); - bool alreadyInsertModalBarrier = false; - PerformanceView nextPerformance; + List visibleRoutes = []; + + assert(() { + if (debugShowGrid) + visibleRoutes.add(new GridPaper(color: debugGridColor)); + return true; + }); + + + bool alreadyInsertedHeroes = false; + bool alreadyInsertedModalBarrier = false; + Route nextContentRoute; + PerformanceView nextHeroPerformance; for (int i = _history.length-1; i >= 0; i -= 1) { - Route route = _history[i]; + final Route route = _history[i]; if (!route.hasContent) { assert(!route.modal); + assert(!_desiredHeroes.hasInstructions || (_desiredHeroes.from != route && _desiredHeroes.to != route)); + assert(!route._hasActiveHeroes); continue; } - visibleRoutes.add( - new KeyedSubtree( - key: new ObjectKey(route), - child: route.build(this, nextPerformance) - ) - ); - if (route.isActuallyOpaque) + if (route._hasActiveHeroes && !alreadyInsertedHeroes) { + visibleRoutes.addAll(_activeHeroes.getWidgets(context, _currentHeroPerformance)); + alreadyInsertedHeroes = true; + } + if (_desiredHeroes.hasInstructions) { + if ((_desiredHeroes.to == route || _desiredHeroes.from == route) && nextHeroPerformance == null) + nextHeroPerformance = route.performance; + visibleRoutes.add(route._internalBuild(nextContentRoute, buildTargetHeroes: _desiredHeroes.to == route)); + } else { + visibleRoutes.add(route._internalBuild(nextContentRoute)); + } + if (route.isActuallyOpaque) { + assert(!_desiredHeroes.hasInstructions || + (_history.indexOf(_desiredHeroes.from) >= i && _history.indexOf(_desiredHeroes.to) >= i)); break; + } assert(route.modal || route.ephemeral); - if (route.modal && i > 0 && !alreadyInsertModalBarrier) { + if (route.modal && i > 0 && !alreadyInsertedModalBarrier) { visibleRoutes.add(new Listener( onPointerDown: (_) { pop(); }, child: new Container() )); - alreadyInsertModalBarrier = true; + alreadyInsertedModalBarrier = true; } - nextPerformance = route.performance; + nextContentRoute = route; } + + if (_desiredHeroes.hasInstructions) { + assert(nextHeroPerformance != null); + scheduler.requestPostFrameCallback((Duration timestamp) { + Map heroesFrom; + Map heroesTo; + Set mostValuableKeys = new Set(); + if (_desiredHeroes.from.mostValuableKeys != null) + mostValuableKeys.addAll(_desiredHeroes.from.mostValuableKeys); + if (_desiredHeroes.to.mostValuableKeys != null) + mostValuableKeys.addAll(_desiredHeroes.to.mostValuableKeys); + if (_activeHeroes.isEmpty) { + assert(!_desiredHeroes.from._hasActiveHeroes); + heroesFrom = _desiredHeroes.from.getHeroesToAnimate(mostValuableKeys); + _desiredHeroes.from._hasActiveHeroes = heroesFrom.length > 0; + } else { + assert(_desiredHeroes.from._hasActiveHeroes); + heroesFrom = _activeHeroes.getHeroesToAnimate(); + } + heroesTo = _desiredHeroes.to.getHeroesToAnimate(mostValuableKeys); + _desiredHeroes.to._hasActiveHeroes = heroesTo.length > 0; + _desiredHeroes.reset(); + setState(() { + final RenderBox renderObject = context.findRenderObject(); + final Point animationTopLeft = renderObject.localToGlobal(Point.origin); + final Point animationBottomRight = renderObject.localToGlobal(renderObject.size.bottomRight(Point.origin)); + final Rect animationArea = new Rect.fromLTRB(animationTopLeft.x, animationTopLeft.y, animationBottomRight.x, animationBottomRight.y); + Curve curve = Curves.ease; + if (nextHeroPerformance.status == PerformanceStatus.reverse) { + nextHeroPerformance = new ReversePerformance(nextHeroPerformance); + curve = new Interval(nextHeroPerformance.progress, 1.0, curve: curve); + } + _activeHeroes.animate(heroesFrom, heroesTo, animationArea, curve); + _currentHeroPerformance = nextHeroPerformance; + }); + }); + } + return new Focus(child: new Stack(visibleRoutes.reversed.toList())); } } abstract class Route { + Route() { + _subtreeKey = new GlobalKey(label: debugLabel); + } + /// If hasContent is true, then the route represents some on-screen state. /// /// If hasContent is false, then no performance will be created, and the values of @@ -227,13 +388,12 @@ abstract class Route { PerformanceView get performance => null; bool get isActuallyOpaque => (performance == null || performance.isCompleted) && opaque; - Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance); - + NavigatorState get navigator => _navigator; NavigatorState _navigator; void setState(void fn()) { - assert(_navigator != null); - _navigator.setState(fn); + assert(navigator != null); + navigator.setState(fn); } void didPush(NavigatorState navigator) { @@ -244,24 +404,73 @@ abstract class Route { } void didPop([dynamic result]) { - assert(_navigator != null); + assert(navigator != null); if (performance == null) - _navigator._removeRoute(this); + navigator._removeRoute(this); } void _handlePerformanceStatusChanged(PerformanceStatus status) { if (status == PerformanceStatus.completed) { - _navigator._didCompleteRoute(this); + navigator._didCompleteRoute(this); } else if (status == PerformanceStatus.dismissed) { - _navigator._didDismissRoute(this); - _navigator._removeRoute(this); + navigator._didDismissRoute(this); + navigator._removeRoute(this); _navigator = null; } } - String toString() => '$runtimeType()'; + /// Called by the navigator.build() function if hasContent is true, to get the + /// subtree for this route. + /// + /// If buildTargetHeroes is true, then getHeroesToAnimate() will be called + /// after this build, before the next build, and this build should render the + /// route off-screen, at the end of its animation. Next frame, the argument + /// will be false, and the tree should be built at the first frame of the + /// transition animation, whatever that is. + Widget _internalBuild(Route nextRoute, { bool buildTargetHeroes: false }) { + assert(navigator != null); + return keySubtree(build(new RouteArguments( + navigator, + previousPerformance: performance, + nextPerformance: nextRoute?.performance + ))); + } + + bool get canHaveHeroes => hasContent && modal && opaque; + Set get mostValuableKeys => null; + + /// Return a party of heroes (one per tag) to animate. This is called by the + /// navigator when hasContent is true just after this route, the previous + /// route, or the next route, has been pushed or popped, to figure out which + /// heroes it should be trying to animate. + Map getHeroesToAnimate([Set mostValuableKeys]) => const {}; + bool _hasActiveHeroes = false; + + /// Returns the BuildContext for the root of the subtree built for this route, + /// assuming that internalBuild used keySubtree to build that subtree. + /// This is only valid after a build phase. + BuildContext get context => _subtreeKey.currentContext; + + GlobalKey _subtreeKey; + + /// Wraps the given subtree in a route-specific GlobalKey. + Widget keySubtree(Widget child) { + return new KeyedSubtree( + key: _subtreeKey, + child: child + ); + } + + /// Called by internalBuild. This is the method to override if you want to + /// change what subtree is built for this route. + Widget build(RouteArguments args); + + String get debugLabel => '$runtimeType'; + + String toString() => '$runtimeType(performance: $performance; key: $_subtreeKey)'; } + abstract class PerformanceRoute extends Route { PerformanceRoute() { _performance = createPerformance(); @@ -272,13 +481,27 @@ abstract class PerformanceRoute extends Route { Performance createPerformance() { Duration duration = transitionDuration; - assert(duration >= Duration.ZERO); - return new Performance(duration: duration); + assert(duration != null && duration >= Duration.ZERO); + return new Performance(duration: duration, debugLabel: debugLabel); } Duration get transitionDuration; - Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance); + Widget _internalBuild(Route nextRoute, { bool buildTargetHeroes: false }) { + assert(hasContent); + assert(transitionDuration > Duration.ZERO); + if (buildTargetHeroes && performance.progress != 1.0) { + Performance fakePerformance = createPerformance(); + assert(fakePerformance != null); + fakePerformance.progress = 1.0; + return new OffStage( + child: keySubtree( + build(new RouteArguments(navigator, previousPerformance: fakePerformance)) + ) + ); + } + return super._internalBuild(nextRoute, buildTargetHeroes: buildTargetHeroes); + } void didPush(NavigatorState navigator) { super.didPush(navigator); @@ -294,35 +517,66 @@ abstract class PerformanceRoute extends Route { const Duration _kTransitionDuration = const Duration(milliseconds: 150); const Point _kTransitionStartPoint = const Point(0.0, 75.0); +/// A route that represents a page in an application. +/// +/// PageRoutes try to animate between themselves in a fashion that is aware of +/// any Heroes. class PageRoute extends PerformanceRoute { - PageRoute(this.builder); + PageRoute(this._builder, { + this.name: '', + Set mostValuableKeys + }) : _mostValuableKeys = mostValuableKeys { + assert(_builder != null); + } - final RouteBuilder builder; + final RouteBuilder _builder; + final String name; + final Set _mostValuableKeys; + + Set get mostValuableKeys => _mostValuableKeys; bool get opaque => true; Duration get transitionDuration => _kTransitionDuration; - Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance) { + Map getHeroesToAnimate([Set mostValuableKeys]) { + return Hero.of(context, mostValuableKeys); + } + + Widget build(RouteArguments args) { // TODO(jackson): Hit testing should ignore transform // TODO(jackson): Block input unless content is interactive + // TODO(ianh): Support having different transitions, e.g. when heroes are around. return new SlideTransition( - performance: performance, - position: new AnimatedValue(_kTransitionStartPoint, end: Point.origin, curve: easeOut), + performance: args.previousPerformance, + position: new AnimatedValue(_kTransitionStartPoint, end: Point.origin, curve: Curves.easeOut), child: new FadeTransition( - performance: performance, - opacity: new AnimatedValue(0.0, end: 1.0, curve: easeOut), - child: builder(new RouteArguments(navigator: navigator, previousPerformance: this.performance, nextPerformance: nextRoutePerformance)) + performance: args.previousPerformance, + opacity: new AnimatedValue(0.0, end: 1.0, curve: Curves.easeOut), + child: invokeBuilder(args) ) ); } + + Widget invokeBuilder(RouteArguments args) { + Widget result = _builder(args); + assert(() { + if (result == null) + debugPrint('The builder for route \'$name\' returned null. RouteBuilders must never return null.'); + assert(result != null && 'A RouteBuilder returned null. See the previous log message for details.' is String); + return true; + }); + return result; + } + + String get debugLabel => '${super.debugLabel}($name)'; } class StateRoute extends Route { - StateRoute({ this.route, this.owner, this.callback }); + StateRoute({ this.route, this.owner, this.onPop }); Route route; State owner; - StateRouteCallback callback; + StateRouteCallback onPop; bool get hasContent => false; bool get modal => false; @@ -330,10 +584,10 @@ class StateRoute extends Route { void didPop([dynamic result]) { assert(result == null); - if (callback != null) - callback(this); + if (onPop != null) + onPop(this); super.didPop(result); } - Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance) => null; + Widget build(RouteArguments args) => null; } diff --git a/packages/flutter/lib/src/widgets/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index 614323154a..a517dd5b3f 100644 --- a/packages/flutter/lib/src/widgets/scrollable.dart +++ b/packages/flutter/lib/src/widgets/scrollable.dart @@ -181,7 +181,7 @@ abstract class ScrollableState extends State { dispatchOnScroll(); } - Future scrollTo(double newScrollOffset, { Duration duration, Curve curve: ease }) { + Future scrollTo(double newScrollOffset, { Duration duration, Curve curve: Curves.ease }) { if (newScrollOffset == _scrollOffset) return new Future.value(); @@ -362,12 +362,12 @@ class ScrollableViewportState extends ScrollableState { Widget buildContent(BuildContext context) { return new SizeObserver( - callback: _handleViewportSizeChanged, + onSizeChanged: _handleViewportSizeChanged, child: new Viewport( scrollOffset: scrollOffsetVector, scrollDirection: config.scrollDirection, child: new SizeObserver( - callback: _handleChildSizeChanged, + onSizeChanged: _handleChildSizeChanged, child: config.child ) ) @@ -434,7 +434,6 @@ abstract class ScrollableListPainter extends Painter { double _scrollOffset = 0.0; void set scrollOffset (double value) { assert(value != null); - assert(value >= 0.0 && value <= 1.0); if (_scrollOffset == value) return; _scrollOffset = value; @@ -597,7 +596,7 @@ abstract class ScrollableWidgetListState extends } return new SizeObserver( - callback: _handleSizeChanged, + onSizeChanged: _handleSizeChanged, child: new Container( padding: _crossAxisPadding, child: new HomogeneousViewport( @@ -693,7 +692,7 @@ class PageableList extends ScrollableList { this.onPageChanged, EdgeDims padding, this.duration: const Duration(milliseconds: 200), - this.curve: ease + this.curve: Curves.ease }) : super( key: key, initialScrollOffset: initialPage == null ? null : initialPage * itemExtent, @@ -821,7 +820,7 @@ class ScrollableMixedWidgetListState extends ScrollableState turns; + + Widget buildWithChild(BuildContext context, Widget child) { + performance.updateVariable(turns); + Matrix4 transform = new Matrix4.rotationZ(turns.value * math.PI * 2.0); + return new Transform( + transform: transform, + alignment: const FractionalOffset(0.5, 0.5), + child: child + ); + } +} + class FadeTransition extends TransitionWithChild { FadeTransition({ Key key, @@ -150,6 +177,47 @@ class SquashTransition extends TransitionWithChild { } } +/// An animated variable containing a RelativeRectangle +/// +/// This class specializes the interpolation of AnimatedValue to +/// be appropriate for rectangles that are described in terms of offsets from +/// other rectangles. +class AnimatedRelativeRectValue extends AnimatedValue { + AnimatedRelativeRectValue(RelativeRect begin, { RelativeRect end, Curve curve, Curve reverseCurve }) + : super(begin, end: end, curve: curve, reverseCurve: reverseCurve); + + RelativeRect lerp(double t) => RelativeRect.lerp(begin, end, t); +} + +/// Animated version of [Positioned]. +/// Only works if it's the child of a [Stack]. +class PositionedTransition extends TransitionWithChild { + PositionedTransition({ + Key key, + this.rect, + PerformanceView performance, + Widget child + }) : super(key: key, + performance: performance, + child: child) { + assert(rect != null); + } + + final AnimatedRelativeRectValue rect; + + Widget buildWithChild(BuildContext context, Widget child) { + performance.updateVariable(rect); + return new Positioned( + top: rect.value.top, + right: rect.value.right, + bottom: rect.value.bottom, + left: rect.value.left, + child: child + ); + } +} + + typedef Widget BuilderFunction(BuildContext context); class BuilderTransition extends TransitionComponent { diff --git a/packages/flutter/lib/widgets.dart b/packages/flutter/lib/widgets.dart index 2ecb32b564..a18ebef3d7 100644 --- a/packages/flutter/lib/widgets.dart +++ b/packages/flutter/lib/widgets.dart @@ -11,9 +11,12 @@ export 'src/widgets/binding.dart'; export 'src/widgets/dismissable.dart'; export 'src/widgets/drag_target.dart'; export 'src/widgets/editable_text.dart'; +export 'src/widgets/enter_exit_transition.dart'; export 'src/widgets/focus.dart'; export 'src/widgets/framework.dart'; export 'src/widgets/gesture_detector.dart'; +export 'src/widgets/gridpaper.dart'; +export 'src/widgets/heroes.dart'; export 'src/widgets/homogeneous_viewport.dart'; export 'src/widgets/mimic.dart'; export 'src/widgets/mixed_viewport.dart'; diff --git a/packages/flutter/pubspec.yaml b/packages/flutter/pubspec.yaml index 4ea141a4e7..e80192caad 100644 --- a/packages/flutter/pubspec.yaml +++ b/packages/flutter/pubspec.yaml @@ -1,17 +1,17 @@ name: flutter -version: 0.0.5 +version: 0.0.10 author: Flutter Authors description: A framework for writing Flutter applications homepage: http://flutter.io dependencies: cassowary: '>=0.1.7 <0.2.0' material_design_icons: '>=0.0.3 <0.1.0' - mojo_services: '>=0.3.0 <0.4.0' - mojo: '>=0.2.0 <0.3.0' + mojo_services: 0.4.0 + mojo: 0.3.0 newton: '>=0.1.4 <0.2.0' - sky_engine: 0.0.36 - sky_services: 0.0.36 - sky_tools: '>=0.0.20 <0.1.0' + sky_engine: 0.0.40 + sky_services: 0.0.40 + sky_tools: '>=0.0.25 <0.1.0' vector_math: '>=1.4.3 <2.0.0' intl: '>=0.12.4+2 <0.13.0' environment: diff --git a/packages/flutter_sprites/lib/flutter_sprites.dart b/packages/flutter_sprites/lib/flutter_sprites.dart index 9db7007a29..97b48b3d5d 100644 --- a/packages/flutter_sprites/lib/flutter_sprites.dart +++ b/packages/flutter_sprites/lib/flutter_sprites.dart @@ -35,9 +35,10 @@ part 'src/node_with_size.dart'; part 'src/particle_system.dart'; part 'src/physics_body.dart'; part 'src/physics_debug.dart'; +part 'src/physics_group.dart'; part 'src/physics_joint.dart'; -part 'src/physics_node.dart'; part 'src/physics_shape.dart'; +part 'src/physics_world.dart'; part 'src/sound.dart'; part 'src/sound_manager.dart'; part 'src/sprite.dart'; diff --git a/packages/flutter_sprites/lib/src/node.dart b/packages/flutter_sprites/lib/src/node.dart index e3151585a7..67982bf59c 100644 --- a/packages/flutter_sprites/lib/src/node.dart +++ b/packages/flutter_sprites/lib/src/node.dart @@ -132,9 +132,8 @@ class Node { void set rotation(double rotation) { assert(rotation != null); - if (_physicsBody != null && parent is PhysicsNode) { - PhysicsNode physicsNode = parent; - physicsNode._updateRotation(this.physicsBody, rotation); + if (_physicsBody != null && (parent is PhysicsWorld || parent is PhysicsGroup)) { + _updatePhysicsRotation(physicsBody, rotation, parent); return; } @@ -142,12 +141,35 @@ class Node { invalidateTransformMatrix(); } + void _updatePhysicsRotation(PhysicsBody body, double rotation, Node physicsParent) { + if (physicsParent == null) return; + + if (physicsParent is PhysicsWorld) { + PhysicsWorld world = physicsParent; + world._updateRotation(body, rotation); + } else if (physicsParent is PhysicsGroup) { + _updatePhysicsRotation(body, rotation + physicsParent.rotation, physicsParent.parent); + } else { + assert(false); + } + } + void _setRotationFromPhysics(double rotation) { assert(rotation != null); _rotation = rotation; invalidateTransformMatrix(); } + void teleportRotation(double rotation) { + assert(rotation != null); + if (_physicsBody != null && parent is PhysicsWorld) { + _physicsBody._body.setTransform(_physicsBody._body.position, radians(rotation)); + _physicsBody._body.angularVelocity = 0.0; + _physicsBody._body.setType(box2d.BodyType.STATIC); + } + _setRotationFromPhysics(rotation); + } + /// The position of this node relative to its parent. /// /// myNode.position = new Point(42.0, 42.0); @@ -156,9 +178,8 @@ class Node { void set position(Point position) { assert(position != null); - if (_physicsBody != null && parent is PhysicsNode) { - PhysicsNode physicsNode = parent; - physicsNode._updatePosition(this.physicsBody, position); + if (_physicsBody != null && (parent is PhysicsWorld || parent is PhysicsGroup)) { + _updatePhysicsPosition(this.physicsBody, position, parent); return; } @@ -166,12 +187,43 @@ class Node { invalidateTransformMatrix(); } + void _updatePhysicsPosition(PhysicsBody body, Point position, Node physicsParent) { + if (physicsParent == null) return; + + if (physicsParent is PhysicsWorld) { + PhysicsWorld world = physicsParent; + world._updatePosition(body, position); + } else if (physicsParent is PhysicsGroup) { + Vector4 parentPos = physicsParent.transformMatrix.transform(new Vector4(position.x, position.y, 0.0, 1.0)); + _updatePhysicsPosition(body, new Point(parentPos.x, parentPos.y), physicsParent.parent); + } else { + assert(false); + } + } + void _setPositionFromPhysics(Point position) { assert(position != null); _position = position; invalidateTransformMatrix(); } + void teleportPosition(Point position) { + assert(position != null); + if (_physicsBody != null && parent is PhysicsWorld) { + PhysicsWorld physicsNode = parent; + _physicsBody._body.setTransform( + new Vector2( + position.x / physicsNode.b2WorldToNodeConversionFactor, + position.y / physicsNode.b2WorldToNodeConversionFactor + ), + _physicsBody._body.getAngle() + ); + _physicsBody._body.linearVelocity = new Vector2.zero(); + _physicsBody._body.setType(box2d.BodyType.STATIC); + } + _setPositionFromPhysics(position); + } + /// The skew along the x-axis of this node in degrees. /// /// myNode.skewX = 45.0; @@ -224,10 +276,28 @@ class Node { void set scale(double scale) { assert(scale != null); + + if (_physicsBody != null && (parent is PhysicsWorld || parent is PhysicsGroup)) { + _updatePhysicsScale(physicsBody, scale, parent); + } + _scaleX = _scaleY = scale; invalidateTransformMatrix(); } + void _updatePhysicsScale(PhysicsBody body, double scale, Node physicsParent) { + if (physicsParent == null) return; + + if (physicsParent is PhysicsWorld) { + PhysicsWorld world = physicsParent; + world._updateScale(body, scale); + } else if (physicsParent is PhysicsGroup) { + _updatePhysicsScale(body, scale * physicsParent.scale, physicsParent.parent); + } else { + assert(false); + } + } + /// The horizontal scale of this node relative its parent. /// /// myNode.scaleX = 5.0; @@ -235,6 +305,8 @@ class Node { void set scaleX(double scaleX) { assert(scaleX != null); + assert(physicsBody == null); + _scaleX = scaleX; invalidateTransformMatrix(); } @@ -246,6 +318,8 @@ class Node { void set scaleY(double scaleY) { assert(scaleY != null); + assert(physicsBody == null); + _scaleY = scaleY; invalidateTransformMatrix(); } @@ -273,6 +347,7 @@ class Node { void addChild(Node child) { assert(child != null); assert(child._parent == null); + assert(!(child is PhysicsGroup) || this is PhysicsGroup || this is PhysicsWorld); _childrenNeedSorting = true; _children.add(child); @@ -281,6 +356,10 @@ class Node { _childrenLastAddedOrder += 1; child._addedOrder = _childrenLastAddedOrder; if (_spriteBox != null) _spriteBox._registerNode(child); + + if (child is PhysicsGroup) { + child._attachGroup(child, child._world); + } } /// Removes a child from this node. @@ -293,6 +372,10 @@ class Node { child._spriteBox = null; if (_spriteBox != null) _spriteBox._deregisterNode(child); } + + if (child is PhysicsGroup) { + child._detachGroup(child); + } } /// Removes this node from its parent node. @@ -644,7 +727,7 @@ class Node { set physicsBody(PhysicsBody physicsBody) { if (parent != null) { - assert(parent is PhysicsNode); + assert(parent is PhysicsWorld); if (physicsBody == null) { physicsBody._detach(); diff --git a/packages/flutter_sprites/lib/src/particle_system.dart b/packages/flutter_sprites/lib/src/particle_system.dart index c3b256dc14..c3760dae09 100644 --- a/packages/flutter_sprites/lib/src/particle_system.dart +++ b/packages/flutter_sprites/lib/src/particle_system.dart @@ -363,7 +363,7 @@ class ParticleSystem extends Node { List rects = []; List colors = []; - _paint.setTransferMode(transferMode); + _paint.transferMode = transferMode; for (_Particle particle in _particles) { // Rect diff --git a/packages/flutter_sprites/lib/src/physics_body.dart b/packages/flutter_sprites/lib/src/physics_body.dart index 0517d7b702..98f71b47a1 100644 --- a/packages/flutter_sprites/lib/src/physics_body.dart +++ b/packages/flutter_sprites/lib/src/physics_body.dart @@ -40,6 +40,13 @@ class PhysicsBody { this.active = active; } + Vector2 _lastPosition; + double _lastRotation; + Vector2 _targetPosition; + double _targetAngle; + + double _scale; + Object tag; final PhysicsShape shape; @@ -225,7 +232,7 @@ class PhysicsBody { double gravityScale; - PhysicsNode _physicsNode; + PhysicsWorld _physicsNode; Node _node; box2d.Body _body; @@ -286,9 +293,12 @@ class PhysicsBody { _body.applyAngularImpulse(impulse / _physicsNode.b2WorldToNodeConversionFactor); } - void _attach(PhysicsNode physicsNode, Node node) { + void _attach(PhysicsWorld physicsNode, Node node) { assert(_attached == false); + // Update scale + _scale = node.scale; + // Create BodyDef box2d.BodyDef bodyDef = new box2d.BodyDef(); bodyDef.linearVelocity = new Vector2(linearVelocity.dx, linearVelocity.dy); @@ -313,6 +323,24 @@ class PhysicsBody { // Create Body _body = physicsNode.b2World.createBody(bodyDef); + _createFixtures(physicsNode); + + _body.userData = this; + + _physicsNode = physicsNode; + _node = node; + + _attached = true; + + // Attach any joints + for (PhysicsJoint joint in _joints) { + if (joint.bodyA._attached && joint.bodyB._attached) { + joint._attach(physicsNode); + } + } + } + + void _createFixtures(PhysicsWorld physicsNode) { // Create FixtureDef box2d.FixtureDef fixtureDef = new box2d.FixtureDef(); fixtureDef.friction = friction; @@ -334,19 +362,6 @@ class PhysicsBody { box2d.Fixture fixture = _body.createFixtureFromFixtureDef(fixtureDef); fixture.userData = physicsShape; } - _body.userData = this; - - _physicsNode = physicsNode; - _node = node; - - _attached = true; - - // Attach any joints - for (PhysicsJoint joint in _joints) { - if (joint.bodyA._attached && joint.bodyB._attached) { - joint._attach(physicsNode); - } - } } void _detach() { @@ -356,13 +371,26 @@ class PhysicsBody { } } - void _addB2Shapes(PhysicsNode physicsNode, PhysicsShape shape, List b2Shapes, List physicsShapes) { + void _updateScale(PhysicsWorld physicsNode) { + // Destroy old fixtures + for (box2d.Fixture fixture = _body.getFixtureList(); fixture != null; fixture = fixture.getNext()) { + _body.destroyFixture(fixture); + } + + // Make sure we create new b2Shapes + shape._invalidate(); + + // Create new fixtures + _createFixtures(physicsNode); + } + + void _addB2Shapes(PhysicsWorld physicsNode, PhysicsShape shape, List b2Shapes, List physicsShapes) { if (shape is PhysicsShapeGroup) { for (PhysicsShape child in shape.shapes) { _addB2Shapes(physicsNode, child, b2Shapes, physicsShapes); } } else { - b2Shapes.add(shape.getB2Shape(physicsNode)); + b2Shapes.add(shape.getB2Shape(physicsNode, _scale)); physicsShapes.add(shape); } } diff --git a/packages/flutter_sprites/lib/src/physics_debug.dart b/packages/flutter_sprites/lib/src/physics_debug.dart index 30f877c929..acf77294fa 100644 --- a/packages/flutter_sprites/lib/src/physics_debug.dart +++ b/packages/flutter_sprites/lib/src/physics_debug.dart @@ -12,7 +12,7 @@ class _PhysicsDebugDraw extends box2d.DebugDraw { ); } - PhysicsNode physicsNode; + PhysicsWorld physicsNode; PaintingCanvas canvas; @@ -43,7 +43,7 @@ class _PhysicsDebugDraw extends box2d.DebugDraw { void drawCircle(Vector2 center, num radius, box2d.Color3i color, [Vector2 axis]) { Paint paint = new Paint() ..color = _toColor(color) - ..setStyle(ui.PaintingStyle.stroke) + ..style = ui.PaintingStyle.stroke ..strokeWidth = 1.0; canvas.drawCircle(_toPoint(center), _scale(radius), paint); diff --git a/packages/flutter_sprites/lib/src/physics_group.dart b/packages/flutter_sprites/lib/src/physics_group.dart new file mode 100644 index 0000000000..b858a8eda0 --- /dev/null +++ b/packages/flutter_sprites/lib/src/physics_group.dart @@ -0,0 +1,107 @@ +part of flutter_sprites; + +class PhysicsGroup extends Node { + + set scaleX(double scaleX) { + assert(false); + } + + set scaleY(double scaleX) { + assert(false); + } + + set skewX(double scaleX) { + assert(false); + } + + set skewY(double scaleX) { + assert(false); + } + + set physicsBody(PhysicsBody body) { + assert(false); + } + + set position(Point position) { + super.position = position; + _invalidatePhysicsBodies(this); + } + + set rotation(double rotation) { + super.rotation = rotation; + _invalidatePhysicsBodies(this); + } + + set scale(double scale) { + super.scale = scale; + _invalidatePhysicsBodies(this); + } + + void _invalidatePhysicsBodies(Node node) { + if (_world == null) return; + + if (node.physicsBody != null) { + // TODO: Add to list + _world._bodiesScheduledForUpdate.add(node.physicsBody); + } + + for (Node child in node.children) { + _invalidatePhysicsBodies(child); + } + } + + void addChild(Node node) { + super.addChild(node); + + PhysicsWorld world = _world; + if (node.physicsBody != null && world != null) { + node.physicsBody._attach(world, node); + } + + if (node is PhysicsGroup) { + _attachGroup(this, world); + } + } + + void _attachGroup(PhysicsGroup group, PhysicsWorld world) { + for (Node child in group.children) { + if (child is PhysicsGroup) { + _attachGroup(child, world); + } else if (child.physicsBody != null) { + child.physicsBody._attach(world, child); + } + } + } + + void removeChild(Node node) { + super.removeChild(node); + + if (node.physicsBody != null) { + node.physicsBody._detach(); + } + + if (node is PhysicsGroup) { + _detachGroup(this); + } + } + + void _detachGroup(PhysicsGroup group) { + for (Node child in group.children) { + if (child is PhysicsGroup) { + _detachGroup(child); + } else if (child.physicsBody != null) { + child.physicsBody._detach(); + } + } + } + + PhysicsWorld get _world { + if (this.parent is PhysicsWorld) + return this.parent; + if (this.parent is PhysicsGroup) { + PhysicsGroup group = this.parent; + return group._world; + } + return null; + } +} diff --git a/packages/flutter_sprites/lib/src/physics_joint.dart b/packages/flutter_sprites/lib/src/physics_joint.dart index 262bb227c9..a0425bb4b8 100644 --- a/packages/flutter_sprites/lib/src/physics_joint.dart +++ b/packages/flutter_sprites/lib/src/physics_joint.dart @@ -23,7 +23,7 @@ abstract class PhysicsJoint { bool _active = true; box2d.Joint _joint; - PhysicsNode _physicsNode; + PhysicsWorld _physicsNode; void _completeCreation() { if (bodyA._attached && bodyB._attached) { @@ -31,7 +31,7 @@ abstract class PhysicsJoint { } } - void _attach(PhysicsNode physicsNode) { + void _attach(PhysicsWorld physicsNode) { if (_joint == null) { _physicsNode = physicsNode; _joint = _createB2Joint(physicsNode); @@ -48,7 +48,7 @@ abstract class PhysicsJoint { _active = false; } - box2d.Joint _createB2Joint(PhysicsNode physicsNode); + box2d.Joint _createB2Joint(PhysicsWorld physicsNode); void destroy() { _detach(); @@ -92,7 +92,7 @@ class PhysicsJointRevolute extends PhysicsJoint { final double upperAngle; final bool enableLimit; - box2d.Joint _createB2Joint(PhysicsNode physicsNode) { + box2d.Joint _createB2Joint(PhysicsWorld physicsNode) { // Create Joint Definition Vector2 vecAnchor = new Vector2( _worldAnchor.x / physicsNode.b2WorldToNodeConversionFactor, @@ -124,7 +124,7 @@ class PhysicsJointPrismatic extends PhysicsJoint { Offset axis; - box2d.Joint _createB2Joint(PhysicsNode physicsNode) { + box2d.Joint _createB2Joint(PhysicsWorld physicsNode) { box2d.PrismaticJointDef b2Def = new box2d.PrismaticJointDef(); b2Def.initialize(bodyA._body, bodyB._body, bodyA._body.position, new Vector2(axis.dx, axis.dy)); return physicsNode.b2World.createJoint(b2Def); @@ -147,7 +147,7 @@ class PhysicsJointWeld extends PhysicsJoint { final double dampening; final double frequency; - box2d.Joint _createB2Joint(PhysicsNode physicsNode) { + box2d.Joint _createB2Joint(PhysicsWorld physicsNode) { box2d.WeldJointDef b2Def = new box2d.WeldJointDef(); Vector2 middle = new Vector2( (bodyA._body.position.x + bodyB._body.position.x) / 2.0, @@ -182,7 +182,7 @@ class PhysicsJointPulley extends PhysicsJoint { final Point anchorB; final double ratio; - box2d.Joint _createB2Joint(PhysicsNode physicsNode) { + box2d.Joint _createB2Joint(PhysicsWorld physicsNode) { box2d.PulleyJointDef b2Def = new box2d.PulleyJointDef(); b2Def.initialize( bodyA._body, @@ -211,7 +211,7 @@ class PhysicsJointGear extends PhysicsJoint { final double ratio; - box2d.Joint _createB2Joint(PhysicsNode physicsNode) { + box2d.Joint _createB2Joint(PhysicsWorld physicsNode) { box2d.GearJointDef b2Def = new box2d.GearJointDef(); b2Def.bodyA = bodyA._body; b2Def.bodyB = bodyB._body; @@ -243,7 +243,7 @@ class PhysicsJointDistance extends PhysicsJoint { final double dampening; final double frequency; - box2d.Joint _createB2Joint(PhysicsNode physicsNode) { + box2d.Joint _createB2Joint(PhysicsWorld physicsNode) { box2d.DistanceJointDef b2Def = new box2d.DistanceJointDef(); b2Def.initialize( bodyA._body, @@ -280,7 +280,7 @@ class PhysicsJointWheel extends PhysicsJoint { final double dampening; final double frequency; - box2d.Joint _createB2Joint(PhysicsNode physicsNode) { + box2d.Joint _createB2Joint(PhysicsWorld physicsNode) { box2d.WheelJointDef b2Def = new box2d.WheelJointDef(); b2Def.initialize( bodyA._body, @@ -313,7 +313,7 @@ class PhysicsJointFriction extends PhysicsJoint { final double maxForce; final double maxTorque; - box2d.Joint _createB2Joint(PhysicsNode physicsNode) { + box2d.Joint _createB2Joint(PhysicsWorld physicsNode) { box2d.FrictionJointDef b2Def = new box2d.FrictionJointDef(); b2Def.initialize( bodyA._body, @@ -345,7 +345,7 @@ class PhysicsJointConstantVolume extends PhysicsJoint { final double dampening; final double frequency; - box2d.Joint _createB2Joint(PhysicsNode physicsNode) { + box2d.Joint _createB2Joint(PhysicsWorld physicsNode) { box2d.ConstantVolumeJointDef b2Def = new box2d.ConstantVolumeJointDef(); for (PhysicsBody body in bodies) { b2Def.addBody(body._body); @@ -356,7 +356,7 @@ class PhysicsJointConstantVolume extends PhysicsJoint { } } -Vector2 _convertPosToVec(Point pt, PhysicsNode physicsNode) { +Vector2 _convertPosToVec(Point pt, PhysicsWorld physicsNode) { return new Vector2( pt.x / physicsNode.b2WorldToNodeConversionFactor, pt.y / physicsNode.b2WorldToNodeConversionFactor diff --git a/packages/flutter_sprites/lib/src/physics_shape.dart b/packages/flutter_sprites/lib/src/physics_shape.dart index 2669aeb2be..de0eca029e 100644 --- a/packages/flutter_sprites/lib/src/physics_shape.dart +++ b/packages/flutter_sprites/lib/src/physics_shape.dart @@ -6,14 +6,18 @@ abstract class PhysicsShape { Object userObject; - box2d.Shape getB2Shape(PhysicsNode node) { + box2d.Shape getB2Shape(PhysicsWorld node, double scale) { if (_b2Shape == null) { - _b2Shape = _createB2Shape(node); + _b2Shape = _createB2Shape(node, scale); } return _b2Shape; } - box2d.Shape _createB2Shape(PhysicsNode node); + box2d.Shape _createB2Shape(PhysicsWorld node, double scale); + + void _invalidate() { + _b2Shape = null; + } } class PhysicsShapeCircle extends PhysicsShape { @@ -22,11 +26,11 @@ class PhysicsShapeCircle extends PhysicsShape { final Point point; final double radius; - box2d.Shape _createB2Shape(PhysicsNode node) { + box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { box2d.CircleShape shape = new box2d.CircleShape(); - shape.p.x = point.x / node.b2WorldToNodeConversionFactor; - shape.p.y = point.y / node.b2WorldToNodeConversionFactor; - shape.radius = radius / node.b2WorldToNodeConversionFactor; + shape.p.x = scale * point.x / node.b2WorldToNodeConversionFactor; + shape.p.y = scale * point.y / node.b2WorldToNodeConversionFactor; + shape.radius = scale * radius / node.b2WorldToNodeConversionFactor; return shape; } } @@ -36,12 +40,12 @@ class PhysicsShapePolygon extends PhysicsShape { final List points; - box2d.Shape _createB2Shape(PhysicsNode node) { + box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { List vectors = []; for (Point point in points) { Vector2 vec = new Vector2( - point.x / node.b2WorldToNodeConversionFactor, - point.y / node.b2WorldToNodeConversionFactor + scale * point.x / node.b2WorldToNodeConversionFactor, + scale * point.y / node.b2WorldToNodeConversionFactor ); vectors.add(vec); } @@ -65,14 +69,14 @@ class PhysicsShapeBox extends PhysicsShape { final Point center; final double rotation; - box2d.Shape _createB2Shape(PhysicsNode node) { + box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { box2d.PolygonShape shape = new box2d.PolygonShape(); shape.setAsBox( - width / node.b2WorldToNodeConversionFactor, - height / node.b2WorldToNodeConversionFactor, + scale * width / node.b2WorldToNodeConversionFactor, + scale * height / node.b2WorldToNodeConversionFactor, new Vector2( - center.x / node.b2WorldToNodeConversionFactor, - center.y / node.b2WorldToNodeConversionFactor + scale * center.x / node.b2WorldToNodeConversionFactor, + scale * center.y / node.b2WorldToNodeConversionFactor ), radians(rotation) ); @@ -86,12 +90,12 @@ class PhysicsShapeChain extends PhysicsShape { final List points; final bool loop; - box2d.Shape _createB2Shape(PhysicsNode node) { + box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { List vectors = []; for (Point point in points) { Vector2 vec = new Vector2( - point.x / node.b2WorldToNodeConversionFactor, - point.y / node.b2WorldToNodeConversionFactor + scale * point.x / node.b2WorldToNodeConversionFactor, + scale * point.y / node.b2WorldToNodeConversionFactor ); vectors.add(vec); } @@ -111,16 +115,16 @@ class PhysicsShapeEdge extends PhysicsShape { final Point pointA; final Point pointB; - box2d.Shape _createB2Shape(PhysicsNode node) { + box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { box2d.EdgeShape shape = new box2d.EdgeShape(); shape.set( new Vector2( - pointA.x / node.b2WorldToNodeConversionFactor, - pointA.y / node.b2WorldToNodeConversionFactor + scale * pointA.x / node.b2WorldToNodeConversionFactor, + scale * pointA.y / node.b2WorldToNodeConversionFactor ), new Vector2( - pointB.x / node.b2WorldToNodeConversionFactor, - pointB.y / node.b2WorldToNodeConversionFactor + scale * pointB.x / node.b2WorldToNodeConversionFactor, + scale * pointB.y / node.b2WorldToNodeConversionFactor ) ); return shape; @@ -133,7 +137,13 @@ class PhysicsShapeGroup extends PhysicsShape { final List shapes; - box2d.Shape _createB2Shape(PhysicsNode node) { + box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { return null; } + + void _invalidate() { + for (PhysicsShape shape in shapes) { + shape._invalidate(); + } + } } diff --git a/packages/flutter_sprites/lib/src/physics_node.dart b/packages/flutter_sprites/lib/src/physics_world.dart similarity index 77% rename from packages/flutter_sprites/lib/src/physics_node.dart rename to packages/flutter_sprites/lib/src/physics_world.dart index f95bb2df5a..fd27e95bcc 100644 --- a/packages/flutter_sprites/lib/src/physics_node.dart +++ b/packages/flutter_sprites/lib/src/physics_world.dart @@ -9,8 +9,8 @@ enum PhysicsContactType { typedef void PhysicsContactCallback(PhysicsContactType type, PhysicsContact contact); -class PhysicsNode extends Node { - PhysicsNode(Offset gravity) { +class PhysicsWorld extends Node { + PhysicsWorld(Offset gravity) { b2World = new box2d.World.withGravity( new Vector2( gravity.dx / b2WorldToNodeConversionFactor, @@ -18,7 +18,7 @@ class PhysicsNode extends Node { _init(); } - PhysicsNode.fromB2World(this.b2World, this.b2WorldToNodeConversionFactor) { + PhysicsWorld.fromB2World(this.b2World, this.b2WorldToNodeConversionFactor) { _init(); } @@ -43,6 +43,8 @@ class PhysicsNode extends Node { List _bodiesScheduledForDestruction = []; + List _bodiesScheduledForUpdate = []; + _PhysicsDebugDraw _debugDraw; double b2WorldToNodeConversionFactor = 10.0; @@ -71,9 +73,48 @@ class PhysicsNode extends Node { } void _stepPhysics(double dt) { + // Update transformations of bodies whose groups have moved + for (PhysicsBody body in _bodiesScheduledForUpdate) { + Node node = body._node; + node._updatePhysicsPosition(body, node.position, node.parent); + node._updatePhysicsRotation(body, node.rotation, node.parent); + } + _bodiesScheduledForUpdate.clear(); + // Remove bodies that were marked for destruction during the update phase _removeBodiesScheduledForDestruction(); + // Assign velocities and momentum to static and kinetic bodies + for (box2d.Body b2Body = b2World.bodyList; b2Body != null; b2Body = b2Body.getNext()) { + // Fetch body + PhysicsBody body = b2Body.userData; + + // Skip all dynamic bodies + if (b2Body.getType() == box2d.BodyType.DYNAMIC) { + body._lastPosition = null; + body._lastRotation = null; + continue; + } + + // Update linear velocity + if (body._lastPosition == null) { + b2Body.linearVelocity.setZero(); + } else { + Vector2 velocity = (body._targetPosition - body._lastPosition) / dt; + b2Body.linearVelocity = velocity; + body._lastPosition = null; + } + + // Update angular velocity + if (body._lastRotation == null) { + b2Body.angularVelocity = 0.0; + } else { + double angularVelocity = (body._targetAngle - body._lastRotation) / dt; + b2Body.angularVelocity = angularVelocity; + body._lastRotation = 0.0; + } + } + // Calculate a step in the simulation b2World.stepDt(dt, 10, 10); @@ -81,6 +122,13 @@ class PhysicsNode extends Node { for (box2d.Body b2Body = b2World.bodyList; b2Body != null; b2Body = b2Body.getNext()) { // Update visual position and rotation PhysicsBody body = b2Body.userData; + + if (b2Body.getType() == box2d.BodyType.KINEMATIC) { + body._targetPosition = null; + body._targetAngle = null; + } + + // Update visual position and rotation body._node._setPositionFromPhysics(new Point( b2Body.position.x * b2WorldToNodeConversionFactor, b2Body.position.y * b2WorldToNodeConversionFactor @@ -113,22 +161,44 @@ class PhysicsNode extends Node { } void _updatePosition(PhysicsBody body, Point position) { + if (body._lastPosition == null && body.type == PhysicsBodyType.static) { + body._lastPosition = new Vector2.copy(body._body.position); + body._body.setType(box2d.BodyType.KINEMATIC); + } + Vector2 newPos = new Vector2( position.x / b2WorldToNodeConversionFactor, position.y / b2WorldToNodeConversionFactor ); double angle = body._body.getAngle(); - body._body.setTransform(newPos, angle); + + if (body.type == PhysicsBodyType.dynamic) { + body._body.setTransform(newPos, angle); + } else { + body._targetPosition = newPos; + body._targetAngle = angle; + } body._body.setAwake(true); } void _updateRotation(PhysicsBody body, double rotation) { + if (body._lastRotation == null) + body._lastRotation = body._body.getAngle(); + Vector2 pos = body._body.position; double newAngle = radians(rotation); body._body.setTransform(pos, newAngle); body._body.setAwake(true); } + void _updateScale(PhysicsBody body, double scale) { + body._scale = scale; + + if (body._attached) { + body._updateScale(this); + } + } + void addChild(Node node) { super.addChild(node); if (node.physicsBody != null) { @@ -192,7 +262,7 @@ class _ContactCallbackInfo { class _ContactHandler extends box2d.ContactListener { _ContactHandler(this.physicsNode); - PhysicsNode physicsNode; + PhysicsWorld physicsNode; List<_ContactCallbackInfo> callbackInfos = []; diff --git a/packages/flutter_sprites/lib/src/sprite.dart b/packages/flutter_sprites/lib/src/sprite.dart index 3a532f42dc..1bc818ab8c 100644 --- a/packages/flutter_sprites/lib/src/sprite.dart +++ b/packages/flutter_sprites/lib/src/sprite.dart @@ -113,7 +113,7 @@ abstract class SpritePaint { paint.color = new Color.fromARGB((255.0*_opacity).toInt(), 255, 255, 255); if (colorOverlay != null) { - paint.colorFilter = new ui.ColorFilter.mode(colorOverlay, ui.TransferMode.srcATop); + paint.colorFilter = new ColorFilter.mode(colorOverlay, ui.TransferMode.srcATop); } if (transferMode != null) { diff --git a/packages/flutter_sprites/lib/src/sprite_box.dart b/packages/flutter_sprites/lib/src/sprite_box.dart index 356b48b1d9..be59130bc7 100644 --- a/packages/flutter_sprites/lib/src/sprite_box.dart +++ b/packages/flutter_sprites/lib/src/sprite_box.dart @@ -78,7 +78,7 @@ class SpriteBox extends RenderBox { List _constrainedNodes; - List _physicsNodes; + List _physicsNodes; Rect _visibleArea; @@ -400,7 +400,7 @@ class SpriteBox extends RenderBox { void _addActionControllersAndPhysicsNodes(Node node) { if (node._actions != null) _actionControllers.add(node._actions); - if (node is PhysicsNode) _physicsNodes.add(node); + if (node is PhysicsWorld) _physicsNodes.add(node); for (int i = node.children.length - 1; i >= 0; i--) { Node child = node.children[i]; @@ -422,7 +422,7 @@ class SpriteBox extends RenderBox { if (_physicsNodes == null) _rebuildActionControllersAndPhysicsNodes(); - for (PhysicsNode physicsNode in _physicsNodes) { + for (PhysicsWorld physicsNode in _physicsNodes) { physicsNode._stepPhysics(dt); } } diff --git a/packages/flutter_sprites/lib/src/textured_line.dart b/packages/flutter_sprites/lib/src/textured_line.dart index 3bf96404ce..dd530c7b92 100644 --- a/packages/flutter_sprites/lib/src/textured_line.dart +++ b/packages/flutter_sprites/lib/src/textured_line.dart @@ -41,8 +41,8 @@ class TexturedLinePainter { ui.ImageShader shader = new ui.ImageShader(texture.image, ui.TileMode.repeated, ui.TileMode.repeated, matrix.storage); - _cachedPaint = new Paint(); - _cachedPaint.setShader(shader); + _cachedPaint = new Paint() + ..shader = shader; } } diff --git a/packages/flutter_sprites/lib/src/virtual_joystick.dart b/packages/flutter_sprites/lib/src/virtual_joystick.dart index c08495e440..4e455d5b59 100644 --- a/packages/flutter_sprites/lib/src/virtual_joystick.dart +++ b/packages/flutter_sprites/lib/src/virtual_joystick.dart @@ -14,7 +14,7 @@ class VirtualJoystick extends NodeWithSize { _paintControl = new Paint() ..color=new Color(0xffffffff) ..strokeWidth = 1.0 - ..setStyle(ui.PaintingStyle.stroke); + ..style = ui.PaintingStyle.stroke; } Point _value = Point.origin; diff --git a/packages/flutter_sprites/pubspec.yaml b/packages/flutter_sprites/pubspec.yaml index b1afc598c5..dfb89c8def 100644 --- a/packages/flutter_sprites/pubspec.yaml +++ b/packages/flutter_sprites/pubspec.yaml @@ -1,9 +1,9 @@ name: flutter_sprites description: A sprite toolkit built on top of Flutter -version: 0.0.3 +version: 0.0.7 author: Flutter Authors homepage: http://flutter.io dependencies: - flutter: ">=0.0.5 <0.1.0" + flutter: ">=0.0.10 <0.1.0" sky_tools: ">=0.0.20 <0.1.0" box2d: ">=0.2.0 <0.3.0" diff --git a/packages/flx/lib/bundle.dart b/packages/flx/lib/bundle.dart new file mode 100644 index 0000000000..9e72a25921 --- /dev/null +++ b/packages/flx/lib/bundle.dart @@ -0,0 +1,75 @@ +// 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:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +const String kBundleMagic = '#!mojo '; + +Future> _readBytesWithLength(RandomAccessFile file) async { + ByteData buffer = new ByteData(4); + await file.readInto(buffer.buffer.asUint8List()); + int length = buffer.getUint32(0, Endianness.LITTLE_ENDIAN); + return await file.read(length); +} + +const int kMaxLineLen = 10*1024; +const int kNewline = 0x0A; +Future _readLine(RandomAccessFile file) async { + String line = ''; + while (line.length < kMaxLineLen) { + int byte = await file.readByte(); + if (byte == -1 || byte == kNewline) + break; + line += new String.fromCharCode(byte); + } + return line; +} + +// Represents a parsed .flx Bundle. Contains information from the bundle's +// header, as well as an open File handle positioned where the zip content +// begins. +// The bundle format is: +// #!mojo \n +// <32-bit length> +// <32-bit length> +// +// +// The manifest is a JSON string containing the following keys: +// (optional) name: the name of the package. +// version: the package version. +// update-url: the base URL to download a new manifest and bundle. +// key: a BASE-64 encoded DER-encoded ASN.1 representation of the Q point of the +// ECDSA public key that was used to sign this manifest. +// content-hash: an integer SHA-256 hash value of the . +class Bundle { + Bundle(this.path); + + final String path; + List signatureBytes; + List manifestBytes; + Map manifest; + RandomAccessFile content; + + Future _readHeader() async { + content = await new File(path).open(); + String magic = await _readLine(content); + if (!magic.startsWith(kBundleMagic)) + return false; + signatureBytes = await _readBytesWithLength(content); + manifestBytes = await _readBytesWithLength(content); + String manifestString = UTF8.decode(manifestBytes); + manifest = JSON.decode(manifestString); + return true; + } + + static Future readHeader(String path) async { + Bundle bundle = new Bundle(path); + if (!await bundle._readHeader()) + return null; + return bundle; + } +} diff --git a/packages/flx/lib/signing.dart b/packages/flx/lib/signing.dart new file mode 100644 index 0000000000..d3390a6d59 --- /dev/null +++ b/packages/flx/lib/signing.dart @@ -0,0 +1,94 @@ +// 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:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:asn1lib/asn1lib.dart'; +import 'package:bignum/bignum.dart'; +import 'package:cipher/cipher.dart'; + +// The ECDSA algorithm parameters we're using. These match the parameters used +// by the Flutter updater package. +final ECDomainParameters _ecDomain = new ECDomainParameters('prime256v1'); +final String kSignerAlgorithm = 'SHA-256/ECDSA'; +final String kHashAlgorithm = 'SHA-256'; + +final SecureRandom _random = _initRandom(); + +SecureRandom _initRandom() { + // TODO(mpcomplete): Provide a better seed here. External entropy source? + final Uint8List key = new Uint8List(16); + final KeyParameter keyParam = new KeyParameter(key); + final ParametersWithIV params = new ParametersWithIV(keyParam, new Uint8List(16)); + SecureRandom random = new SecureRandom('AES/CTR/AUTO-SEED-PRNG') + ..seed(params); + return random; +} + +// Returns a serialized manifest, with the public key and hash of the content +// included. +Uint8List serializeManifest(Map manifestDescriptor, ECPublicKey publicKey, Uint8List zipBytes) { + if (manifestDescriptor == null) + return null; + final List kSavedKeys = [ + 'name', + 'version', + 'update-url' + ]; + Map outputManifest = new Map(); + manifestDescriptor.forEach((key, value) { + if (kSavedKeys.contains(key)) + outputManifest[key] = value; + }); + + if (publicKey != null) + outputManifest['key'] = BASE64.encode(publicKey.Q.getEncoded()); + + Uint8List zipHash = new Digest(kHashAlgorithm).process(zipBytes); + BigInteger zipHashInt = new BigInteger.fromBytes(1, zipHash); + outputManifest['content-hash'] = zipHashInt.intValue(); + + return new Uint8List.fromList(UTF8.encode(JSON.encode(outputManifest))); +} + +// Returns the ASN.1 encoded signature of the input manifestBytes. +List signManifest(Uint8List manifestBytes, ECPrivateKey privateKey) { + if (manifestBytes == null || privateKey == null) + return []; + Signer signer = new Signer(kSignerAlgorithm); + PrivateKeyParameter params = new PrivateKeyParameter(privateKey); + signer.init(true, new ParametersWithRandom(params, _random)); + ECSignature signature = signer.generateSignature(manifestBytes); + ASN1Sequence asn1 = new ASN1Sequence() + ..add(new ASN1Integer(signature.r)) + ..add(new ASN1Integer(signature.s)); + return asn1.encodedBytes; +} + +ECPrivateKey _asn1ParsePrivateKey(ECDomainParameters ecDomain, Uint8List privateKey) { + ASN1Parser parser = new ASN1Parser(privateKey); + ASN1Sequence seq = parser.nextObject(); + assert(seq.elements.length >= 2); + ASN1OctetString keyOct = seq.elements[1]; + BigInteger d = new BigInteger.fromBytes(1, keyOct.octets); + return new ECPrivateKey(d, ecDomain); +} + +Future loadPrivateKey(String privateKeyPath) async { + File file = new File(privateKeyPath); + if (!file.existsSync()) + return null; + List bytes = file.readAsBytesSync(); + return _asn1ParsePrivateKey(_ecDomain, new Uint8List.fromList(bytes)); +} + +ECPublicKey publicKeyFromPrivateKey(ECPrivateKey privateKey) { + if (privateKey == null) + return null; + ECPoint Q = privateKey.parameters.G * privateKey.d; + return new ECPublicKey(Q, privateKey.parameters); +} diff --git a/packages/flx/pubspec.yaml b/packages/flx/pubspec.yaml new file mode 100644 index 0000000000..323cd8c5cd --- /dev/null +++ b/packages/flx/pubspec.yaml @@ -0,0 +1,13 @@ +name: flx +version: 0.0.1 +author: Flutter Authors +description: Library for dealing with Flutter bundle (.flx) files +homepage: http://flutter.io +dependencies: + sky_services: 0.0.38 + yaml: ^2.1.3 + asn1lib: ^0.4.1 + cipher: ^0.7.1 + path: ^1.3.0 +environment: + sdk: '>=1.12.0 <2.0.0' diff --git a/packages/unit/test/rendering/offstage_test.dart b/packages/unit/test/rendering/offstage_test.dart new file mode 100644 index 0000000000..76b16f90dd --- /dev/null +++ b/packages/unit/test/rendering/offstage_test.dart @@ -0,0 +1,32 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:test/test.dart'; + +import 'rendering_tester.dart'; + +void main() { + test("offstage", () { + RenderBox child; + bool painted = false; + // viewport incoming constraints are tight 800x600 + // viewport is vertical by default + RenderBox root = new RenderViewport( + child: new RenderOffStage( + child: new RenderCustomPaint( + child: child = new RenderConstrainedBox( + additionalConstraints: new BoxConstraints.tightFor(height: 10.0, width: 10.0) + ), + onPaint: (PaintingCanvas canvas, Size size) { + painted = true; + } + ) + ) + ); + expect(child.hasSize, isFalse); + expect(painted, isFalse); + layout(root, phase: EnginePhase.paint); + expect(child.hasSize, isTrue); + expect(painted, isFalse); + expect(child.size, equals(const Size(800.0, 10.0))); + }); +} diff --git a/packages/unit/test/rendering/overflow_test.dart b/packages/unit/test/rendering/overflow_test.dart new file mode 100644 index 0000000000..2528f589dd --- /dev/null +++ b/packages/unit/test/rendering/overflow_test.dart @@ -0,0 +1,42 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:test/test.dart'; + +import 'rendering_tester.dart'; + +void main() { + test("overflow should not affect baseline", () { + RenderBox root, child, text; + double baseline1, baseline2, height1, height2; + + root = new RenderPositionedBox( + child: new RenderCustomPaint( + child: child = text = new RenderParagraph(new PlainTextSpan('Hello World')), + onPaint: (PaintingCanvas canvas, Size size) { + baseline1 = child.getDistanceToBaseline(TextBaseline.alphabetic); + height1 = text.size.height; + } + ) + ); + layout(root, phase: EnginePhase.paint); + + root = new RenderPositionedBox( + child: new RenderCustomPaint( + child: child = new RenderOverflowBox( + child: text = new RenderParagraph(new PlainTextSpan('Hello World')), + maxHeight: height1 / 2.0 + ), + onPaint: (PaintingCanvas canvas, Size size) { + baseline2 = child.getDistanceToBaseline(TextBaseline.alphabetic); + height2 = text.size.height; + } + ) + ); + layout(root, phase: EnginePhase.paint); + + expect(baseline1, lessThan(height1)); + expect(height2, equals(height1 / 2.0)); + expect(baseline2, equals(baseline1)); + expect(baseline2, greaterThan(height2)); + }); +} diff --git a/packages/unit/test/widget/align_test.dart b/packages/unit/test/widget/align_test.dart index 48343cba4d..a66c2db6be 100644 --- a/packages/unit/test/widget/align_test.dart +++ b/packages/unit/test/widget/align_test.dart @@ -9,16 +9,14 @@ void main() { tester.pumpWidget( new Align( child: new Container(), - horizontal: 0.75, - vertical: 0.75 + alignment: const FractionalOffset(0.75, 0.75) ) ); tester.pumpWidget( new Align( child: new Container(), - horizontal: 0.5, - vertical: 0.5 + alignment: const FractionalOffset(0.5, 0.5) ) ); }); diff --git a/packages/unit/test/widget/animated_container_test.dart b/packages/unit/test/widget/animated_container_test.dart index c54beb01ea..653f20f602 100644 --- a/packages/unit/test/widget/animated_container_test.dart +++ b/packages/unit/test/widget/animated_container_test.dart @@ -1,3 +1,4 @@ +import 'package:flutter/animation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; @@ -45,4 +46,51 @@ void main() { }); }); + + test('AnimatedContainer overanimate test', () { + testWidgets((WidgetTester tester) { + tester.pumpWidget( + new AnimatedContainer( + duration: const Duration(milliseconds: 200), + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF00FF00) + ) + ) + ); + expect(scheduler.transientCallbackCount, 0); + tester.pump(new Duration(seconds: 1)); + expect(scheduler.transientCallbackCount, 0); + tester.pumpWidget( + new AnimatedContainer( + duration: const Duration(milliseconds: 200), + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF00FF00) + ) + ) + ); + expect(scheduler.transientCallbackCount, 0); + tester.pump(new Duration(seconds: 1)); + expect(scheduler.transientCallbackCount, 0); + tester.pumpWidget( + new AnimatedContainer( + duration: const Duration(milliseconds: 200), + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF0000FF) + ) + ) + ); + expect(scheduler.transientCallbackCount, 1); // this is the only time an animation should have started! + tester.pump(new Duration(seconds: 1)); + expect(scheduler.transientCallbackCount, 0); + tester.pumpWidget( + new AnimatedContainer( + duration: const Duration(milliseconds: 200), + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF0000FF) + ) + ) + ); + expect(scheduler.transientCallbackCount, 0); + }); + }); } diff --git a/packages/unit/test/widget/build_scope_test.dart b/packages/unit/test/widget/build_scope_test.dart index 477d4612c5..ccb8788e92 100644 --- a/packages/unit/test/widget/build_scope_test.dart +++ b/packages/unit/test/widget/build_scope_test.dart @@ -1,3 +1,4 @@ +import 'package:flutter/animation.dart'; import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; @@ -75,12 +76,14 @@ void main() { debugWidgetsExceptionHandler = (String context, dynamic exception, StackTrace stack) { cachedException = exception; }; + debugSchedulerExceptionHandler = (dynamic exception, StackTrace stack) { throw exception; }; }); tearDown(() { assert(cachedException == null); cachedException = null; debugWidgetsExceptionHandler = null; + debugSchedulerExceptionHandler = null; }); test('Legal times for setState', () { diff --git a/packages/unit/test/widget/drawer_test.dart b/packages/unit/test/widget/drawer_test.dart index 631ae43ef9..0406bf5d4c 100644 --- a/packages/unit/test/widget/drawer_test.dart +++ b/packages/unit/test/widget/drawer_test.dart @@ -14,14 +14,14 @@ void main() { routes: { '/': (RouteArguments args) { navigator = args.navigator; - new Container(); + return new Container(); } } ) ); tester.pump(); // no effect expect(tester.findText('drawer'), isNull); - showDrawer(navigator: navigator, child: new Text('drawer')); + showDrawer(context: navigator.context, child: new Text('drawer')); tester.pump(); // drawer should be starting to animate in expect(tester.findText('drawer'), isNotNull); tester.pump(new Duration(seconds: 1)); // animation done @@ -43,14 +43,14 @@ void main() { routes: { '/': (RouteArguments args) { navigator = args.navigator; - new Container(); + return new Container(); } } ) ); tester.pump(); // no effect expect(tester.findText('drawer'), isNull); - showDrawer(navigator: navigator, child: new Text('drawer')); + showDrawer(context: navigator.context, child: new Text('drawer')); tester.pump(); // drawer should be starting to animate in expect(tester.findText('drawer'), isNotNull); tester.pump(new Duration(seconds: 1)); // animation done diff --git a/packages/unit/test/widget/fractionally_sized_box_test.dart b/packages/unit/test/widget/fractionally_sized_box_test.dart index 537c7bb704..148486b518 100644 --- a/packages/unit/test/widget/fractionally_sized_box_test.dart +++ b/packages/unit/test/widget/fractionally_sized_box_test.dart @@ -19,7 +19,7 @@ void main() { width: 0.5, height: 0.25, child: new SizeObserver( - callback: (Size size) { + onSizeChanged: (Size size) { detectedSize = size; }, child: new Container( diff --git a/packages/unit/test/widget/positioned_test.dart b/packages/unit/test/widget/positioned_test.dart new file mode 100644 index 0000000000..d6bcb0ebde --- /dev/null +++ b/packages/unit/test/widget/positioned_test.dart @@ -0,0 +1,74 @@ +import 'package:flutter/animation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; +import 'package:test/test.dart'; + +import 'widget_tester.dart'; + +void main() { + + test('Can animate position data', () { + testWidgets((WidgetTester tester) { + + final AnimatedRelativeRectValue rect = new AnimatedRelativeRectValue( + new RelativeRect.fromRect( + new Rect.fromLTRB(10.0, 20.0, 20.0, 30.0), + new Rect.fromLTRB(0.0, 10.0, 100.0, 110.0) + ), + end: new RelativeRect.fromRect( + new Rect.fromLTRB(80.0, 90.0, 90.0, 100.0), + new Rect.fromLTRB(0.0, 10.0, 100.0, 110.0) + ), + curve: Curves.linear + ); + final Performance performance = new Performance( + duration: const Duration(seconds: 10) + ); + final List sizes = []; + final List positions = []; + final GlobalKey key = new GlobalKey(); + + void recordMetrics() { + RenderBox box = key.currentContext.findRenderObject(); + BoxParentData boxParentData = box.parentData; + sizes.add(box.size); + positions.add(boxParentData.position); + } + + tester.pumpWidget( + new Center( + child: new Container( + height: 100.0, + width: 100.0, + child: new Stack([ + new PositionedTransition( + rect: rect, + performance: performance, + child: new Container( + key: key + ) + ) + ]) + ) + ) + ); // t=0 + recordMetrics(); + performance.play(); + tester.pump(); // t=0 again + recordMetrics(); + tester.pump(const Duration(seconds: 1)); // t=1 + recordMetrics(); + tester.pump(const Duration(seconds: 1)); // t=2 + recordMetrics(); + tester.pump(const Duration(seconds: 3)); // t=5 + recordMetrics(); + tester.pump(const Duration(seconds: 5)); // t=10 + recordMetrics(); + + expect(sizes, equals([const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0)])); + expect(positions, equals([const Point(10.0, 10.0), const Point(10.0, 10.0), const Point(17.0, 17.0), const Point(24.0, 24.0), const Point(45.0, 45.0), const Point(80.0, 80.0)])); + + }); + }); + +} diff --git a/packages/unit/test/widget/size_observer_test.dart b/packages/unit/test/widget/size_observer_test.dart index 1eae694bdf..1ebb816c4a 100644 --- a/packages/unit/test/widget/size_observer_test.dart +++ b/packages/unit/test/widget/size_observer_test.dart @@ -11,7 +11,7 @@ void main() { List results = []; tester.pumpWidget(new Center( child: new SizeObserver( - callback: (Size size) { results.add(size); }, + onSizeChanged: (Size size) { results.add(size); }, child: new Container(width:0.0, height:0.0) ) )); @@ -20,7 +20,7 @@ void main() { expect(results, equals([Size.zero])); tester.pumpWidget(new Center( child: new SizeObserver( - callback: (Size size) { results.add(size); }, + onSizeChanged: (Size size) { results.add(size); }, child: new Container(width:100.0, height:0.0) ) )); @@ -29,7 +29,7 @@ void main() { expect(results, equals([Size.zero, const Size(100.0, 0.0)])); tester.pumpWidget(new Center( child: new SizeObserver( - callback: (Size size) { results.add(size); }, + onSizeChanged: (Size size) { results.add(size); }, child: new Container(width:0.0, height:0.0) ) )); @@ -38,7 +38,7 @@ void main() { expect(results, equals([Size.zero, const Size(100.0, 0.0), Size.zero])); tester.pumpWidget(new Center( child: new SizeObserver( - callback: (Size size) { results.add(size); }, + onSizeChanged: (Size size) { results.add(size); }, child: new Container(width:0.0, height:0.0) ) )); diff --git a/packages/unit/test/widget/snack_bar_test.dart b/packages/unit/test/widget/snack_bar_test.dart index 606a5b1628..3b43138503 100644 --- a/packages/unit/test/widget/snack_bar_test.dart +++ b/packages/unit/test/widget/snack_bar_test.dart @@ -16,7 +16,7 @@ void main() { return new GestureDetector( onTap: () { showSnackBar( - navigator: args.navigator, + context: args.navigator.context, placeholderKey: placeholderKey, content: new Text(helloSnackBar) ); diff --git a/packages/unit/test/widget/stack_test.dart b/packages/unit/test/widget/stack_test.dart index 9d64024334..14bf9a8f71 100644 --- a/packages/unit/test/widget/stack_test.dart +++ b/packages/unit/test/widget/stack_test.dart @@ -139,7 +139,7 @@ void main() { Widget buildFrame(int index) { itemsPainted = []; List items = new List.generate(itemCount, (i) { - return new CustomPaint(child: new Text('$i'), callback: (_, __) { itemsPainted.add(i); }); + return new CustomPaint(child: new Text('$i'), onPaint: (_, __) { itemsPainted.add(i); }); }); return new Center(child: new IndexedStack(items, index: index)); } diff --git a/packages/unit/test/widget/tabs_test.dart b/packages/unit/test/widget/tabs_test.dart new file mode 100644 index 0000000000..188bfad9e1 --- /dev/null +++ b/packages/unit/test/widget/tabs_test.dart @@ -0,0 +1,76 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:test/test.dart'; + +import 'widget_tester.dart'; + +int selectedIndex = 2; + +Widget buildFrame({ List tabs, bool isScrollable: false }) { + return new TabBar( + labels: tabs.map((String tab) => new TabLabel(text: tab)).toList(), + selectedIndex: selectedIndex, + isScrollable: isScrollable, + onChanged: (int tabIndex) { + selectedIndex = tabIndex; + } + ); +} + +void main() { + test('TabBar tap selects tab', () { + testWidgets((WidgetTester tester) { + List tabs = ['A', 'B', 'C']; + selectedIndex = 2; + + tester.pumpWidget(buildFrame(tabs: tabs, isScrollable: false)); + expect(tester.findText('A'), isNotNull); + expect(tester.findText('B'), isNotNull); + expect(tester.findText('C'), isNotNull); + expect(selectedIndex, equals(2)); + + tester.pumpWidget(buildFrame(tabs: tabs, isScrollable: false)); + tester.tap(tester.findText('B')); + tester.pump(); + expect(selectedIndex, equals(1)); + + tester.pumpWidget(buildFrame(tabs: tabs, isScrollable: false)); + tester.tap(tester.findText('C')); + tester.pump(); + expect(selectedIndex, equals(2)); + + tester.pumpWidget(buildFrame(tabs: tabs, isScrollable: false)); + tester.tap(tester.findText('A')); + tester.pump(); + expect(selectedIndex, equals(0)); + }); + }); + + test('Scrollable TabBar tap selects tab', () { + testWidgets((WidgetTester tester) { + List tabs = ['A', 'B', 'C']; + selectedIndex = 2; + + tester.pumpWidget(buildFrame(tabs: tabs, isScrollable: true)); + expect(tester.findText('A'), isNotNull); + expect(tester.findText('B'), isNotNull); + expect(tester.findText('C'), isNotNull); + expect(selectedIndex, equals(2)); + + tester.pumpWidget(buildFrame(tabs: tabs, isScrollable: true)); + tester.tap(tester.findText('B')); + tester.pump(); + expect(selectedIndex, equals(1)); + + tester.pumpWidget(buildFrame(tabs: tabs, isScrollable: true)); + tester.tap(tester.findText('C')); + tester.pump(); + expect(selectedIndex, equals(2)); + + tester.pumpWidget(buildFrame(tabs: tabs, isScrollable: true)); + tester.tap(tester.findText('A')); + tester.pump(); + expect(selectedIndex, equals(0)); + }); + }); +} diff --git a/packages/updater/lib/bundle.dart b/packages/updater/lib/bundle.dart new file mode 100644 index 0000000000..9e72a25921 --- /dev/null +++ b/packages/updater/lib/bundle.dart @@ -0,0 +1,75 @@ +// 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:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +const String kBundleMagic = '#!mojo '; + +Future> _readBytesWithLength(RandomAccessFile file) async { + ByteData buffer = new ByteData(4); + await file.readInto(buffer.buffer.asUint8List()); + int length = buffer.getUint32(0, Endianness.LITTLE_ENDIAN); + return await file.read(length); +} + +const int kMaxLineLen = 10*1024; +const int kNewline = 0x0A; +Future _readLine(RandomAccessFile file) async { + String line = ''; + while (line.length < kMaxLineLen) { + int byte = await file.readByte(); + if (byte == -1 || byte == kNewline) + break; + line += new String.fromCharCode(byte); + } + return line; +} + +// Represents a parsed .flx Bundle. Contains information from the bundle's +// header, as well as an open File handle positioned where the zip content +// begins. +// The bundle format is: +// #!mojo \n +// <32-bit length> +// <32-bit length> +// +// +// The manifest is a JSON string containing the following keys: +// (optional) name: the name of the package. +// version: the package version. +// update-url: the base URL to download a new manifest and bundle. +// key: a BASE-64 encoded DER-encoded ASN.1 representation of the Q point of the +// ECDSA public key that was used to sign this manifest. +// content-hash: an integer SHA-256 hash value of the . +class Bundle { + Bundle(this.path); + + final String path; + List signatureBytes; + List manifestBytes; + Map manifest; + RandomAccessFile content; + + Future _readHeader() async { + content = await new File(path).open(); + String magic = await _readLine(content); + if (!magic.startsWith(kBundleMagic)) + return false; + signatureBytes = await _readBytesWithLength(content); + manifestBytes = await _readBytesWithLength(content); + String manifestString = UTF8.decode(manifestBytes); + manifest = JSON.decode(manifestString); + return true; + } + + static Future readHeader(String path) async { + Bundle bundle = new Bundle(path); + if (!await bundle._readHeader()) + return null; + return bundle; + } +} diff --git a/packages/updater/lib/main.dart b/packages/updater/lib/main.dart index 9a748eb6e1..307984c0d0 100644 --- a/packages/updater/lib/main.dart +++ b/packages/updater/lib/main.dart @@ -3,19 +3,38 @@ // found in the LICENSE file. import 'dart:async'; +import 'dart:convert'; +import 'dart:math'; import 'dart:io'; +import 'dart:typed_data'; import 'package:mojo/core.dart'; -import 'package:flutter/services.dart'; +// TODO(mpcomplete): Remove this 'hide' when we remove the conflicting +// UpdateService from activity.mojom. +import 'package:flutter/services.dart' hide UpdateServiceProxy; import 'package:sky_services/updater/update_service.mojom.dart'; import 'package:path/path.dart' as path; import 'package:yaml/yaml.dart' as yaml; +import 'package:asn1lib/asn1lib.dart'; +import 'package:bignum/bignum.dart'; +import 'package:cipher/cipher.dart'; +import 'package:cipher/impl/client.dart'; -import 'version.dart'; +import 'bundle.dart'; import 'pipe_to_file.dart'; +import 'version.dart'; -const String kManifestFile = 'ui.yaml'; -const String kBundleFile = 'app.skyx'; +const String kManifestFile = 'sky.yaml'; +const String kBundleFile = 'app.flx'; + +// Number of bytes to read at a time from a file. +const int kReadBlockSize = 32*1024; + +// The ECDSA algorithm parameters we're using. These match the parameters used +// by the signing tool in flutter_tools. +final ECDomainParameters _ecDomain = new ECDomainParameters('prime256v1'); +final String kSignerAlgorithm = 'SHA-256/ECDSA'; +final String kHashAlgorithm = 'SHA-256'; UpdateServiceProxy _initUpdateService() { UpdateServiceProxy updateService = new UpdateServiceProxy.unbound(); @@ -32,20 +51,45 @@ Future getDataDir() async { return cachedDataDir; } -class UpdateTask { - UpdateTask() {} +// Parses a DER-encoded ASN.1 ECDSA signature block. +ECSignature _asn1ParseSignature(Uint8List signature) { + ASN1Parser parser = new ASN1Parser(signature); + ASN1Object object = parser.nextObject(); + if (object is! ASN1Sequence) + return null; + ASN1Sequence sequence = object; + if (!(sequence.elements.length == 2 && + sequence.elements[0] is ASN1Integer && + sequence.elements[1] is ASN1Integer)) + return null; + ASN1Integer r = sequence.elements[0]; + ASN1Integer s = sequence.elements[1]; + return new ECSignature(r.valueAsPositiveBigInteger, s.valueAsPositiveBigInteger); +} - run() async { +class UpdateFailure extends Error { + UpdateFailure(this._message); + String _message; + String toString() => _message; +} + +class UpdateTask { + UpdateTask(); + + Future run() async { try { await _runImpl(); - } catch(e) { + } on UpdateFailure catch (e) { print('Update failed: $e'); + } catch (e, stackTrace) { + print('Update failed: $e'); + print('Stack: $stackTrace'); } finally { _updateService.ptr.notifyUpdateCheckComplete(); } } - _runImpl() async { + Future _runImpl() async { _dataDir = await getDataDir(); await _readLocalManifest(); @@ -54,27 +98,25 @@ class UpdateTask { print('Update skipped. No new version.'); return; } - MojoResult result = await _fetchBundle(); - if (!result.isOk) { - print('Update failed while fetching new skyx bundle.'); - return; - } + await _fetchBundle(); + await _validateBundle(); await _replaceBundle(); print('Update success.'); } - yaml.YamlMap _currentManifest; + Map _currentManifest; String _dataDir; String _tempPath; - _readLocalManifest() async { - String manifestPath = path.join(_dataDir, kManifestFile); - String manifestData = await new File(manifestPath).readAsString(); - _currentManifest = yaml.loadYaml(manifestData, sourceUrl: manifestPath); + Future _readLocalManifest() async { + String bundlePath = path.join(_dataDir, kBundleFile); + Bundle bundle = await Bundle.readHeader(bundlePath); + _currentManifest = bundle.manifest; + bundle.content.close(); } Future _fetchManifest() async { - String manifestUrl = _currentManifest['update_url'] + '/' + kManifestFile; + String manifestUrl = _currentManifest['update-url'] + '/' + kManifestFile; String manifestData = await fetchString(manifestUrl); return yaml.loadYaml(manifestData, sourceUrl: manifestUrl); } @@ -85,21 +127,74 @@ class UpdateTask { return (currentVersion < remoteVersion); } - Future _fetchBundle() async { + Future _fetchBundle() async { // TODO(mpcomplete): Use the cache dir. We need an equivalent of mkstemp(). _tempPath = path.join(_dataDir, 'tmp.skyx'); - String bundleUrl = _currentManifest['update_url'] + '/' + kBundleFile; + String bundleUrl = _currentManifest['update-url'] + '/' + kBundleFile; UrlResponse response = await fetchUrl(bundleUrl); - return PipeToFile.copyToFile(response.body, _tempPath); + MojoResult result = await PipeToFile.copyToFile(response.body, _tempPath); + if (!result.isOk) + throw new UpdateFailure('Failure fetching new package: ${response.statusLine}'); } - _replaceBundle() async { + Future _validateBundle() async { + Bundle bundle = await Bundle.readHeader(_tempPath); + + if (bundle == null) + throw new UpdateFailure('Remote package not a valid FLX file.'); + if (bundle.manifest['key'] != _currentManifest['key']) + throw new UpdateFailure('Remote package key does not match.'); + + await _verifyManifestSignature(bundle); + await _verifyContentHash(bundle); + + bundle.content.close(); + } + + Future _verifyManifestSignature(Bundle bundle) async { + ECSignature ecSignature = _asn1ParseSignature(bundle.signatureBytes); + if (ecSignature == null) + throw new UpdateFailure('Corrupt package signature.'); + + List keyBytes = BASE64.decode(_currentManifest['key']); + ECPoint q = _ecDomain.curve.decodePoint(keyBytes); + ECPublicKey ecPublicKey = new ECPublicKey(q, _ecDomain); + + Signer signer = new Signer(kSignerAlgorithm); + signer.init(false, new PublicKeyParameter(ecPublicKey)); + if (!signer.verifySignature(bundle.manifestBytes, ecSignature)) + throw new UpdateFailure('Invalid package signature. This package has been tampered with.'); + } + + Future _verifyContentHash(Bundle bundle) async { + // Hash the bundle contents. + Digest hasher = new Digest(kHashAlgorithm); + RandomAccessFile content = bundle.content; + int remainingLen = await content.length() - await content.position(); + while (remainingLen > 0) { + List chunk = await content.read(min(remainingLen, kReadBlockSize)); + hasher.update(chunk, 0, chunk.length); + remainingLen -= chunk.length; + } + Uint8List hashBytes = new Uint8List(hasher.digestSize); + int len = hasher.doFinal(hashBytes, 0); + hashBytes = hashBytes.sublist(0, len); + BigInteger actualHash = new BigInteger.fromBytes(1, hashBytes); + + // Compare to our expected hash from the manifest. + BigInteger expectedHash = new BigInteger(bundle.manifest['content-hash'], 10); + if (expectedHash != actualHash) + throw new UpdateFailure('Invalid package content hash. This package has been tampered with.'); + } + + Future _replaceBundle() async { String bundlePath = path.join(_dataDir, kBundleFile); await new File(_tempPath).rename(bundlePath); } } void main() { - var task = new UpdateTask(); + initCipher(); + UpdateTask task = new UpdateTask(); task.run(); } diff --git a/packages/updater/lib/pipe_to_file.dart b/packages/updater/lib/pipe_to_file.dart index f6a62d0a0b..511a7a369e 100644 --- a/packages/updater/lib/pipe_to_file.dart +++ b/packages/updater/lib/pipe_to_file.dart @@ -30,13 +30,13 @@ class PipeToFile { return _consumer.endRead(thisRead.lengthInBytes); } - Future drain() async { - var completer = new Completer(); + Future drain() async { + Completer completer = new Completer(); // TODO(mpcomplete): Is it legit to pass an async callback to listen? _eventStream.listen((List event) async { - var mojoSignals = new MojoHandleSignals(event[1]); + MojoHandleSignals mojoSignals = new MojoHandleSignals(event[1]); if (mojoSignals.isReadable) { - var result = await _doRead(); + MojoResult result = await _doRead(); if (!result.isOk) { _eventStream.close(); _eventStream = null; @@ -58,7 +58,7 @@ class PipeToFile { } static Future copyToFile(MojoDataPipeConsumer consumer, String outputPath) { - var drainer = new PipeToFile(consumer, outputPath); + PipeToFile drainer = new PipeToFile(consumer, outputPath); return drainer.drain(); } } diff --git a/packages/updater/lib/version.dart b/packages/updater/lib/version.dart index 975927736c..15c1ab7d5c 100644 --- a/packages/updater/lib/version.dart +++ b/packages/updater/lib/version.dart @@ -9,7 +9,7 @@ import 'dart:math'; // Usage: assert(new Version('1.1.0') < new Version('1.2.1')); class Version { Version(String versionStr) : - _parts = versionStr.split('.').map((val) => int.parse(val)).toList(); + _parts = versionStr.split('.').map((String val) => int.parse(val)).toList(); List _parts; @@ -28,5 +28,5 @@ class Version { return _parts.length - other._parts.length; // results in 1.0 < 1.0.0 } - int get hashCode => _parts.fold(373, (acc, part) => 37*acc + part); + int get hashCode => _parts.fold(373, (int acc, int part) => 37*acc + part); } diff --git a/packages/updater/pubspec.yaml b/packages/updater/pubspec.yaml index 198081cc74..caced20b6d 100644 --- a/packages/updater/pubspec.yaml +++ b/packages/updater/pubspec.yaml @@ -4,11 +4,13 @@ author: Flutter Authors description: The autoupdater for flutter homepage: http://flutter.io dependencies: - mojo: '>=0.2.0 <0.3.0' + mojo: 0.3.0 flutter: ">=0.0.3 <0.1.0" sky_services: any path: any yaml: any + cipher: any + asn1lib: any dependency_overrides: flutter: path: ../sky