From 269ba86a3ecedeefb3e4b975c74aef85094ccf4e Mon Sep 17 00:00:00 2001 From: Kris Giesing Date: Thu, 15 Oct 2015 10:29:09 -0700 Subject: [PATCH 01/63] Export new InputEvent classes from appropriate places --- packages/flutter/lib/src/rendering/proxy_box.dart | 1 + packages/flutter/lib/src/widgets/basic.dart | 2 ++ 2 files changed, 3 insertions(+) diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index d68ec6c8a9..49d7da03a9 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 /// diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index 1ef3bd88f4..c32d23f157 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -24,11 +24,13 @@ export 'package:flutter/rendering.dart' show FlexDirection, FlexJustifyContent, FractionalOffset, + InputEvent, Matrix4, Offset, Paint, Path, Point, + PointerInputEvent, Rect, ScrollDirection, Shape, From 46415fa02bf16695db718037a61d7292df32ac77 Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Thu, 15 Oct 2015 14:43:48 -0700 Subject: [PATCH 02/63] Remember last position in sprite physics --- packages/flutter_sprites/lib/src/physics_body.dart | 3 +++ packages/flutter_sprites/lib/src/physics_node.dart | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/packages/flutter_sprites/lib/src/physics_body.dart b/packages/flutter_sprites/lib/src/physics_body.dart index 0517d7b702..270f8efb39 100644 --- a/packages/flutter_sprites/lib/src/physics_body.dart +++ b/packages/flutter_sprites/lib/src/physics_body.dart @@ -40,6 +40,9 @@ class PhysicsBody { this.active = active; } + Vector2 _lastPosition; + double _lastRotation; + Object tag; final PhysicsShape shape; diff --git a/packages/flutter_sprites/lib/src/physics_node.dart b/packages/flutter_sprites/lib/src/physics_node.dart index f95bb2df5a..1cff1aa937 100644 --- a/packages/flutter_sprites/lib/src/physics_node.dart +++ b/packages/flutter_sprites/lib/src/physics_node.dart @@ -113,6 +113,9 @@ class PhysicsNode extends Node { } void _updatePosition(PhysicsBody body, Point position) { + if (body._lastPosition == null) + body._lastPosition = body._body.position; + Vector2 newPos = new Vector2( position.x / b2WorldToNodeConversionFactor, position.y / b2WorldToNodeConversionFactor @@ -123,6 +126,9 @@ class PhysicsNode extends Node { } 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); From adba86431eda5c0b1befe590de99f92ccdb3cc5e Mon Sep 17 00:00:00 2001 From: Hans Muller Date: Thu, 15 Oct 2015 14:41:54 -0700 Subject: [PATCH 03/63] Revised LinearGradient ctor checking. It's OK to just specify the colors list. --- packages/flutter/lib/src/painting/box_painter.dart | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/flutter/lib/src/painting/box_painter.dart b/packages/flutter/lib/src/painting/box_painter.dart index 117c71823b..2d3b3363aa 100644 --- a/packages/flutter/lib/src/painting/box_painter.dart +++ b/packages/flutter/lib/src/painting/box_painter.dart @@ -306,9 +306,7 @@ class LinearGradient extends Gradient { 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 +321,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 From ee631c0aa87fc7ee7541b1b3e012d6b0db56e07f Mon Sep 17 00:00:00 2001 From: Collin Jackson Date: Thu, 15 Oct 2015 16:17:25 -0700 Subject: [PATCH 04/63] Build stocks app on iOS --- examples/stocks/BUILD.gn | 5 ++ examples/stocks/ios/Info.plist | 58 ++++++++++++++++++ .../01J-lp-oVM-view-Ze5-6b-2t3.nib | Bin 0 -> 1787 bytes .../ios/LaunchScreen.storyboardc/Info.plist | Bin 0 -> 258 bytes .../UIViewController-01J-lp-oVM.nib | Bin 0 -> 832 bytes 5 files changed, 63 insertions(+) create mode 100644 examples/stocks/ios/Info.plist create mode 100644 examples/stocks/ios/LaunchScreen.storyboardc/01J-lp-oVM-view-Ze5-6b-2t3.nib create mode 100644 examples/stocks/ios/LaunchScreen.storyboardc/Info.plist create mode 100644 examples/stocks/ios/LaunchScreen.storyboardc/UIViewController-01J-lp-oVM.nib 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 0000000000000000000000000000000000000000..1aa489da1163a4cf716729117166c40cf66ef1f5 GIT binary patch literal 1787 zcmebCbaE_8&d4lFWn^Gr;ACK6P+(wSFk)a}&}3j>n8Luo(8a*O(8A2XzylIzV_;}) zXm4n5Z|`et=x=YB*48|yv2$)?+q{nUWi3ssn%dX2G;L_=-qhK=yRm&wQ^UUY#-r_x zXWH8?cQoB@?zq?7`LMD1QDej7_U2cO4X@jpKDM|2Xlwr0*!;h-i=nZtovpE@&o9_B zFDElEH6<)Dr!=)A)H680v?w{X%P%;fC^Nq(v!rr%sApJaYPn-+Nq$aZWqxUibADcN zNl{{EUP2A!@6^gke!*^;Ma3nK zB_&0fNu?#JVMbHH+FbLJ^HWlbTyqObDk18EGxAGwQk+tu!IaVw>givQSXi3c;};y9 znw+1P;#rcKJ0m{S(+BJl_tMOiRL_*uypqhc%+#XEFjYua^@e)7q!yQC=7HTaDby3> zkD}D#%&N@1bl=3{?5z;*x#Xu7`{kE}6eZ>r=OmV-qAT;vE6GRl_{>nxfTH}0%+wVB zq^#8B5`-hBg8k;5S_ux&fW*uqP$0DX1&3#3mZVM%^>oh9$uDxw&n?K$OU)~B&M(a? z=?Ck9m;_SY5$frjnpcuq)Di0GlwX>cQrr&ma#Cu}LR7yaxhNz*C^a{~EVV1tGq^OV zEHkydxFgilBQqr>HE&|5XK-b4Nop?GZokA_P=JEj!3BxQsol^R0tN0guv5Y^i!+mQ zQo}RzQu52eF7gZ3OR6kMEuIOM4=GB_ED0{jFG@^L^~o$Q0V$aPH3c5{6EUKrJ=7B% z3hkkujyVMxi4#LTof4C?(~CfU1iNQ4*m&psyu8$8SOS^{iJ{=s+{C<+%w*^Mypq&B zL~@!A))JCm;FDUGnu7?$DM)dh3Ja3uTpSDx43oK}85kIra`7=RFwEs*0_8d|IUh_; z0F!gLK)JA$fu)m6h=GBjn}MaBbpZp*LI#!w);VCIRtDBiu%d1TR*)R)LI&13T|mcaF+OKrz`(u`p#xnU;cIS)tzBHKU|(}V zeFh51HgG^sh zWrw6zlz>wkEFO_#3*=LNaBzx)Nft1PEto;+136mSz;O?8@;r_nP!Q&%7WLWU2ESlPNr%Yj46_?SaSAU7 zf=deu@{5oPWrqF+zhK|elEkE(RL7#C#7c(F2EX9olA_GKbcT)wzhJP}!Ge&?!qDFc ziUPQa;8GQ=5~6)pL#Ss^XM6S{yH+73vvWl3!Grl%H6X;*wgNnVy$elA7Y0S5j0Nke``Xg3uQ)AdIXyEVZaO zGe7SlD_gvPG`elN28Ld`IR(1;VZM~e3NUi;o2OLO&fa;Q0Sp)!!4v}nCzOU!Hvwvc BP;vkO literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..8de9beddcb77a8052f2b4a5b77daa47460b2fc80 GIT binary patch literal 832 zcmebCbaE_8&d4lFWn^Gr;ACK65Mp3pFk)a}5MW?n$Y5Y#P-kFZSi;D_z|O$HaEXb5 zp`oF@slBnWqq(iSv8kuAwYRaYud%Jav1LMY+vLWUDUHojo7$!~HqK~nncdp7ps{UX zW6Pq}#i5>lnMsbx$*IM~nMs*BnI)CZ`FUxX>7_-9C7Jno#onovGr?*?iV`zRf=lv? z64O(CGK)(1a-l>&gi8-aI0g0JKAkp?vPoKo3)SOPRtY2boYHz5gOKNdRW**qg zC83_K6(y-fd5JmxNm;4MCB-3$Nja%*`9)!wspUTTi7AC?fQL-GrJQp-|d>bz4c zr-8-8GK({la#F)H^HTE5L3U073%lke=cl9=x#kv>RC=dY_W1>S=H+DOrKW)0HyNzP zIX^EiH5ul&ey|wS8Q!Ut9ig7V`K3k4sWU@81B&u1GE-9^lAbB4c_o=?nW;q`e!+T4 zl_jag?Oc2e3=BP7f(#4{-CP_D3=ADyTnr2h4PdenOg4eZJ}zbk28L!X9tH-6UM>~} z28LEHZUzR1evS#APHve+#U(+h#Rd6!DXB$$T%ZW2d7x@JkbMkU5wtesp;3=9mNT)bfOyNXNl ziy%gHv9@usGB7Z-aDkFcKgZ?(4=am%Y=j5aoHFJTIS})jftz7&J3=ALx zK~C)iJG+w$lpH(3GJRZZU@Lk+UdTx;_Ak#%EyAt5v%xPI5|j+H8bUpTO7luGb5s3G zOL9_65OKoL*8mClN~qe24WXW>Ze-|a@C$Y Date: Thu, 15 Oct 2015 17:01:47 -0700 Subject: [PATCH 05/63] Animated sprite physics bodies now correctly transfers energy to dynamic bodies --- .../flutter_sprites/lib/src/physics_body.dart | 2 + .../flutter_sprites/lib/src/physics_node.dart | 47 +++++++++++++++++-- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/packages/flutter_sprites/lib/src/physics_body.dart b/packages/flutter_sprites/lib/src/physics_body.dart index 270f8efb39..8b8d22ff98 100644 --- a/packages/flutter_sprites/lib/src/physics_body.dart +++ b/packages/flutter_sprites/lib/src/physics_body.dart @@ -42,6 +42,8 @@ class PhysicsBody { Vector2 _lastPosition; double _lastRotation; + Vector2 _targetPosition; + double _targetAngle; Object tag; diff --git a/packages/flutter_sprites/lib/src/physics_node.dart b/packages/flutter_sprites/lib/src/physics_node.dart index 1cff1aa937..12685c0c5c 100644 --- a/packages/flutter_sprites/lib/src/physics_node.dart +++ b/packages/flutter_sprites/lib/src/physics_node.dart @@ -74,6 +74,37 @@ class PhysicsNode extends Node { // 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); @@ -113,22 +144,30 @@ class PhysicsNode extends Node { } void _updatePosition(PhysicsBody body, Point position) { - if (body._lastPosition == null) - body._lastPosition = body._body.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); From f48b88cd3f8ba3983aa15a51f0075647f455f576 Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Thu, 15 Oct 2015 17:08:51 -0700 Subject: [PATCH 06/63] Updates physics test --- examples/game/test_physics.dart | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/examples/game/test_physics.dart b/examples/game/test_physics.dart index ecadb2f6f0..059acfb8c5 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'; @@ -52,7 +53,7 @@ class TestBed extends NodeWithSize { _physicsNode = new PhysicsNode(new Offset(0.0, 100.0)); _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.physicsBody = new PhysicsBody( new PhysicsShapeCircle(Point.origin, 32.0), @@ -63,6 +64,13 @@ class TestBed extends NodeWithSize { _physicsNode.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, easeInOut), + new ActionTween((a) => _obstacle.position = a, new Point(768.0, 800.0), new Point(256.0, 800.0), 1.0, easeInOut) + ]); + _obstacle.actions.run(new ActionRepeatForever(seq)); + addChild(_physicsNode); userInteractionEnabled = true; From 7b31d9b2e41e5015fa29019af86901a1011361be Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Thu, 15 Oct 2015 23:58:55 -0700 Subject: [PATCH 07/63] Rationalize exports a bit more The goal is to follow the guidelines in https://github.com/flutter/engine/blob/master/sky/specs/style-guide.md#packages Fixes #1638 --- packages/flutter/lib/painting.dart | 1 + packages/flutter/lib/rendering.dart | 1 + .../flutter/lib/src/material/checkbox.dart | 47 ++++++++++--------- .../flutter/lib/src/material/date_picker.dart | 1 - packages/flutter/lib/src/material/dialog.dart | 1 - .../flutter/lib/src/material/drawer_item.dart | 6 +-- .../flutter/lib/src/material/flat_button.dart | 1 - .../src/material/floating_action_button.dart | 1 - .../flutter/lib/src/material/icon_button.dart | 1 - .../flutter/lib/src/material/ink_well.dart | 3 +- packages/flutter/lib/src/material/input.dart | 2 - .../flutter/lib/src/material/list_item.dart | 2 - .../flutter/lib/src/material/material.dart | 1 - .../lib/src/material/material_app.dart | 2 - .../lib/src/material/material_button.dart | 1 - .../lib/src/material/progress_indicator.dart | 16 +++---- .../lib/src/material/radial_reaction.dart | 5 +- packages/flutter/lib/src/material/radio.dart | 16 +++---- .../lib/src/material/raised_button.dart | 1 - .../flutter/lib/src/material/scaffold.dart | 1 - .../flutter/lib/src/material/snack_bar.dart | 2 - packages/flutter/lib/src/material/switch.dart | 15 +++--- packages/flutter/lib/src/material/tabs.dart | 4 +- .../flutter/lib/src/material/theme_data.dart | 6 +-- .../flutter/lib/src/material/tool_bar.dart | 1 - .../flutter/lib/src/material/typography.dart | 3 +- .../flutter/lib/src/painting/basic_types.dart | 19 ++++++++ .../flutter/lib/src/painting/box_painter.dart | 2 +- .../lib/src/painting/text_painter.dart | 3 +- .../flutter/lib/src/painting/text_style.dart | 3 +- .../lib/src/rendering/basic_types.dart | 14 ++++++ packages/flutter/lib/src/rendering/box.dart | 14 +++--- packages/flutter/lib/src/rendering/image.dart | 4 ++ packages/flutter/lib/src/rendering/layer.dart | 7 ++- .../flutter/lib/src/rendering/object.dart | 17 ++++--- .../flutter/lib/src/rendering/paragraph.dart | 17 ++++++- .../flutter/lib/src/rendering/proxy_box.dart | 16 +++---- packages/flutter/lib/src/widgets/basic.dart | 30 ++++++++++-- .../flutter/lib/src/widgets/drag_target.dart | 1 - .../lib/src/widgets/gesture_detector.dart | 19 ++++++++ .../lib/src/widgets/homogeneous_viewport.dart | 5 +- .../flutter/lib/src/widgets/transitions.dart | 2 +- 42 files changed, 193 insertions(+), 121 deletions(-) create mode 100644 packages/flutter/lib/src/painting/basic_types.dart create mode 100644 packages/flutter/lib/src/rendering/basic_types.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..f7ed579fcf 100644 --- a/packages/flutter/lib/rendering.dart +++ b/packages/flutter/lib/rendering.dart @@ -6,6 +6,7 @@ library rendering; export 'src/rendering/auto_layout.dart'; +export 'src/rendering/basic_types.dart'; export 'src/rendering/block.dart'; export 'src/rendering/box.dart'; export 'src/rendering/debug.dart'; 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/date_picker.dart b/packages/flutter/lib/src/material/date_picker.dart index 46caf21ff3..e9d57597f7 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'; diff --git a/packages/flutter/lib/src/material/dialog.dart b/packages/flutter/lib/src/material/dialog.dart index 9a39a00578..6bf57bab00 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'; diff --git a/packages/flutter/lib/src/material/drawer_item.dart b/packages/flutter/lib/src/material/drawer_item.dart index 6723b15f1e..4d203d495e 100644 --- a/packages/flutter/lib/src/material/drawer_item.dart +++ b/packages/flutter/lib/src/material/drawer_item.dart @@ -4,8 +4,6 @@ import 'dart:ui' as ui; -import 'package:flutter/gestures.dart'; -import 'package:flutter/painting.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; @@ -51,8 +49,8 @@ class _DrawerItemState extends State { ui.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 ui.ColorFilter.mode(themeData.primaryColor, TransferMode.srcATop); + return new ui.ColorFilter.mode(const Color(0x73000000), TransferMode.dstIn); } Widget build(BuildContext context) { 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..b7883a78fb 100644 --- a/packages/flutter/lib/src/material/floating_action_button.dart +++ b/packages/flutter/lib/src/material/floating_action_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 'icon.dart'; diff --git a/packages/flutter/lib/src/material/icon_button.dart b/packages/flutter/lib/src/material/icon_button.dart index 7e8abf6334..f629806d30 100644 --- a/packages/flutter/lib/src/material/icon_button.dart +++ b/packages/flutter/lib/src/material/icon_button.dart @@ -4,7 +4,6 @@ import 'dart:ui' as ui; -import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import 'icon.dart'; diff --git a/packages/flutter/lib/src/material/ink_well.dart b/packages/flutter/lib/src/material/ink_well.dart index 161be19e5e..bc4bb235b0 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'; @@ -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..c2dfb5f902 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'; diff --git a/packages/flutter/lib/src/material/list_item.dart b/packages/flutter/lib/src/material/list_item.dart index 84377c65ef..9f59a7a306 100644 --- a/packages/flutter/lib/src/material/list_item.dart +++ b/packages/flutter/lib/src/material/list_item.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/widgets.dart'; import 'ink_well.dart'; diff --git a/packages/flutter/lib/src/material/material.dart b/packages/flutter/lib/src/material/material.dart index dcfbd2113a..893d4788d4 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'; diff --git a/packages/flutter/lib/src/material/material_app.dart b/packages/flutter/lib/src/material/material_app.dart index 04b3087bd6..0d41ab62cd 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'; diff --git a/packages/flutter/lib/src/material/material_button.dart b/packages/flutter/lib/src/material/material_button.dart index 0a343e9edc..bf5380d20a 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'; diff --git a/packages/flutter/lib/src/material/progress_indicator.dart b/packages/flutter/lib/src/material/progress_indicator.dart index 2c20a0af3e..73052ecdc7 100644 --- a/packages/flutter/lib/src/material/progress_indicator.dart +++ b/packages/flutter/lib/src/material/progress_indicator.dart @@ -76,10 +76,10 @@ class LinearProgressIndicator extends ProgressIndicator { double bufferValue }) : super(key: key, value: value, bufferValue: bufferValue); - 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 +103,7 @@ class LinearProgressIndicator extends ProgressIndicator { ), child: new CustomPaint( token: _getCustomPaintToken(performanceValue), - callback: (ui.Canvas canvas, Size size) { + callback: (Canvas canvas, Size size) { _paint(context, performanceValue, canvas, size); } ) @@ -124,15 +124,15 @@ class CircularProgressIndicator extends ProgressIndicator { double bufferValue }) : super(key: key, value: value, bufferValue: bufferValue); - 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 +140,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 +154,7 @@ class CircularProgressIndicator extends ProgressIndicator { ), child: new CustomPaint( token: _getCustomPaintToken(performanceValue), - callback: (ui.Canvas canvas, Size size) { + callback: (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..8e7349673c 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); @@ -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..0a5c42d7df 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); + callback: (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..4496187e76 100644 --- a/packages/flutter/lib/src/material/scaffold.dart +++ b/packages/flutter/lib/src/material/scaffold.dart @@ -4,7 +4,6 @@ import 'dart:ui' as ui; -import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'constants.dart'; diff --git a/packages/flutter/lib/src/material/snack_bar.dart b/packages/flutter/lib/src/material/snack_bar.dart index 3441fa7438..8ec933a93b 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'; 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..0eb804960f 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -7,8 +7,6 @@ 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'; @@ -312,7 +310,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); + ui.ColorFilter filter = new ui.ColorFilter.mode(iconColor, TransferMode.srcATop); return new Icon(type: label.icon, size: _kTabIconSize, colorFilter: filter); } diff --git a/packages/flutter/lib/src/material/theme_data.dart b/packages/flutter/lib/src/material/theme_data.dart index f5a8e1fabd..7566fd405c 100644 --- a/packages/flutter/lib/src/material/theme_data.dart +++ b/packages/flutter/lib/src/material/theme_data.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 'dart:ui'; +import 'dart:ui' show Color; -import 'package:flutter/src/material/typography.dart'; -import 'package:flutter/src/material/colors.dart'; +import 'typography.dart'; +import 'colors.dart'; enum ThemeBrightness { dark, light } diff --git a/packages/flutter/lib/src/material/tool_bar.dart b/packages/flutter/lib/src/material/tool_bar.dart index cdcbe9ccac..b2f5daaf4d 100644 --- a/packages/flutter/lib/src/material/tool_bar.dart +++ b/packages/flutter/lib/src/material/tool_bar.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/painting.dart'; import 'package:flutter/widgets.dart'; import 'constants.dart'; 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..2265c2b91d --- /dev/null +++ b/packages/flutter/lib/src/painting/basic_types.dart @@ -0,0 +1,19 @@ +// 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, + 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 2d3b3363aa..864b9627c9 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. 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..642e6c5a99 --- /dev/null +++ b/packages/flutter/lib/src/rendering/basic_types.dart @@ -0,0 +1,14 @@ +// 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, + Offset, + Paint, + Path, + Point, + Rect, + Size, + TransferMode; diff --git a/packages/flutter/lib/src/rendering/box.dart b/packages/flutter/lib/src/rendering/box.dart index 25bb5d8829..968a8c80ca 100644 --- a/packages/flutter/lib/src/rendering/box.dart +++ b/packages/flutter/lib/src/rendering/box.dart @@ -602,16 +602,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); diff --git a/packages/flutter/lib/src/rendering/image.dart b/packages/flutter/lib/src/rendering/image.dart index 3863cc0f22..52cda1c9da 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 diff --git a/packages/flutter/lib/src/rendering/layer.dart b/packages/flutter/lib/src/rendering/layer.dart index 0434fd8332..c5637e797d 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 @@ -322,7 +325,7 @@ class ColorFilterLayer extends ContainerLayer { Color color; /// The transfer mode to use to combine [color] with the children's painting - ui.TransferMode transferMode; + TransferMode transferMode; void addToScene(ui.SceneBuilder builder, Offset layerOffset) { builder.pushColorFilter(color, transferMode, bounds.shift(offset)); diff --git a/packages/flutter/lib/src/rendering/object.dart b/packages/flutter/lib/src/rendering/object.dart index be74fec813..679ccecad5 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) + ..setTransferMode(TransferMode.srcOver) ..isAntiAlias = false; } @@ -277,7 +276,7 @@ class PaintingContext { } } - static Paint _getPaintForColorFilter(Color color, ui.TransferMode transferMode) { + static Paint _getPaintForColorFilter(Color color, TransferMode transferMode) { return new Paint() ..colorFilter = new ui.ColorFilter.mode(color, transferMode) ..isAntiAlias = false; @@ -295,7 +294,7 @@ class PaintingContext { Point childPosition, Rect bounds, Color color, - ui.TransferMode transferMode) { + TransferMode transferMode) { assert(debugCanPaintChild(child)); final Offset childOffset = childPosition.toOffset(); if (!child.needsCompositing) { @@ -316,7 +315,7 @@ class PaintingContext { static Paint _getPaintForShaderMask(Rect bounds, ShaderCallback shaderCallback, - ui.TransferMode transferMode) { + TransferMode transferMode) { return new Paint() ..transferMode = transferMode ..shader = shaderCallback(bounds); @@ -326,7 +325,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) { 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 93307aaa34..805d506321 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -629,7 +629,7 @@ class RenderOpacity extends RenderProxyBox { /// 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 }) + RenderColorFilter({ RenderBox child, Color color, TransferMode transferMode }) : _color = color, _transferMode = transferMode, super(child); /// The color to use as input to the color filter @@ -644,9 +644,9 @@ class RenderColorFilter extends RenderProxyBox { } /// 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) { + TransferMode get transferMode => _transferMode; + TransferMode _transferMode; + void set transferMode (TransferMode newTransferMode) { assert(newTransferMode != null); if (_transferMode == newTransferMode) return; @@ -661,7 +661,7 @@ class RenderColorFilter extends RenderProxyBox { } 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; @@ -674,9 +674,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; diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index c32d23f157..eec0075f46 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -18,25 +18,47 @@ export 'package:flutter/rendering.dart' show BoxDecoration, BoxDecorationPosition, BoxShadow, + Canvas, Color, 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 @@ -64,7 +86,7 @@ class ColorFilter extends OneChildRenderObjectWidget { } final Color color; - final ui.TransferMode transferMode; + final TransferMode transferMode; RenderColorFilter createRenderObject() => new RenderColorFilter(color: color, transferMode: transferMode); @@ -78,7 +100,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); @@ -86,7 +108,7 @@ class ShaderMask extends OneChildRenderObjectWidget { } final ShaderCallback shaderCallback; - final ui.TransferMode transferMode; + final TransferMode transferMode; RenderShaderMask createRenderObject() { return new RenderShaderMask( diff --git a/packages/flutter/lib/src/widgets/drag_target.dart b/packages/flutter/lib/src/widgets/drag_target.dart index 6de530d648..5a6f237860 100644 --- a/packages/flutter/lib/src/widgets/drag_target.dart +++ b/packages/flutter/lib/src/widgets/drag_target.dart @@ -5,7 +5,6 @@ import 'dart:collection'; import 'package:flutter/animation.dart'; -import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'basic.dart'; diff --git a/packages/flutter/lib/src/widgets/gesture_detector.dart b/packages/flutter/lib/src/widgets/gesture_detector.dart index 5862ee3c43..0b8841c84d 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/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/transitions.dart b/packages/flutter/lib/src/widgets/transitions.dart index 3749e8d987..bd2f7dab4a 100644 --- a/packages/flutter/lib/src/widgets/transitions.dart +++ b/packages/flutter/lib/src/widgets/transitions.dart @@ -3,7 +3,7 @@ // found in the LICENSE file. import 'package:flutter/animation.dart'; -import 'package:vector_math/vector_math_64.dart'; +import 'package:vector_math/vector_math_64.dart' show Matrix4; import 'basic.dart'; import 'framework.dart'; From 2609f7bf8edf9148978d86374069e478f9b8e247 Mon Sep 17 00:00:00 2001 From: Hans Muller Date: Fri, 16 Oct 2015 10:06:10 -0700 Subject: [PATCH 08/63] OMG I've been running with checking turned off. Fixed scrollbar assertion failures. --- examples/widgets/scrollbar.dart | 7 ++++++- packages/flutter/lib/src/widgets/scrollable.dart | 1 - 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/examples/widgets/scrollbar.dart b/examples/widgets/scrollbar.dart index b488467a24..eaf38a1933 100644 --- a/examples/widgets/scrollbar.dart +++ b/examples/widgets/scrollbar.dart @@ -23,7 +23,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 ); } diff --git a/packages/flutter/lib/src/widgets/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index 614323154a..f53a82cadc 100644 --- a/packages/flutter/lib/src/widgets/scrollable.dart +++ b/packages/flutter/lib/src/widgets/scrollable.dart @@ -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; From 7febbfc70fd3b887504cfa28315b3a9263a14f87 Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Fri, 16 Oct 2015 10:18:35 -0700 Subject: [PATCH 09/63] Correctly resets targets for kinematic sprite physics bodies --- packages/flutter_sprites/lib/src/physics_node.dart | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/packages/flutter_sprites/lib/src/physics_node.dart b/packages/flutter_sprites/lib/src/physics_node.dart index 12685c0c5c..004917433f 100644 --- a/packages/flutter_sprites/lib/src/physics_node.dart +++ b/packages/flutter_sprites/lib/src/physics_node.dart @@ -112,6 +112,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 From 23bae330771723e0af0c652d44e3181751d40d50 Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Fri, 16 Oct 2015 10:19:25 -0700 Subject: [PATCH 10/63] Adds teleporting methods for moving sprite kinematic physics bodies without assigning velocities --- packages/flutter_sprites/lib/src/node.dart | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/packages/flutter_sprites/lib/src/node.dart b/packages/flutter_sprites/lib/src/node.dart index e3151585a7..13b98427a8 100644 --- a/packages/flutter_sprites/lib/src/node.dart +++ b/packages/flutter_sprites/lib/src/node.dart @@ -148,6 +148,16 @@ class Node { invalidateTransformMatrix(); } + void teleportRotation(double rotation) { + assert(rotation != null); + if (_physicsBody != null && parent is PhysicsNode) { + _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); @@ -172,6 +182,23 @@ class Node { invalidateTransformMatrix(); } + void teleportPosition(Point position) { + assert(position != null); + if (_physicsBody != null && parent is PhysicsNode) { + PhysicsNode 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; From ccfecf434d394983538ef1b9646db79e5fee48ea Mon Sep 17 00:00:00 2001 From: Hans Muller Date: Fri, 16 Oct 2015 11:00:12 -0700 Subject: [PATCH 11/63] Restored overlay_geometry example --- examples/widgets/overlay_geometry.dart | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/examples/widgets/overlay_geometry.dart b/examples/widgets/overlay_geometry.dart index ffde8ff1fd..c59f0f17f1 100644 --- a/examples/widgets/overlay_geometry.dart +++ b/examples/widgets/overlay_geometry.dart @@ -31,9 +31,8 @@ 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); @@ -103,7 +102,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(); From 4c5064368832a0d2340628a4557f18b79b15337f Mon Sep 17 00:00:00 2001 From: Hixie Date: Fri, 16 Oct 2015 14:44:02 -0700 Subject: [PATCH 12/63] Release process rev number updates for stage two --- packages/flutter/pubspec.yaml | 6 +++--- packages/flutter_sprites/pubspec.yaml | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/flutter/pubspec.yaml b/packages/flutter/pubspec.yaml index 4ea141a4e7..ece1bfe9f4 100644 --- a/packages/flutter/pubspec.yaml +++ b/packages/flutter/pubspec.yaml @@ -1,5 +1,5 @@ name: flutter -version: 0.0.5 +version: 0.0.6 author: Flutter Authors description: A framework for writing Flutter applications homepage: http://flutter.io @@ -9,8 +9,8 @@ dependencies: mojo_services: '>=0.3.0 <0.4.0' mojo: '>=0.2.0 <0.3.0' newton: '>=0.1.4 <0.2.0' - sky_engine: 0.0.36 - sky_services: 0.0.36 + sky_engine: 0.0.37 + sky_services: 0.0.37 sky_tools: '>=0.0.20 <0.1.0' vector_math: '>=1.4.3 <2.0.0' intl: '>=0.12.4+2 <0.13.0' diff --git a/packages/flutter_sprites/pubspec.yaml b/packages/flutter_sprites/pubspec.yaml index b1afc598c5..177ac7c55d 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.4 author: Flutter Authors homepage: http://flutter.io dependencies: - flutter: ">=0.0.5 <0.1.0" + flutter: ">=0.0.6 <0.1.0" sky_tools: ">=0.0.20 <0.1.0" box2d: ">=0.2.0 <0.3.0" From 09ac8de2d6638c399ca65e112ac972c5286110d1 Mon Sep 17 00:00:00 2001 From: Hans Muller Date: Fri, 16 Oct 2015 15:10:26 -0700 Subject: [PATCH 13/63] Fix scollable tabs, add basic unit test --- packages/flutter/lib/src/material/tabs.dart | 2 +- packages/unit/test/widget/tabs_test.dart | 76 +++++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 packages/unit/test/widget/tabs_test.dart diff --git a/packages/flutter/lib/src/material/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index 0eb804960f..00025c8376 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -335,7 +335,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 ); diff --git a/packages/unit/test/widget/tabs_test.dart b/packages/unit/test/widget/tabs_test.dart new file mode 100644 index 0000000000..99f10fa096 --- /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: (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)); + }); + }); +} From d0d84e1666b7ee394125418e2e1e2db6af2f521f Mon Sep 17 00:00:00 2001 From: Hixie Date: Fri, 2 Oct 2015 15:07:35 -0700 Subject: [PATCH 14/63] Sundry debugging aids and fixes (These are all the debugging-related fixes and trivial typo fixes that I extracted out of my heroes branch.) Fix rendering.dart import order. Introduce a debugLabel for Performances so that when you create a performance, you can tag it so that if later you print it out, you can figure out which performance it is. Allow the progress of a PerformanceView to be determined (but not set). Allow subclasses of PerformanceView that are constants to be created by defining a constant constructor for PerformanceView. Introduce a debugPrint() method that throttles its output. This is a test to see if it resolves the problems people have been having with debugDumpRenderTree() et al having their output corrupted on Android. It turns out (according to some things I read On The Internets) that Android only has a 64KB kernel buffer for its logs and and if you output to it too fast, it'll drop data on the floor. If this does in fact reliably resolve this problem, we should probably move the fix over to C++ land (where "print" is implemented) so that any use of print is handled (avoiding the interleaving problem we have now if you use both debugPrint() and print()). Fix a bug with the debugging code for "size". In the specific case of a RenderBox having a parent that doesn't set parentUsesSize, then later the parent setting parentUsesSize but the child having its layout short-circuited (e.g. because the constraints didn't change), we didn't update the _DebugSize object to know that now it's ok that the size be used by the parent, and we'd assert. Also, allow a _DebugSize to be used to set the size of yourself. Previously you could only set your size from a regular Size or from your child's _DebugSize. Add more debugging information to various Widgets where it might be helpful. Make GlobalKey's toString() include the runtimeType so that when subclassing it the new class doesn't claim to be a GlobalKey instance. Include the Widget's key in the Element's description since we don't include it in the detailed description normally (it's in the name part). Fix a test that was returning null from a route. --- packages/flutter/lib/rendering.dart | 2 +- .../lib/src/animation/performance.dart | 18 ++++++- packages/flutter/lib/src/material/drawer.dart | 2 +- .../flutter/lib/src/rendering/binding.dart | 3 +- packages/flutter/lib/src/rendering/box.dart | 23 +++++--- packages/flutter/lib/src/rendering/debug.dart | 33 ++++++++++++ .../flutter/lib/src/rendering/object.dart | 41 ++++++++++---- .../flutter/lib/src/rendering/proxy_box.dart | 2 +- packages/flutter/lib/src/widgets/basic.dart | 53 +++++++++++++++++++ packages/flutter/lib/src/widgets/binding.dart | 4 +- .../flutter/lib/src/widgets/framework.dart | 29 +++++----- .../lib/src/widgets/mixed_viewport.dart | 2 +- packages/unit/test/widget/drawer_test.dart | 4 +- 13 files changed, 179 insertions(+), 37 deletions(-) diff --git a/packages/flutter/lib/rendering.dart b/packages/flutter/lib/rendering.dart index f7ed579fcf..24e7b46054 100644 --- a/packages/flutter/lib/rendering.dart +++ b/packages/flutter/lib/rendering.dart @@ -7,6 +7,7 @@ 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'; @@ -22,7 +23,6 @@ export 'src/rendering/object.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/performance.dart b/packages/flutter/lib/src/animation/performance.dart index 0b8a020f17..e959d16961 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 @@ -45,6 +47,10 @@ abstract class PerformanceView { /// The current status of this animation PerformanceStatus get status; + /// 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; @@ -61,12 +67,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. @@ -220,6 +230,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/material/drawer.dart b/packages/flutter/lib/src/material/drawer.dart index d41e0875de..35ea2ef596 100644 --- a/packages/flutter/lib/src/material/drawer.dart +++ b/packages/flutter/lib/src/material/drawer.dart @@ -106,7 +106,7 @@ 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; diff --git a/packages/flutter/lib/src/rendering/binding.dart b/packages/flutter/lib/src/rendering/binding.dart index e501ff39fa..6b36f42150 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'; @@ -252,5 +253,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 968a8c80ca..b26a99adbb 100644 --- a/packages/flutter/lib/src/rendering/box.dart +++ b/packages/flutter/lib/src/rendering/box.dart @@ -359,9 +359,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 +379,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 +395,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 +484,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; } diff --git a/packages/flutter/lib/src/rendering/debug.dart b/packages/flutter/lib/src/rendering/debug.dart index cf2df69323..49a6937ee8 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,34 @@ 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 = 32 * 1024; +Queue _debugPrintBuffer = new Queue(); +bool _debugPrintScheduled = false; +void _debugPrintTask() { + _debugPrintScheduled = false; + 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(new Duration(seconds: 1), _debugPrintTask); + } +} diff --git a/packages/flutter/lib/src/rendering/object.dart b/packages/flutter/lib/src/rendering/object.dart index 679ccecad5..a203e74dac 100644 --- a/packages/flutter/lib/src/rendering/object.dart +++ b/packages/flutter/lib/src/rendering/object.dart @@ -513,14 +513,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); } @@ -723,15 +723,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) { @@ -768,6 +783,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/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index 805d506321..198d834f04 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -1018,7 +1018,7 @@ 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'; } } diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index eec0075f46..776e33bd4c 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -76,6 +76,11 @@ class Opacity extends OneChildRenderObjectWidget { void updateRenderObject(RenderOpacity renderObject, Opacity oldWidget) { renderObject.opacity = opacity; } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('opacity: $opacity'); + } } class ColorFilter extends OneChildRenderObjectWidget { @@ -283,6 +288,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 { @@ -298,6 +311,11 @@ class ConstrainedBox extends OneChildRenderObjectWidget { void updateRenderObject(RenderConstrainedBox renderObject, ConstrainedBox oldWidget) { renderObject.additionalConstraints = constraints; } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('constraints: $constraints'); + } } class FractionallySizedBox extends OneChildRenderObjectWidget { @@ -316,6 +334,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 { @@ -355,6 +381,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 { @@ -644,6 +675,18 @@ class Positioned extends ParentDataWidget { if (needsLayout) renderObject.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'); + } } class Grid extends MultiChildRenderObjectWidget { @@ -728,6 +771,11 @@ class Flexible extends ParentDataWidget { renderObject.markNeedsLayout(); } } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('flex: $flex'); + } } class Paragraph extends LeafRenderObjectWidget { @@ -1077,6 +1125,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/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index 1cfd022b49..891f7ebd71 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 @@ -184,7 +186,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})]'; } @@ -823,10 +825,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 +1095,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 +1128,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 +1272,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 +1614,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/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/unit/test/widget/drawer_test.dart b/packages/unit/test/widget/drawer_test.dart index 631ae43ef9..cc5fe28eae 100644 --- a/packages/unit/test/widget/drawer_test.dart +++ b/packages/unit/test/widget/drawer_test.dart @@ -14,7 +14,7 @@ void main() { routes: { '/': (RouteArguments args) { navigator = args.navigator; - new Container(); + return new Container(); } } ) @@ -43,7 +43,7 @@ void main() { routes: { '/': (RouteArguments args) { navigator = args.navigator; - new Container(); + return new Container(); } } ) From c701ad6ad06deaa9e87644efb158276d761bba96 Mon Sep 17 00:00:00 2001 From: Hixie Date: Fri, 16 Oct 2015 14:55:37 -0700 Subject: [PATCH 15/63] RelativeRect Introduce a class that can describe the metrics used in a Positioned widget, to enable easier manipulation and storage of the values, e.g. for animation purposes. --- packages/flutter/lib/src/rendering/stack.dart | 137 ++++++++++++++++++ 1 file changed, 137 insertions(+) diff --git a/packages/flutter/lib/src/rendering/stack.dart b/packages/flutter/lib/src/rendering/stack.dart index 2382411e69..c6ba3f635f 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.left + rect.width, + container.bottom - rect.top + rect.height + ); + } + + 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, $top, $right, $bottom)"; +} + /// 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; From aed45ba92b77f94dff99c06e356dd85566ebb9dc Mon Sep 17 00:00:00 2001 From: Hixie Date: Sat, 17 Oct 2015 14:52:37 -0700 Subject: [PATCH 16/63] Reduce latency of low-volume debugPrint output If we haven't printed anything for a second, then reset the count of how much we've printed. I also reduced the amount of data to ~16kb until we pause because I saw some corruption even pausing 1 second every ~32kb. (Numbers are approximate because we're counting UTF-16 characters and some of the characters in the output are multiple bytes in UTF-8.) --- packages/flutter/lib/src/rendering/debug.dart | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/flutter/lib/src/rendering/debug.dart b/packages/flutter/lib/src/rendering/debug.dart index 49a6937ee8..403fd76933 100644 --- a/packages/flutter/lib/src/rendering/debug.dart +++ b/packages/flutter/lib/src/rendering/debug.dart @@ -47,11 +47,18 @@ void debugPrint(String message) { _debugPrintTask(); } int _debugPrintedCharacters = 0; -int _kDebugPrintCapacity = 32 * 1024; +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 @@ -60,6 +67,8 @@ void _debugPrintTask() { if (_debugPrintBuffer.length > 0) { _debugPrintScheduled = true; _debugPrintedCharacters = 0; - new Timer(new Duration(seconds: 1), _debugPrintTask); + new Timer(_kDebugPrintPauseTime, _debugPrintTask); + } else { + _debugPrintStopwatch.start(); } } From 7c0c1c960964fedd23d8ee21c18b9549426f8976 Mon Sep 17 00:00:00 2001 From: Hixie Date: Sat, 17 Oct 2015 16:20:31 -0700 Subject: [PATCH 17/63] toString()ify more stuff - truncate pixel values to 1dp since there's really no point being told the Size is 302.98732587287 by 648.28498579187. - describe more Widgets so that debugDumpApp() is more useful. - remove bufferValue from ProgressIndicator (cc @hansmuller) since it's not yet implemented. - half-hearted toString() for ThemeData. There's no point making a complete one, since it would cause line-wrap even on big monitors in debugDumpApp dumps, and you can easily get the actual values from a debugging if that's the issue. - flesh out BoxConstraints.toString() so that fully unconstrained and fully infinite constraints are called out explicitly. I experimented with adding even more special cases, e.g. calling out unconstrained widths with fixed heights, etc, but it made the output less readable. - remove a redundant _updateVariable() in AnimatedContainer (cc @abarth). - add more information to RenderView.toString(). --- packages/flutter/lib/src/material/icon.dart | 17 +++++++++++++- .../flutter/lib/src/material/icon_button.dart | 5 +++++ .../lib/src/material/material_button.dart | 6 +++++ .../lib/src/material/progress_indicator.dart | 21 ++++++++++-------- packages/flutter/lib/src/material/tabs.dart | 15 +++++++++++++ packages/flutter/lib/src/material/theme.dart | 5 +++++ .../flutter/lib/src/material/theme_data.dart | 2 ++ packages/flutter/lib/src/material/title.dart | 5 +++++ packages/flutter/lib/src/rendering/box.dart | 16 +++++++++++++- packages/flutter/lib/src/rendering/stack.dart | 2 +- packages/flutter/lib/src/rendering/view.dart | 15 ++++++++----- .../lib/src/widgets/animated_container.dart | 21 +++++++++++++++++- packages/flutter/lib/src/widgets/basic.dart | 22 ++++++++++++++++++- packages/flutter/lib/src/widgets/focus.dart | 11 +++++++++- 14 files changed, 143 insertions(+), 20 deletions(-) diff --git a/packages/flutter/lib/src/material/icon.dart b/packages/flutter/lib/src/material/icon.dart index 8c25d35387..46b46ab278 100644 --- a/packages/flutter/lib/src/material/icon.dart +++ b/packages/flutter/lib/src/material/icon.dart @@ -23,6 +23,8 @@ class IconThemeData { } int get hashCode => color.hashCode; + + String toString() => '$color'; } class IconTheme extends InheritedWidget { @@ -45,6 +47,10 @@ class IconTheme extends InheritedWidget { bool updateShouldNotify(IconTheme old) => data != old.data; + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('$data'); + } } AssetBundle _initIconBundle() { @@ -63,7 +69,10 @@ 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; @@ -108,4 +117,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 f629806d30..4ea19a36fe 100644 --- a/packages/flutter/lib/src/material/icon_button.dart +++ b/packages/flutter/lib/src/material/icon_button.dart @@ -36,4 +36,9 @@ class IconButton extends StatelessComponent { ) ); } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('$icon'); + } } diff --git a/packages/flutter/lib/src/material/material_button.dart b/packages/flutter/lib/src/material/material_button.dart index bf5380d20a..1eb4591493 100644 --- a/packages/flutter/lib/src/material/material_button.dart +++ b/packages/flutter/lib/src/material/material_button.dart @@ -47,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/progress_indicator.dart b/packages/flutter/lib/src/material/progress_indicator.dart index 73052ecdc7..e688a447c0 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 { @@ -72,9 +77,8 @@ 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, Canvas canvas, Size size) { Paint paint = new Paint() @@ -120,9 +124,8 @@ 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, Canvas canvas, Size size) { Paint paint = new Paint() diff --git a/packages/flutter/lib/src/material/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index 00025c8376..3a9d40ea81 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -281,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 { @@ -345,6 +355,11 @@ class Tab extends StatelessComponent { child: centeredLabel ); } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('$label'); + } } class _TabsScrollBehavior extends BoundedBehavior { 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 7566fd405c..3b789d0409 100644 --- a/packages/flutter/lib/src/material/theme_data.dart +++ b/packages/flutter/lib/src/material/theme_data.dart @@ -124,4 +124,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/rendering/box.dart b/packages/flutter/lib/src/rendering/box.dart index b26a99adbb..2341e818fa 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] diff --git a/packages/flutter/lib/src/rendering/stack.dart b/packages/flutter/lib/src/rendering/stack.dart index c6ba3f635f..85af118fe6 100644 --- a/packages/flutter/lib/src/rendering/stack.dart +++ b/packages/flutter/lib/src/rendering/stack.dart @@ -132,7 +132,7 @@ class RelativeRect { return value; } - String toString() => "RelativeRect.fromLTRB($left, $top, $right, $bottom)"; + String toString() => "RelativeRect.fromLTRB(${left.toStringAsFixed(1)}, ${top.toStringAsFixed(1)}, ${right.toStringAsFixed(1)}, ${bottom.toStringAsFixed(1)})"; } /// Parent data for use with [RenderStack] 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/widgets/animated_container.dart b/packages/flutter/lib/src/widgets/animated_container.dart index 307fdd431f..8017dbaa16 100644 --- a/packages/flutter/lib/src/widgets/animated_container.dart +++ b/packages/flutter/lib/src/widgets/animated_container.dart @@ -123,7 +123,6 @@ class _AnimatedContainerState extends State { void _updateAllVariables() { setState(() { - _updateVariable(_constraints); _updateVariable(_constraints); _updateVariable(_decoration); _updateVariable(_foregroundDecoration); @@ -224,4 +223,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 776e33bd4c..248f343a70 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -314,7 +314,7 @@ class ConstrainedBox extends OneChildRenderObjectWidget { void debugFillDescription(List description) { super.debugFillDescription(description); - description.add('constraints: $constraints'); + description.add('$constraints'); } } @@ -549,6 +549,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'); + } + } 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 { From fb8fe97a9b15c8418b88134fa75c3a363de2f9ad Mon Sep 17 00:00:00 2001 From: Hixie Date: Sat, 17 Oct 2015 18:28:33 -0700 Subject: [PATCH 18/63] Enable Positioned to be animated. Add a AnimatedRelativeRectValue class for animating RelativeRects. Add a PositionedTransition class for animating Positioned using AnimatedRelativeRectValues. Add a test for PositionedTransition. Fix a math bug a RelativeRect found by the test. Fix a logic bug in the two ParentDataWidget classes found by the test. Specifically, they were marking the child dirty, rather than the parent. The parentData is for the parent's layout, not the child's, so they have to mark the parent dirty. (I didn't hoist this up to the superclass because ParentData could be used for painting, hit testing, accessibility, or any number of other things, and I didn't want to bake in the assumption that it needed markNeedsLayout.) --- packages/flutter/lib/src/rendering/stack.dart | 4 +- packages/flutter/lib/src/widgets/basic.dart | 11 ++- .../flutter/lib/src/widgets/transitions.dart | 43 +++++++++++ .../unit/test/widget/positioned_test.dart | 74 +++++++++++++++++++ 4 files changed, 127 insertions(+), 5 deletions(-) create mode 100644 packages/unit/test/widget/positioned_test.dart diff --git a/packages/flutter/lib/src/rendering/stack.dart b/packages/flutter/lib/src/rendering/stack.dart index 85af118fe6..54b329b41b 100644 --- a/packages/flutter/lib/src/rendering/stack.dart +++ b/packages/flutter/lib/src/rendering/stack.dart @@ -42,8 +42,8 @@ class RelativeRect { return new RelativeRect.fromLTRB( rect.left - container.left, rect.top - container.top, - container.right - rect.left + rect.width, - container.bottom - rect.top + rect.height + container.right - rect.right, + container.bottom - rect.bottom ); } diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index 248f343a70..ac64a03bb9 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -692,8 +692,11 @@ 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) { @@ -788,7 +791,9 @@ 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(); } } diff --git a/packages/flutter/lib/src/widgets/transitions.dart b/packages/flutter/lib/src/widgets/transitions.dart index bd2f7dab4a..c696131a40 100644 --- a/packages/flutter/lib/src/widgets/transitions.dart +++ b/packages/flutter/lib/src/widgets/transitions.dart @@ -4,11 +4,13 @@ import 'package:flutter/animation.dart'; import 'package:vector_math/vector_math_64.dart' show Matrix4; +import 'package:flutter/rendering.dart'; import 'basic.dart'; import 'framework.dart'; export 'package:flutter/animation.dart' show AnimationDirection; +export 'package:flutter/rendering.dart' show RelativeRect; abstract class TransitionComponent extends StatefulComponent { TransitionComponent({ @@ -150,6 +152,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/unit/test/widget/positioned_test.dart b/packages/unit/test/widget/positioned_test.dart new file mode 100644 index 0000000000..7adecc8e58 --- /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: 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)])); + + }); + }); + +} From 284eaa9cd7967831665cdd5b084b7c971b05d9ff Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Wed, 14 Oct 2015 20:32:53 -0700 Subject: [PATCH 19/63] Add a MaterialList A MaterialList understands the sizing, padding, and scrollbar features of Material Design lists. Also, add CircleAvatar for showing the circular avatars that are commonly used in material lists. --- packages/flutter/lib/material.dart | 6 +- .../lib/src/material/circle_avatar.dart | 47 ++++++++++++++ .../flutter/lib/src/material/constants.dart | 6 +- .../flutter/lib/src/material/date_picker.dart | 4 +- .../src/material/floating_action_button.dart | 3 +- packages/flutter/lib/src/material/icon.dart | 46 +------------ .../flutter/lib/src/material/icon_button.dart | 1 + .../flutter/lib/src/material/icon_theme.dart | 32 ++++++++++ .../lib/src/material/icon_theme_data.dart | 21 ++++++ .../flutter/lib/src/material/list_item.dart | 7 +- .../lib/src/material/material_list.dart | 64 +++++++++++++++++++ packages/flutter/lib/src/material/tabs.dart | 19 ++---- .../flutter/lib/src/material/theme_data.dart | 16 ++++- .../flutter/lib/src/material/tool_bar.dart | 28 ++++---- 14 files changed, 217 insertions(+), 83 deletions(-) create mode 100644 packages/flutter/lib/src/material/circle_avatar.dart create mode 100644 packages/flutter/lib/src/material/icon_theme.dart create mode 100644 packages/flutter/lib/src/material/icon_theme_data.dart create mode 100644 packages/flutter/lib/src/material/material_list.dart diff --git a/packages/flutter/lib/material.dart b/packages/flutter/lib/material.dart index 51bcfafe62..40c668cd63 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'; @@ -20,14 +21,17 @@ export 'src/material/drawer_item.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/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 e9d57597f7..c2bdc579ea 100644 --- a/packages/flutter/lib/src/material/date_picker.dart +++ b/packages/flutter/lib/src/material/date_picker.dart @@ -122,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/floating_action_button.dart b/packages/flutter/lib/src/material/floating_action_button.dart index b7883a78fb..1a6d7d332f 100644 --- a/packages/flutter/lib/src/material/floating_action_button.dart +++ b/packages/flutter/lib/src/material/floating_action_button.dart @@ -4,7 +4,8 @@ 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 46b46ab278..0257564fec 100644 --- a/packages/flutter/lib/src/material/icon.dart +++ b/packages/flutter/lib/src/material/icon.dart @@ -8,50 +8,8 @@ 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; - - String toString() => '$color'; -} - -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'); - } -} +import 'icon_theme.dart'; +import 'icon_theme_data.dart'; AssetBundle _initIconBundle() { if (rootBundle != null) diff --git a/packages/flutter/lib/src/material/icon_button.dart b/packages/flutter/lib/src/material/icon_button.dart index 4ea19a36fe..f7dd28925e 100644 --- a/packages/flutter/lib/src/material/icon_button.dart +++ b/packages/flutter/lib/src/material/icon_button.dart @@ -7,6 +7,7 @@ import 'dart:ui' as ui; import 'package:flutter/widgets.dart'; import 'icon.dart'; +import 'icon_theme_data.dart'; class IconButton extends StatelessComponent { const IconButton({ 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..9ba71ab451 --- /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; + } + + int get hashCode => color.hashCode; + + String toString() => '$color'; +} diff --git a/packages/flutter/lib/src/material/list_item.dart b/packages/flutter/lib/src/material/list_item.dart index 9f59a7a306..0352f301ab 100644 --- a/packages/flutter/lib/src/material/list_item.dart +++ b/packages/flutter/lib/src/material/list_item.dart @@ -5,7 +5,6 @@ import 'package:flutter/widgets.dart'; import 'ink_well.dart'; -import 'constants.dart'; class ListItem extends StatelessComponent { ListItem({ @@ -42,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_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/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index 3a9d40ea81..798f3362e5 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -13,9 +13,10 @@ 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); @@ -509,18 +510,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; @@ -532,7 +523,7 @@ class _TabBarState extends ScrollableState { } Widget content = new IconTheme( - data: new IconThemeData(color: iconThemeColor), + data: iconTheme, child: new DefaultTextStyle( style: textStyle, child: new BuilderTransition( diff --git a/packages/flutter/lib/src/material/theme_data.dart b/packages/flutter/lib/src/material/theme_data.dart index 3b789d0409..8e79255b9f 100644 --- a/packages/flutter/lib/src/material/theme_data.dart +++ b/packages/flutter/lib/src/material/theme_data.dart @@ -4,8 +4,9 @@ import 'dart:ui' show Color; -import 'typography.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; diff --git a/packages/flutter/lib/src/material/tool_bar.dart b/packages/flutter/lib/src/material/tool_bar.dart index b2f5daaf4d..c4ac519c5a 100644 --- a/packages/flutter/lib/src/material/tool_bar.dart +++ b/packages/flutter/lib/src/material/tool_bar.dart @@ -5,7 +5,8 @@ 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'; @@ -17,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; @@ -25,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(); From ccc98c8f41ac4076ce61c0149098220b41ba0352 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Mon, 19 Oct 2015 09:37:20 -0700 Subject: [PATCH 20/63] The dx and dy properties of PointerInputEvents shouldn't be null They should be 0.0 when there's no offset. Fixes #1661 --- packages/flutter/lib/src/gestures/events.dart | 42 +++++++++---------- .../flutter/lib/src/rendering/binding.dart | 3 +- 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/packages/flutter/lib/src/gestures/events.dart b/packages/flutter/lib/src/gestures/events.dart index 722b9984a9..9fd8e3ef6c 100644 --- a/packages/flutter/lib/src/gestures/events.dart +++ b/packages/flutter/lib/src/gestures/events.dart @@ -20,28 +20,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/rendering/binding.dart b/packages/flutter/lib/src/rendering/binding.dart index 6b36f42150..d62d9bec2a 100644 --- a/packages/flutter/lib/src/rendering/binding.dart +++ b/packages/flutter/lib/src/rendering/binding.dart @@ -62,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) { From 88bcfa2d795fc31a7d5f0cace955b05ec1d72466 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Mon, 19 Oct 2015 11:26:31 -0700 Subject: [PATCH 21/63] Rev pub packages --- packages/flutter/pubspec.yaml | 6 +++--- packages/flutter_sprites/pubspec.yaml | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/flutter/pubspec.yaml b/packages/flutter/pubspec.yaml index ece1bfe9f4..638ce8b56d 100644 --- a/packages/flutter/pubspec.yaml +++ b/packages/flutter/pubspec.yaml @@ -1,5 +1,5 @@ name: flutter -version: 0.0.6 +version: 0.0.7 author: Flutter Authors description: A framework for writing Flutter applications homepage: http://flutter.io @@ -9,8 +9,8 @@ dependencies: mojo_services: '>=0.3.0 <0.4.0' mojo: '>=0.2.0 <0.3.0' newton: '>=0.1.4 <0.2.0' - sky_engine: 0.0.37 - sky_services: 0.0.37 + sky_engine: 0.0.38 + sky_services: 0.0.38 sky_tools: '>=0.0.20 <0.1.0' vector_math: '>=1.4.3 <2.0.0' intl: '>=0.12.4+2 <0.13.0' diff --git a/packages/flutter_sprites/pubspec.yaml b/packages/flutter_sprites/pubspec.yaml index 177ac7c55d..5ef0ca10fc 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.4 +version: 0.0.5 author: Flutter Authors homepage: http://flutter.io dependencies: - flutter: ">=0.0.6 <0.1.0" + flutter: ">=0.0.7 <0.1.0" sky_tools: ">=0.0.20 <0.1.0" box2d: ">=0.2.0 <0.3.0" From 27b5fc14a3963b264ae71fecca40d8ddcae65cf3 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Mon, 19 Oct 2015 12:08:53 -0700 Subject: [PATCH 22/63] Scaffold should wrap its body in a Material Fixes #1669 --- examples/address_book/lib/main.dart | 30 +++--- examples/fitness/lib/feed.dart | 33 +++---- examples/fitness/lib/meal.dart | 24 +++-- examples/fitness/lib/measurement.dart | 42 ++++----- examples/fitness/lib/settings.dart | 44 +++++---- examples/stocks/lib/stock_list.dart | 22 ++--- examples/stocks/lib/stock_settings.dart | 56 ++++++----- examples/stocks/lib/stock_symbol_viewer.dart | 32 +++---- examples/widgets/date_picker.dart | 10 +- examples/widgets/drag_and_drop.dart | 38 ++++---- examples/widgets/indexed_stack.dart | 13 +-- examples/widgets/overlay_geometry.dart | 1 - examples/widgets/pageable_list.dart | 5 +- examples/widgets/progress_indicator.dart | 1 - examples/widgets/scale.dart | 10 +- examples/widgets/scrollbar.dart | 1 - examples/widgets/sector.dart | 94 +++++++++---------- examples/widgets/tabs.dart | 5 +- .../flutter/lib/src/material/scaffold.dart | 5 +- 19 files changed, 216 insertions(+), 250 deletions(-) diff --git a/examples/address_book/lib/main.dart b/examples/address_book/lib/main.dart index 964c39f2cf..9f79aeeb00 100644 --- a/examples/address_book/lib/main.dart +++ b/examples/address_book/lib/main.dart @@ -60,22 +60,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) { diff --git a/examples/fitness/lib/feed.dart b/examples/fitness/lib/feed.dart index cbb9922bed..4208a112fb 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) ); } } @@ -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,11 +183,9 @@ 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() ); } } 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..394d86c507 100644 --- a/examples/fitness/lib/measurement.dart +++ b/examples/fitness/lib/measurement.dart @@ -172,28 +172,26 @@ class MeasurementFragmentState extends State { 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..f33b6f0c9c 100644 --- a/examples/fitness/lib/settings.dart +++ b/examples/fitness/lib/settings.dart @@ -92,29 +92,27 @@ class SettingsFragmentState extends State { } 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/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_settings.dart b/examples/stocks/lib/stock_settings.dart index c0404c7268..d618bae8cb 100644 --- a/examples/stocks/lib/stock_settings.dart +++ b/examples/stocks/lib/stock_settings.dart @@ -83,35 +83,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..4faf71d458 100644 --- a/examples/stocks/lib/stock_symbol_viewer.dart +++ b/examples/stocks/lib/stock_symbol_viewer.dart @@ -32,24 +32,22 @@ class StockSymbolViewerState extends State { ), center: new Text('${config.stock.name} (${config.stock.symbol})') ), - body: new Material( - child: 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 - ) + 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 ) - ]) - ) + ) + ]) ); } 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/indexed_stack.dart b/examples/widgets/indexed_stack.dart index 4c0ce83122..a4e6a25de1 100644 --- a/examples/widgets/indexed_stack.dart +++ b/examples/widgets/indexed_stack.dart @@ -40,14 +40,11 @@ class IndexedStackDemoState extends State { 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)) ) ) ) diff --git a/examples/widgets/overlay_geometry.dart b/examples/widgets/overlay_geometry.dart index c59f0f17f1..ee96d77663 100644 --- a/examples/widgets/overlay_geometry.dart +++ b/examples/widgets/overlay_geometry.dart @@ -139,7 +139,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..637d4054a9 100644 --- a/examples/widgets/pageable_list.dart +++ b/examples/widgets/pageable_list.dart @@ -137,10 +137,7 @@ class PageableListAppState extends State { ); return new SizeObserver( callback: updatePageSize, - child: new Container( - child: list, - decoration: new BoxDecoration(backgroundColor: Theme.of(context).primarySwatch[50]) - ) + child: list ); } diff --git a/examples/widgets/progress_indicator.dart b/examples/widgets/progress_indicator.dart index fdf2338008..392d52afd0 100644 --- a/examples/widgets/progress_indicator.dart +++ b/examples/widgets/progress_indicator.dart @@ -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..f78524639f 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(callback: paint, token: "$_zoom $_offset") ) ) ); diff --git a/examples/widgets/scrollbar.dart b/examples/widgets/scrollbar.dart index eaf38a1933..66893bc7bd 100644 --- a/examples/widgets/scrollbar.dart +++ b/examples/widgets/scrollbar.dart @@ -49,7 +49,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)) ) 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/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/src/material/scaffold.dart b/packages/flutter/lib/src/material/scaffold.dart index 4496187e76..6eb8b39952 100644 --- a/packages/flutter/lib/src/material/scaffold.dart +++ b/packages/flutter/lib/src/material/scaffold.dart @@ -7,6 +7,7 @@ import 'dart:ui' as ui; import 'package:flutter/widgets.dart'; import 'constants.dart'; +import 'material.dart'; class Scaffold extends StatelessComponent { Scaffold({ @@ -38,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 + ) )); } From 1e228618eb567da2cacd560cc49825b032c68d22 Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Mon, 19 Oct 2015 12:13:00 -0700 Subject: [PATCH 23/63] Makes sprite physics bodies scalable --- packages/flutter_sprites/lib/src/node.dart | 10 ++++ .../flutter_sprites/lib/src/physics_body.dart | 51 +++++++++++----- .../flutter_sprites/lib/src/physics_node.dart | 8 +++ .../lib/src/physics_shape.dart | 58 +++++++++++-------- 4 files changed, 89 insertions(+), 38 deletions(-) diff --git a/packages/flutter_sprites/lib/src/node.dart b/packages/flutter_sprites/lib/src/node.dart index 13b98427a8..fc0af25e27 100644 --- a/packages/flutter_sprites/lib/src/node.dart +++ b/packages/flutter_sprites/lib/src/node.dart @@ -251,6 +251,12 @@ class Node { void set scale(double scale) { assert(scale != null); + + if (_physicsBody != null && parent is PhysicsNode) { + PhysicsNode physicsNode = parent; + physicsNode._updateScale(this.physicsBody, scale); + } + _scaleX = _scaleY = scale; invalidateTransformMatrix(); } @@ -262,6 +268,8 @@ class Node { void set scaleX(double scaleX) { assert(scaleX != null); + assert(physicsBody == null); + _scaleX = scaleX; invalidateTransformMatrix(); } @@ -273,6 +281,8 @@ class Node { void set scaleY(double scaleY) { assert(scaleY != null); + assert(physicsBody == null); + _scaleY = scaleY; invalidateTransformMatrix(); } diff --git a/packages/flutter_sprites/lib/src/physics_body.dart b/packages/flutter_sprites/lib/src/physics_body.dart index 8b8d22ff98..63123ff7e1 100644 --- a/packages/flutter_sprites/lib/src/physics_body.dart +++ b/packages/flutter_sprites/lib/src/physics_body.dart @@ -45,6 +45,8 @@ class PhysicsBody { Vector2 _targetPosition; double _targetAngle; + double _scale; + Object tag; final PhysicsShape shape; @@ -294,6 +296,9 @@ class PhysicsBody { void _attach(PhysicsNode 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); @@ -318,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(PhysicsNode physicsNode) { // Create FixtureDef box2d.FixtureDef fixtureDef = new box2d.FixtureDef(); fixtureDef.friction = friction; @@ -339,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() { @@ -361,13 +371,26 @@ class PhysicsBody { } } + void _updateScale(PhysicsNode 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(PhysicsNode 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_node.dart b/packages/flutter_sprites/lib/src/physics_node.dart index 004917433f..6abed0b93a 100644 --- a/packages/flutter_sprites/lib/src/physics_node.dart +++ b/packages/flutter_sprites/lib/src/physics_node.dart @@ -181,6 +181,14 @@ class PhysicsNode extends Node { 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) { diff --git a/packages/flutter_sprites/lib/src/physics_shape.dart b/packages/flutter_sprites/lib/src/physics_shape.dart index 2669aeb2be..7249b71f65 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(PhysicsNode node, double scale) { if (_b2Shape == null) { - _b2Shape = _createB2Shape(node); + _b2Shape = _createB2Shape(node, scale); } return _b2Shape; } - box2d.Shape _createB2Shape(PhysicsNode node); + box2d.Shape _createB2Shape(PhysicsNode 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(PhysicsNode 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(PhysicsNode 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(PhysicsNode 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(PhysicsNode 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(PhysicsNode 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(PhysicsNode node, double scale) { return null; } + + void _invalidate() { + for (PhysicsShape shape in shapes) { + shape._invalidate(); + } + } } From 6f9fe7b1fe70090ff545ecbd71ab9aa0b85412a0 Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Mon, 19 Oct 2015 12:13:20 -0700 Subject: [PATCH 24/63] Updates physics test --- examples/game/test_physics.dart | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/examples/game/test_physics.dart b/examples/game/test_physics.dart index 059acfb8c5..20264f83b4 100644 --- a/examples/game/test_physics.dart +++ b/examples/game/test_physics.dart @@ -55,6 +55,7 @@ class TestBed extends NodeWithSize { _obstacle = new Sprite(_spriteSheet["ship.png"]); _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, @@ -71,6 +72,12 @@ class TestBed extends NodeWithSize { ]); _obstacle.actions.run(new ActionRepeatForever(seq)); + seq = new ActionSequence([ + new ActionTween((a) => _obstacle.scale = a, 1.0, 2.0, 2.0, easeInOut), + new ActionTween((a) => _obstacle.scale = a, 2.0, 1.0, 2.0, easeInOut) + ]); + _obstacle.actions.run(new ActionRepeatForever(seq)); + addChild(_physicsNode); userInteractionEnabled = true; From 2aa79d56946e50c63388d108d50c56b1bfc8cf25 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Mon, 19 Oct 2015 12:21:34 -0700 Subject: [PATCH 25/63] Remove old setFoo functions on Paint We now just use Dart properties, which is more idiomatic. --- examples/game/lib/game_objects.dart | 2 +- examples/game/lib/power_bar.dart | 2 +- examples/raw/baseline.dart | 13 +++++++------ examples/raw/painting.dart | 2 +- examples/rendering/baseline.dart | 8 ++++---- examples/stocks/lib/stock_arrow.dart | 4 ++-- examples/widgets/overlay_geometry.dart | 7 ++++--- packages/flutter/lib/src/painting/box_painter.dart | 2 +- packages/flutter/lib/src/rendering/object.dart | 2 +- .../flutter_sprites/lib/src/particle_system.dart | 2 +- packages/flutter_sprites/lib/src/physics_debug.dart | 2 +- packages/flutter_sprites/lib/src/textured_line.dart | 4 ++-- .../flutter_sprites/lib/src/virtual_joystick.dart | 2 +- 13 files changed, 27 insertions(+), 25 deletions(-) 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/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/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..38f190be9c 100644 --- a/examples/rendering/baseline.dart +++ b/examples/rendering/baseline.dart @@ -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/stocks/lib/stock_arrow.dart b/examples/stocks/lib/stock_arrow.dart index f745c242bb..b969f469de 100644 --- a/examples/stocks/lib/stock_arrow.dart +++ b/examples/stocks/lib/stock_arrow.dart @@ -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/widgets/overlay_geometry.dart b/examples/widgets/overlay_geometry.dart index c59f0f17f1..089202135c 100644 --- a/examples/widgets/overlay_geometry.dart +++ b/examples/widgets/overlay_geometry.dart @@ -36,9 +36,10 @@ class Marker extends StatelessComponent { 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); diff --git a/packages/flutter/lib/src/painting/box_painter.dart b/packages/flutter/lib/src/painting/box_painter.dart index 864b9627c9..5983138344 100644 --- a/packages/flutter/lib/src/painting/box_painter.dart +++ b/packages/flutter/lib/src/painting/box_painter.dart @@ -866,7 +866,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/rendering/object.dart b/packages/flutter/lib/src/rendering/object.dart index a203e74dac..60c94d2e28 100644 --- a/packages/flutter/lib/src/rendering/object.dart +++ b/packages/flutter/lib/src/rendering/object.dart @@ -246,7 +246,7 @@ class PaintingContext { static Paint _getPaintForAlpha(int alpha) { return new Paint() ..color = new Color.fromARGB(alpha, 0, 0, 0) - ..setTransferMode(TransferMode.srcOver) + ..transferMode = TransferMode.srcOver ..isAntiAlias = false; } 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_debug.dart b/packages/flutter_sprites/lib/src/physics_debug.dart index 30f877c929..3b73b0740d 100644 --- a/packages/flutter_sprites/lib/src/physics_debug.dart +++ b/packages/flutter_sprites/lib/src/physics_debug.dart @@ -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/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; From 9baf8eb3724c4843fdb12fbf7fa350fc9d386a5f Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Mon, 19 Oct 2015 12:39:22 -0700 Subject: [PATCH 26/63] Remove ColorFilter widget This widget is slow and not commonly used. The original reason we added it was to colorize images, but now that feature is built into the image and background image widgets. Fixes #1646 --- packages/flutter/lib/src/rendering/layer.dart | 26 ------------- .../flutter/lib/src/rendering/object.dart | 37 ------------------ .../flutter/lib/src/rendering/proxy_box.dart | 39 ------------------- packages/flutter/lib/src/widgets/basic.dart | 18 --------- 4 files changed, 120 deletions(-) diff --git a/packages/flutter/lib/src/rendering/layer.dart b/packages/flutter/lib/src/rendering/layer.dart index c5637e797d..3da0d16087 100644 --- a/packages/flutter/lib/src/rendering/layer.dart +++ b/packages/flutter/lib/src/rendering/layer.dart @@ -307,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 - 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 60c94d2e28..db6435636e 100644 --- a/packages/flutter/lib/src/rendering/object.dart +++ b/packages/flutter/lib/src/rendering/object.dart @@ -276,43 +276,6 @@ class PaintingContext { } } - static Paint _getPaintForColorFilter(Color color, 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, - 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, TransferMode transferMode) { diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index 198d834f04..ecace249a8 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -621,45 +621,6 @@ 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, 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] - TransferMode get transferMode => _transferMode; - TransferMode _transferMode; - void set transferMode (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, TransferMode transferMode }) : _shaderCallback = shaderCallback, _transferMode = transferMode, super(child); diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index ac64a03bb9..f1e0dd1cc6 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -83,24 +83,6 @@ class Opacity extends OneChildRenderObjectWidget { } } -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 TransferMode transferMode; - - RenderColorFilter createRenderObject() => new RenderColorFilter(color: color, transferMode: transferMode); - - void updateRenderObject(RenderColorFilter renderObject, ColorFilter oldWidget) { - renderObject.color = color; - renderObject.transferMode = transferMode; - } -} - class ShaderMask extends OneChildRenderObjectWidget { ShaderMask({ Key key, From 715b304ea20d81512d33496d0a59c8b91f94e050 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Mon, 19 Oct 2015 12:56:38 -0700 Subject: [PATCH 27/63] Convert Align to use FractionalOffset instead of two doubles It was confusing as to whether these were fractions or pixels. Fixes #1622 --- examples/widgets/card_collection.dart | 3 +- packages/flutter/lib/src/rendering/box.dart | 24 +++++++++++++ .../flutter/lib/src/rendering/proxy_box.dart | 24 ------------- .../lib/src/rendering/shifted_box.dart | 35 ++++++------------- packages/flutter/lib/src/widgets/basic.dart | 13 +++---- packages/unit/test/widget/align_test.dart | 6 ++-- 6 files changed, 42 insertions(+), 63 deletions(-) diff --git a/examples/widgets/card_collection.dart b/examples/widgets/card_collection.dart index fd2d17a047..f371f24139 100644 --- a/examples/widgets/card_collection.dart +++ b/examples/widgets/card_collection.dart @@ -348,8 +348,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)) diff --git a/packages/flutter/lib/src/rendering/box.dart b/packages/flutter/lib/src/rendering/box.dart index 2341e818fa..486aac8954 100644 --- a/packages/flutter/lib/src/rendering/box.dart +++ b/packages/flutter/lib/src/rendering/box.dart @@ -737,3 +737,27 @@ abstract class RenderBoxContainerDefaultsMixin '$runtimeType($x, $y)'; +} diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index 198d834f04..426076a445 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -863,30 +863,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({ 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/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index ac64a03bb9..4084019f0d 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -237,25 +237,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; } } 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) ) ); }); From 552f26d71324e559e69a38e5ecc16c3110c580ab Mon Sep 17 00:00:00 2001 From: Hixie Date: Mon, 19 Oct 2015 12:46:52 -0700 Subject: [PATCH 28/63] Stop AnimatedContainer from animating every build It turns out that an AnimatedContainer with a BoxDecoration would start animating every single time it was built, whether or not the container's decoration had changed. --- .../flutter/lib/src/animation/scheduler.dart | 2 + .../flutter/lib/src/painting/box_painter.dart | 249 ++++++++++++++++-- .../lib/src/widgets/animated_container.dart | 3 +- .../flutter/lib/src/widgets/framework.dart | 6 +- .../test/widget/animated_container_test.dart | 48 ++++ 5 files changed, 279 insertions(+), 29 deletions(-) diff --git a/packages/flutter/lib/src/animation/scheduler.dart b/packages/flutter/lib/src/animation/scheduler.dart index 699ced4830..88d2b2b311 100644 --- a/packages/flutter/lib/src/animation/scheduler.dart +++ b/packages/flutter/lib/src/animation/scheduler.dart @@ -30,6 +30,8 @@ class Scheduler { Map _transientCallbacks = new LinkedHashMap(); final Set _removedIds = new Set(); + int get transientCallbackCount => _transientCallbacks.length; + /// Called by the engine to produce a new frame. /// /// This function first calls all the callbacks registered by diff --git a/packages/flutter/lib/src/painting/box_painter.dart b/packages/flutter/lib/src/painting/box_painter.dart index 5983138344..5aa148c962 100644 --- a/packages/flutter/lib/src/painting/box_painter.dart +++ b/packages/flutter/lib/src/painting/box_painter.dart @@ -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,17 +314,37 @@ 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, @@ -332,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)'; } @@ -339,7 +434,7 @@ class LinearGradient extends Gradient { /// A 2D radial gradient class RadialGradient extends Gradient { - RadialGradient({ + const RadialGradient({ this.center, this.radius, this.colors, @@ -373,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)'; } @@ -498,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; @@ -516,22 +670,14 @@ class BackgroundImage { /// 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; - /// 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) { @@ -557,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)'; @@ -650,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) diff --git a/packages/flutter/lib/src/widgets/animated_container.dart b/packages/flutter/lib/src/widgets/animated_container.dart index 8017dbaa16..f205fdd2f9 100644 --- a/packages/flutter/lib/src/widgets/animated_container.dart +++ b/packages/flutter/lib/src/widgets/animated_container.dart @@ -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(); diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index 891f7ebd71..2a5aedc7b8 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -202,8 +202,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) 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); + }); + }); } From 6bd4fb85157a20e7708041b405b20659e74a9f74 Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Mon, 19 Oct 2015 13:27:32 -0700 Subject: [PATCH 29/63] Renames PhysicsNode to PhysicsWorld --- examples/game/test_physics.dart | 4 +-- .../flutter_sprites/lib/flutter_sprites.dart | 2 +- packages/flutter_sprites/lib/src/node.dart | 20 +++++++------- .../flutter_sprites/lib/src/physics_body.dart | 10 +++---- .../lib/src/physics_debug.dart | 2 +- .../lib/src/physics_joint.dart | 26 +++++++++---------- .../lib/src/physics_shape.dart | 16 ++++++------ .../{physics_node.dart => physics_world.dart} | 8 +++--- .../flutter_sprites/lib/src/sprite_box.dart | 6 ++--- 9 files changed, 47 insertions(+), 47 deletions(-) rename packages/flutter_sprites/lib/src/{physics_node.dart => physics_world.dart} (98%) diff --git a/examples/game/test_physics.dart b/examples/game/test_physics.dart index 20264f83b4..b645d36516 100644 --- a/examples/game/test_physics.dart +++ b/examples/game/test_physics.dart @@ -47,10 +47,10 @@ 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)); _obstacle = new Sprite(_spriteSheet["ship.png"]); _obstacle.position = new Point(512.0, 800.0); diff --git a/packages/flutter_sprites/lib/flutter_sprites.dart b/packages/flutter_sprites/lib/flutter_sprites.dart index 9db7007a29..4203fd978d 100644 --- a/packages/flutter_sprites/lib/flutter_sprites.dart +++ b/packages/flutter_sprites/lib/flutter_sprites.dart @@ -36,8 +36,8 @@ part 'src/particle_system.dart'; part 'src/physics_body.dart'; part 'src/physics_debug.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 fc0af25e27..51011e949c 100644 --- a/packages/flutter_sprites/lib/src/node.dart +++ b/packages/flutter_sprites/lib/src/node.dart @@ -132,8 +132,8 @@ class Node { void set rotation(double rotation) { assert(rotation != null); - if (_physicsBody != null && parent is PhysicsNode) { - PhysicsNode physicsNode = parent; + if (_physicsBody != null && parent is PhysicsWorld) { + PhysicsWorld physicsNode = parent; physicsNode._updateRotation(this.physicsBody, rotation); return; } @@ -150,7 +150,7 @@ class Node { void teleportRotation(double rotation) { assert(rotation != null); - if (_physicsBody != null && parent is PhysicsNode) { + 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); @@ -166,8 +166,8 @@ class Node { void set position(Point position) { assert(position != null); - if (_physicsBody != null && parent is PhysicsNode) { - PhysicsNode physicsNode = parent; + if (_physicsBody != null && parent is PhysicsWorld) { + PhysicsWorld physicsNode = parent; physicsNode._updatePosition(this.physicsBody, position); return; } @@ -184,8 +184,8 @@ class Node { void teleportPosition(Point position) { assert(position != null); - if (_physicsBody != null && parent is PhysicsNode) { - PhysicsNode physicsNode = parent; + if (_physicsBody != null && parent is PhysicsWorld) { + PhysicsWorld physicsNode = parent; _physicsBody._body.setTransform( new Vector2( position.x / physicsNode.b2WorldToNodeConversionFactor, @@ -252,8 +252,8 @@ class Node { void set scale(double scale) { assert(scale != null); - if (_physicsBody != null && parent is PhysicsNode) { - PhysicsNode physicsNode = parent; + if (_physicsBody != null && parent is PhysicsWorld) { + PhysicsWorld physicsNode = parent; physicsNode._updateScale(this.physicsBody, scale); } @@ -681,7 +681,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/physics_body.dart b/packages/flutter_sprites/lib/src/physics_body.dart index 63123ff7e1..98f71b47a1 100644 --- a/packages/flutter_sprites/lib/src/physics_body.dart +++ b/packages/flutter_sprites/lib/src/physics_body.dart @@ -232,7 +232,7 @@ class PhysicsBody { double gravityScale; - PhysicsNode _physicsNode; + PhysicsWorld _physicsNode; Node _node; box2d.Body _body; @@ -293,7 +293,7 @@ class PhysicsBody { _body.applyAngularImpulse(impulse / _physicsNode.b2WorldToNodeConversionFactor); } - void _attach(PhysicsNode physicsNode, Node node) { + void _attach(PhysicsWorld physicsNode, Node node) { assert(_attached == false); // Update scale @@ -340,7 +340,7 @@ class PhysicsBody { } } - void _createFixtures(PhysicsNode physicsNode) { + void _createFixtures(PhysicsWorld physicsNode) { // Create FixtureDef box2d.FixtureDef fixtureDef = new box2d.FixtureDef(); fixtureDef.friction = friction; @@ -371,7 +371,7 @@ class PhysicsBody { } } - void _updateScale(PhysicsNode physicsNode) { + void _updateScale(PhysicsWorld physicsNode) { // Destroy old fixtures for (box2d.Fixture fixture = _body.getFixtureList(); fixture != null; fixture = fixture.getNext()) { _body.destroyFixture(fixture); @@ -384,7 +384,7 @@ class PhysicsBody { _createFixtures(physicsNode); } - void _addB2Shapes(PhysicsNode physicsNode, PhysicsShape shape, List b2Shapes, List physicsShapes) { + 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); diff --git a/packages/flutter_sprites/lib/src/physics_debug.dart b/packages/flutter_sprites/lib/src/physics_debug.dart index 3b73b0740d..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; 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 7249b71f65..de0eca029e 100644 --- a/packages/flutter_sprites/lib/src/physics_shape.dart +++ b/packages/flutter_sprites/lib/src/physics_shape.dart @@ -6,14 +6,14 @@ abstract class PhysicsShape { Object userObject; - box2d.Shape getB2Shape(PhysicsNode node, double scale) { + box2d.Shape getB2Shape(PhysicsWorld node, double scale) { if (_b2Shape == null) { _b2Shape = _createB2Shape(node, scale); } return _b2Shape; } - box2d.Shape _createB2Shape(PhysicsNode node, double scale); + box2d.Shape _createB2Shape(PhysicsWorld node, double scale); void _invalidate() { _b2Shape = null; @@ -26,7 +26,7 @@ class PhysicsShapeCircle extends PhysicsShape { final Point point; final double radius; - box2d.Shape _createB2Shape(PhysicsNode node, double scale) { + box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { box2d.CircleShape shape = new box2d.CircleShape(); shape.p.x = scale * point.x / node.b2WorldToNodeConversionFactor; shape.p.y = scale * point.y / node.b2WorldToNodeConversionFactor; @@ -40,7 +40,7 @@ class PhysicsShapePolygon extends PhysicsShape { final List points; - box2d.Shape _createB2Shape(PhysicsNode node, double scale) { + box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { List vectors = []; for (Point point in points) { Vector2 vec = new Vector2( @@ -69,7 +69,7 @@ class PhysicsShapeBox extends PhysicsShape { final Point center; final double rotation; - box2d.Shape _createB2Shape(PhysicsNode node, double scale) { + box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { box2d.PolygonShape shape = new box2d.PolygonShape(); shape.setAsBox( scale * width / node.b2WorldToNodeConversionFactor, @@ -90,7 +90,7 @@ class PhysicsShapeChain extends PhysicsShape { final List points; final bool loop; - box2d.Shape _createB2Shape(PhysicsNode node, double scale) { + box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { List vectors = []; for (Point point in points) { Vector2 vec = new Vector2( @@ -115,7 +115,7 @@ class PhysicsShapeEdge extends PhysicsShape { final Point pointA; final Point pointB; - box2d.Shape _createB2Shape(PhysicsNode node, double scale) { + box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { box2d.EdgeShape shape = new box2d.EdgeShape(); shape.set( new Vector2( @@ -137,7 +137,7 @@ class PhysicsShapeGroup extends PhysicsShape { final List shapes; - box2d.Shape _createB2Shape(PhysicsNode node, double scale) { + box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { return null; } diff --git a/packages/flutter_sprites/lib/src/physics_node.dart b/packages/flutter_sprites/lib/src/physics_world.dart similarity index 98% rename from packages/flutter_sprites/lib/src/physics_node.dart rename to packages/flutter_sprites/lib/src/physics_world.dart index 6abed0b93a..d8bf889b6b 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(); } @@ -252,7 +252,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_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); } } From 4094223378ba73749ba45be5e505285a5ce2a603 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Mon, 19 Oct 2015 13:15:22 -0700 Subject: [PATCH 30/63] Show ColorFilter Instead of requiring clients to use ui.ColorFilter, we show show the ColorFilter class, similar to what we do for Color. --- examples/stocks/lib/stock_home.dart | 2 +- packages/flutter/lib/src/material/drawer_item.dart | 6 +++--- packages/flutter/lib/src/material/icon.dart | 2 +- packages/flutter/lib/src/material/icon_button.dart | 2 +- packages/flutter/lib/src/material/tabs.dart | 2 +- packages/flutter/lib/src/painting/basic_types.dart | 1 + packages/flutter/lib/src/painting/box_painter.dart | 6 +++--- packages/flutter/lib/src/rendering/basic_types.dart | 1 + packages/flutter/lib/src/rendering/image.dart | 8 ++++---- packages/flutter/lib/src/widgets/basic.dart | 9 +++++---- packages/flutter_sprites/lib/src/sprite.dart | 2 +- 11 files changed, 22 insertions(+), 19 deletions(-) diff --git a/examples/stocks/lib/stock_home.dart b/examples/stocks/lib/stock_home.dart index 33d9cdd5de..f613dc74cb 100644 --- a/examples/stocks/lib/stock_home.dart +++ b/examples/stocks/lib/stock_home.dart @@ -226,7 +226,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( diff --git a/packages/flutter/lib/src/material/drawer_item.dart b/packages/flutter/lib/src/material/drawer_item.dart index 4d203d495e..123053efd6 100644 --- a/packages/flutter/lib/src/material/drawer_item.dart +++ b/packages/flutter/lib/src/material/drawer_item.dart @@ -47,10 +47,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, TransferMode.srcATop); - return new ui.ColorFilter.mode(const Color(0x73000000), 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/icon.dart b/packages/flutter/lib/src/material/icon.dart index 0257564fec..1112594dc0 100644 --- a/packages/flutter/lib/src/material/icon.dart +++ b/packages/flutter/lib/src/material/icon.dart @@ -35,7 +35,7 @@ class Icon extends StatelessComponent { final int size; final String type; final IconThemeColor color; - final ui.ColorFilter colorFilter; + final ColorFilter colorFilter; String _getColorSuffix(BuildContext context) { IconThemeColor iconThemeColor = color; diff --git a/packages/flutter/lib/src/material/icon_button.dart b/packages/flutter/lib/src/material/icon_button.dart index f7dd28925e..b2f9f0a022 100644 --- a/packages/flutter/lib/src/material/icon_button.dart +++ b/packages/flutter/lib/src/material/icon_button.dart @@ -20,7 +20,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) { diff --git a/packages/flutter/lib/src/material/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index 798f3362e5..4ca1b450f8 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -321,7 +321,7 @@ class Tab extends StatelessComponent { Widget _buildLabelIcon() { assert(label.icon != null); Color iconColor = selected ? selectedColor : color; - ui.ColorFilter filter = new ui.ColorFilter.mode(iconColor, TransferMode.srcATop); + ColorFilter filter = new ColorFilter.mode(iconColor, TransferMode.srcATop); return new Icon(type: label.icon, size: _kTabIconSize, colorFilter: filter); } diff --git a/packages/flutter/lib/src/painting/basic_types.dart b/packages/flutter/lib/src/painting/basic_types.dart index 2265c2b91d..e2edd579b2 100644 --- a/packages/flutter/lib/src/painting/basic_types.dart +++ b/packages/flutter/lib/src/painting/basic_types.dart @@ -5,6 +5,7 @@ export 'dart:ui' show Canvas, Color, + ColorFilter, FontStyle, FontWeight, Offset, diff --git a/packages/flutter/lib/src/painting/box_painter.dart b/packages/flutter/lib/src/painting/box_painter.dart index 5aa148c962..0980795733 100644 --- a/packages/flutter/lib/src/painting/box_painter.dart +++ b/packages/flutter/lib/src/painting/box_painter.dart @@ -561,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, @@ -668,7 +668,7 @@ class BackgroundImage { final Rect centerSlice; /// A color filter to apply to the background image before painting it. - final ui.ColorFilter colorFilter; + final ColorFilter colorFilter; /// The image to be painted into the background. ui.Image get image => _image; diff --git a/packages/flutter/lib/src/rendering/basic_types.dart b/packages/flutter/lib/src/rendering/basic_types.dart index 642e6c5a99..acc920dd37 100644 --- a/packages/flutter/lib/src/rendering/basic_types.dart +++ b/packages/flutter/lib/src/rendering/basic_types.dart @@ -5,6 +5,7 @@ export 'dart:ui' show Canvas, Color, + ColorFilter, Offset, Paint, Path, diff --git a/packages/flutter/lib/src/rendering/image.dart b/packages/flutter/lib/src/rendering/image.dart index 52cda1c9da..079e4dfdf4 100644 --- a/packages/flutter/lib/src/rendering/image.dart +++ b/packages/flutter/lib/src/rendering/image.dart @@ -22,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 @@ -67,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/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index 374f82b843..b843032e35 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -20,6 +20,7 @@ export 'package:flutter/rendering.dart' show BoxShadow, Canvas, Color, + ColorFilter, EdgeDims, FlexAlignItems, FlexDirection, @@ -894,7 +895,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; @@ -936,7 +937,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; @@ -998,7 +999,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; @@ -1033,7 +1034,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; 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) { From dff3fa7e469a6c1d812cea42aa303ef5150bdd56 Mon Sep 17 00:00:00 2001 From: Matt Perry Date: Mon, 19 Oct 2015 16:39:02 -0400 Subject: [PATCH 31/63] Support verifying .flx signatures when updating. Adds a step to the updater to verify that the new .flx package is signed and untampered. Each .flx contains a signed manifest file. The manifest contains a SHA-256 hash of the .flx contents. See bundle.dart for a description of the new .flx format. --- examples/fitness/sky.yaml | 2 +- examples/stocks/sky.yaml | 3 + packages/flutter/pubspec.yaml | 2 +- packages/updater/lib/bundle.dart | 75 +++++++++++++ packages/updater/lib/main.dart | 145 ++++++++++++++++++++----- packages/updater/lib/pipe_to_file.dart | 10 +- packages/updater/lib/version.dart | 4 +- packages/updater/pubspec.yaml | 2 + 8 files changed, 209 insertions(+), 34 deletions(-) create mode 100644 packages/updater/lib/bundle.dart 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/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/packages/flutter/pubspec.yaml b/packages/flutter/pubspec.yaml index 638ce8b56d..5851cef409 100644 --- a/packages/flutter/pubspec.yaml +++ b/packages/flutter/pubspec.yaml @@ -11,7 +11,7 @@ dependencies: newton: '>=0.1.4 <0.2.0' sky_engine: 0.0.38 sky_services: 0.0.38 - sky_tools: '>=0.0.20 <0.1.0' + 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/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..a1eb2a6f57 100644 --- a/packages/updater/pubspec.yaml +++ b/packages/updater/pubspec.yaml @@ -9,6 +9,8 @@ dependencies: sky_services: any path: any yaml: any + cipher: any + asn1lib: any dependency_overrides: flutter: path: ../sky From 8382ca2c0a0293bac9bb8fe545754d8bb2182083 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Mon, 19 Oct 2015 13:42:39 -0700 Subject: [PATCH 32/63] Fix analyzer warnings in examples --- examples/rendering/flex.dart | 3 ++- examples/rendering/interactive_flex.dart | 6 ++++-- examples/rendering/render_paragraph.dart | 6 ++++-- examples/rendering/spinning_flex.dart | 3 ++- 4 files changed, 12 insertions(+), 6 deletions(-) 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); From ed195cfa196399b34a0b7511d7a4576b64ff1993 Mon Sep 17 00:00:00 2001 From: Hixie Date: Mon, 19 Oct 2015 15:41:28 -0700 Subject: [PATCH 33/63] requestPostFrameCallback() Provide a way to schedule a callback for immediately after the current frame has been sent to the GPU thread. This is useful for times where you want to immediately schedule yourself for another build or layout because, for instance, you just displayed frame zero of an animation and you want to use the metrics from that layout to set up the actual animation to begin immediately, such that the very next frame is frame 1. --- .../flutter/lib/src/animation/scheduler.dart | 84 ++++++++++++++++--- .../flutter/lib/src/material/drawer_item.dart | 2 - packages/flutter/lib/src/material/icon.dart | 2 - .../flutter/lib/src/material/icon_button.dart | 2 - packages/flutter/lib/src/material/tabs.dart | 1 - .../unit/test/widget/build_scope_test.dart | 3 + 6 files changed, 74 insertions(+), 20 deletions(-) diff --git a/packages/flutter/lib/src/animation/scheduler.dart b/packages/flutter/lib/src/animation/scheduler.dart index 88d2b2b311..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,37 +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. @@ -72,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/material/drawer_item.dart b/packages/flutter/lib/src/material/drawer_item.dart index 123053efd6..5f1fc9d2a9 100644 --- a/packages/flutter/lib/src/material/drawer_item.dart +++ b/packages/flutter/lib/src/material/drawer_item.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 'dart:ui' as ui; - import 'package:flutter/widgets.dart'; import 'colors.dart'; diff --git a/packages/flutter/lib/src/material/icon.dart b/packages/flutter/lib/src/material/icon.dart index 1112594dc0..da620a6521 100644 --- a/packages/flutter/lib/src/material/icon.dart +++ b/packages/flutter/lib/src/material/icon.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 'dart:ui' as ui; - import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; diff --git a/packages/flutter/lib/src/material/icon_button.dart b/packages/flutter/lib/src/material/icon_button.dart index b2f9f0a022..96be9d5cb7 100644 --- a/packages/flutter/lib/src/material/icon_button.dart +++ b/packages/flutter/lib/src/material/icon_button.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 'dart:ui' as ui; - import 'package:flutter/widgets.dart'; import 'icon.dart'; diff --git a/packages/flutter/lib/src/material/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index 4ca1b450f8..6591eb7f72 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -3,7 +3,6 @@ // 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'; 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', () { From 4f96083e667daf1234ede1d822bf53be7fea0e61 Mon Sep 17 00:00:00 2001 From: Hixie Date: Mon, 19 Oct 2015 16:06:46 -0700 Subject: [PATCH 34/63] Fix warning in test. Arguments must be typed. --- packages/unit/test/widget/tabs_test.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/unit/test/widget/tabs_test.dart b/packages/unit/test/widget/tabs_test.dart index 99f10fa096..188bfad9e1 100644 --- a/packages/unit/test/widget/tabs_test.dart +++ b/packages/unit/test/widget/tabs_test.dart @@ -11,7 +11,7 @@ Widget buildFrame({ List tabs, bool isScrollable: false }) { labels: tabs.map((String tab) => new TabLabel(text: tab)).toList(), selectedIndex: selectedIndex, isScrollable: isScrollable, - onChanged: (tabIndex) { + onChanged: (int tabIndex) { selectedIndex = tabIndex; } ); From 2edc6dbb3d5c5dc910764e65baa2163ca08a9ee3 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Mon, 19 Oct 2015 17:16:05 -0700 Subject: [PATCH 35/63] Add AnimatedSizeValue --- .../flutter/lib/src/animation/animated_value.dart | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) 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 From 529fa95f8718cef9a63104fe228432773472ce45 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Mon, 19 Oct 2015 17:22:59 -0700 Subject: [PATCH 36/63] Give the CustomPaint and SizeObserver callbacks better names The style we use for callbacks in widgets is "onFoo". These classes were using an order naming convention and just called their callbacks "callback". --- examples/game/lib/main.dart | 2 +- examples/rendering/baseline.dart | 2 +- examples/stocks/lib/stock_arrow.dart | 2 +- examples/widgets/card_collection.dart | 2 +- examples/widgets/overlay_geometry.dart | 2 +- examples/widgets/pageable_list.dart | 2 +- examples/widgets/scale.dart | 2 +- packages/flutter/lib/src/material/input.dart | 2 +- .../flutter/lib/src/material/popup_menu.dart | 2 +- .../lib/src/material/progress_indicator.dart | 4 +-- packages/flutter/lib/src/material/radio.dart | 2 +- packages/flutter/lib/src/material/tabs.dart | 2 +- .../flutter/lib/src/rendering/proxy_box.dart | 34 +++++++++---------- packages/flutter/lib/src/widgets/basic.dart | 24 ++++++------- .../flutter/lib/src/widgets/dismissable.dart | 2 +- packages/flutter/lib/src/widgets/mimic.dart | 2 +- .../flutter/lib/src/widgets/navigator.dart | 12 +++---- .../flutter/lib/src/widgets/scrollable.dart | 8 ++--- .../widget/fractionally_sized_box_test.dart | 2 +- .../unit/test/widget/size_observer_test.dart | 8 ++--- packages/unit/test/widget/stack_test.dart | 2 +- 21 files changed, 60 insertions(+), 60 deletions(-) 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/rendering/baseline.dart b/examples/rendering/baseline.dart index 38f190be9c..8d9e04c216 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: (canvas, size) { double baseline = paragraph.getDistanceToBaseline(TextBaseline.alphabetic); double w = paragraph.getMaxIntrinsicWidth(new BoxConstraints.loose(size)); double h = paragraph.getMaxIntrinsicHeight(new BoxConstraints.loose(size)); diff --git a/examples/stocks/lib/stock_arrow.dart b/examples/stocks/lib/stock_arrow.dart index b969f469de..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; diff --git a/examples/widgets/card_collection.dart b/examples/widgets/card_collection.dart index f371f24139..756e0fc6d5 100644 --- a/examples/widgets/card_collection.dart +++ b/examples/widgets/card_collection.dart @@ -337,7 +337,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]), diff --git a/examples/widgets/overlay_geometry.dart b/examples/widgets/overlay_geometry.dart index e14ebf5335..4d6ee5259d 100644 --- a/examples/widgets/overlay_geometry.dart +++ b/examples/widgets/overlay_geometry.dart @@ -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) ) ) ); diff --git a/examples/widgets/pageable_list.dart b/examples/widgets/pageable_list.dart index 637d4054a9..98a5e0fdb5 100644 --- a/examples/widgets/pageable_list.dart +++ b/examples/widgets/pageable_list.dart @@ -136,7 +136,7 @@ class PageableListAppState extends State { : pageSize.width ); return new SizeObserver( - callback: updatePageSize, + onSizeChanged: updatePageSize, child: list ); } diff --git a/examples/widgets/scale.dart b/examples/widgets/scale.dart index f78524639f..5062846125 100644 --- a/examples/widgets/scale.dart +++ b/examples/widgets/scale.dart @@ -63,7 +63,7 @@ class ScaleAppState extends State { body: new GestureDetector( onScaleStart: _handleScaleStart, onScaleUpdate: _handleScaleUpdate, - child: new CustomPaint(callback: paint, token: "$_zoom $_offset") + child: new CustomPaint(onPaint: paint, token: "$_zoom $_offset") ) ) ); diff --git a/packages/flutter/lib/src/material/input.dart b/packages/flutter/lib/src/material/input.dart index c2dfb5f902..91914b63e4 100644 --- a/packages/flutter/lib/src/material/input.dart +++ b/packages/flutter/lib/src/material/input.dart @@ -116,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/popup_menu.dart b/packages/flutter/lib/src/material/popup_menu.dart index 10d0c2bab0..f20540e7fb 100644 --- a/packages/flutter/lib/src/material/popup_menu.dart +++ b/packages/flutter/lib/src/material/popup_menu.dart @@ -75,7 +75,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)); diff --git a/packages/flutter/lib/src/material/progress_indicator.dart b/packages/flutter/lib/src/material/progress_indicator.dart index e688a447c0..1fd6a7190e 100644 --- a/packages/flutter/lib/src/material/progress_indicator.dart +++ b/packages/flutter/lib/src/material/progress_indicator.dart @@ -107,7 +107,7 @@ class LinearProgressIndicator extends ProgressIndicator { ), child: new CustomPaint( token: _getCustomPaintToken(performanceValue), - callback: (Canvas canvas, Size size) { + onPaint: (Canvas canvas, Size size) { _paint(context, performanceValue, canvas, size); } ) @@ -157,7 +157,7 @@ class CircularProgressIndicator extends ProgressIndicator { ), child: new CustomPaint( token: _getCustomPaintToken(performanceValue), - callback: (Canvas canvas, Size size) { + onPaint: (Canvas canvas, Size size) { _paint(context, performanceValue, canvas, size); } ) diff --git a/packages/flutter/lib/src/material/radio.dart b/packages/flutter/lib/src/material/radio.dart index 0a5c42d7df..a8c33aabf3 100644 --- a/packages/flutter/lib/src/material/radio.dart +++ b/packages/flutter/lib/src/material/radio.dart @@ -45,7 +45,7 @@ class Radio extends StatelessComponent { width: kDiameter, height: kDiameter, child: new CustomPaint( - callback: (Canvas canvas, Size size) { + onPaint: (Canvas canvas, Size size) { // Draw the outer circle Paint paint = new Paint() diff --git a/packages/flutter/lib/src/material/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index 6591eb7f72..dcb917446b 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -545,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/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index c5bccf96e0..0109e93736 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -962,33 +962,33 @@ class RenderTransform extends RenderProxyBox { /// 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); + onSizeChanged(size); } } /// 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 @@ -1003,36 +1003,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/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index b843032e35..f048dfe520 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -134,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; } } @@ -428,21 +428,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; } } diff --git a/packages/flutter/lib/src/widgets/dismissable.dart b/packages/flutter/lib/src/widgets/dismissable.dart index 69f76a8a98..f16c6531dd 100644 --- a/packages/flutter/lib/src/widgets/dismissable.dart +++ b/packages/flutter/lib/src/widgets/dismissable.dart @@ -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/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/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index c326efd747..d708f4b615 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -54,11 +54,11 @@ class NavigatorState extends State { _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 )); } @@ -318,11 +318,11 @@ class PageRoute extends PerformanceRoute { } 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,8 +330,8 @@ class StateRoute extends Route { void didPop([dynamic result]) { assert(result == null); - if (callback != null) - callback(this); + if (onPop != null) + onPop(this); super.didPop(result); } diff --git a/packages/flutter/lib/src/widgets/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index f53a82cadc..ea1cbf4668 100644 --- a/packages/flutter/lib/src/widgets/scrollable.dart +++ b/packages/flutter/lib/src/widgets/scrollable.dart @@ -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 ) ) @@ -596,7 +596,7 @@ abstract class ScrollableWidgetListState extends } return new SizeObserver( - callback: _handleSizeChanged, + onSizeChanged: _handleSizeChanged, child: new Container( padding: _crossAxisPadding, child: new HomogeneousViewport( @@ -820,7 +820,7 @@ class ScrollableMixedWidgetListState extends ScrollableState 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/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)); } From f79fdff2d0181c767dda457d982823286e72429c Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Mon, 19 Oct 2015 18:08:52 -0700 Subject: [PATCH 37/63] Move animation curves into a Curves namespace --- examples/game/test_physics.dart | 8 +-- examples/widgets/progress_indicator.dart | 4 +- .../flutter/lib/src/animation/curves.dart | 55 ++++++++++--------- .../lib/src/animation/simulation_stepper.dart | 2 +- packages/flutter/lib/src/material/dialog.dart | 2 +- packages/flutter/lib/src/material/drawer.dart | 2 +- .../flutter/lib/src/material/ink_well.dart | 2 +- .../flutter/lib/src/material/material.dart | 2 +- .../lib/src/material/progress_indicator.dart | 2 +- .../lib/src/material/radial_reaction.dart | 8 +-- .../lib/src/material/scrollbar_painter.dart | 2 +- .../flutter/lib/src/material/snack_bar.dart | 4 +- packages/flutter/lib/src/material/tabs.dart | 2 +- .../flutter/lib/src/rendering/toggleable.dart | 2 +- .../lib/src/widgets/animated_container.dart | 2 +- .../flutter/lib/src/widgets/dismissable.dart | 2 +- .../flutter/lib/src/widgets/navigator.dart | 4 +- .../flutter/lib/src/widgets/scrollable.dart | 4 +- .../unit/test/widget/positioned_test.dart | 2 +- 19 files changed, 58 insertions(+), 53 deletions(-) diff --git a/examples/game/test_physics.dart b/examples/game/test_physics.dart index b645d36516..5c22c30fa7 100644 --- a/examples/game/test_physics.dart +++ b/examples/game/test_physics.dart @@ -67,14 +67,14 @@ class TestBed extends NodeWithSize { // 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, easeInOut), - new ActionTween((a) => _obstacle.position = a, new Point(768.0, 800.0), new Point(256.0, 800.0), 1.0, easeInOut) + 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, easeInOut), - new ActionTween((a) => _obstacle.scale = a, 2.0, 1.0, 2.0, easeInOut) + 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)); diff --git a/examples/widgets/progress_indicator.dart b/examples/widgets/progress_indicator.dart index 392d52afd0..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) 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/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/material/dialog.dart b/packages/flutter/lib/src/material/dialog.dart index 6bf57bab00..bb6157919f 100644 --- a/packages/flutter/lib/src/material/dialog.dart +++ b/packages/flutter/lib/src/material/dialog.dart @@ -142,7 +142,7 @@ class _DialogRoute extends PerformanceRoute { Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance) { return new FadeTransition( performance: performance, - opacity: new AnimatedValue(0.0, end: 1.0, curve: easeOut), + opacity: new AnimatedValue(0.0, end: 1.0, curve: Curves.easeOut), child: builder(new RouteArguments(navigator: navigator, previousPerformance: this.performance, nextPerformance: nextRoutePerformance)) ); } diff --git a/packages/flutter/lib/src/material/drawer.dart b/packages/flutter/lib/src/material/drawer.dart index 35ea2ef596..d0dcdcb338 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, diff --git a/packages/flutter/lib/src/material/ink_well.dart b/packages/flutter/lib/src/material/ink_well.dart index bc4bb235b0..0d5ca2d47b 100644 --- a/packages/flutter/lib/src/material/ink_well.dart +++ b/packages/flutter/lib/src/material/ink_well.dart @@ -28,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, diff --git a/packages/flutter/lib/src/material/material.dart b/packages/flutter/lib/src/material/material.dart index 893d4788d4..96ada6ff6e 100644 --- a/packages/flutter/lib/src/material/material.dart +++ b/packages/flutter/lib/src/material/material.dart @@ -67,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/progress_indicator.dart b/packages/flutter/lib/src/material/progress_indicator.dart index 1fd6a7190e..ac41cf2066 100644 --- a/packages/flutter/lib/src/material/progress_indicator.dart +++ b/packages/flutter/lib/src/material/progress_indicator.dart @@ -45,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) { diff --git a/packages/flutter/lib/src/material/radial_reaction.dart b/packages/flutter/lib/src/material/radial_reaction.dart index 8e7349673c..7d550b6885 100644 --- a/packages/flutter/lib/src/material/radial_reaction.dart +++ b/packages/flutter/lib/src/material/radial_reaction.dart @@ -26,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); @@ -36,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 ); } 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 8ec933a93b..340174daa0 100644 --- a/packages/flutter/lib/src/material/snack_bar.dart +++ b/packages/flutter/lib/src/material/snack_bar.dart @@ -67,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( diff --git a/packages/flutter/lib/src/material/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index dcb917446b..da976a08fa 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -404,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; } 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/widgets/animated_container.dart b/packages/flutter/lib/src/widgets/animated_container.dart index f205fdd2f9..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); diff --git a/packages/flutter/lib/src/widgets/dismissable.dart b/packages/flutter/lib/src/widgets/dismissable.dart index f16c6531dd..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; diff --git a/packages/flutter/lib/src/widgets/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index d708f4b615..358cab089e 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -307,10 +307,10 @@ class PageRoute extends PerformanceRoute { // TODO(jackson): Block input unless content is interactive return new SlideTransition( performance: performance, - position: new AnimatedValue(_kTransitionStartPoint, end: Point.origin, curve: easeOut), + 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), + opacity: new AnimatedValue(0.0, end: 1.0, curve: Curves.easeOut), child: builder(new RouteArguments(navigator: navigator, previousPerformance: this.performance, nextPerformance: nextRoutePerformance)) ) ); diff --git a/packages/flutter/lib/src/widgets/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index ea1cbf4668..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(); @@ -692,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, diff --git a/packages/unit/test/widget/positioned_test.dart b/packages/unit/test/widget/positioned_test.dart index 7adecc8e58..d6bcb0ebde 100644 --- a/packages/unit/test/widget/positioned_test.dart +++ b/packages/unit/test/widget/positioned_test.dart @@ -19,7 +19,7 @@ void main() { new Rect.fromLTRB(80.0, 90.0, 90.0, 100.0), new Rect.fromLTRB(0.0, 10.0, 100.0, 110.0) ), - curve: linear + curve: Curves.linear ); final Performance performance = new Performance( duration: const Duration(seconds: 10) From 1d5f25333ac14c58e895954b18895d3da95f225e Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Tue, 20 Oct 2015 08:14:58 -0700 Subject: [PATCH 38/63] Normalize some function names in proxy_box.dart We call this function _getInnerConstraints in other classes. Also, this change makes it private for RenderOverflowBox. --- .../flutter/lib/src/rendering/proxy_box.dart | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index 0109e93736..a0456d57e0 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -190,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, @@ -201,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); } } @@ -313,7 +313,7 @@ class RenderOverflowBox extends RenderProxyBox { markNeedsLayout(); } - BoxConstraints childConstraints(BoxConstraints constraints) { + BoxConstraints _getInnerConstraints(BoxConstraints constraints) { return new BoxConstraints( minWidth: _minWidth ?? constraints.minWidth, maxWidth: _maxWidth ?? constraints.maxWidth, @@ -346,7 +346,7 @@ class RenderOverflowBox extends RenderProxyBox { void performLayout() { if (child != null) - child.layout(childConstraints(constraints)); + child.layout(_getInnerConstraints(constraints)); } String debugDescribeSettings(String prefix) { From 521489304350a6ef3d317d0b0ab3e458f0b93f92 Mon Sep 17 00:00:00 2001 From: Hixie Date: Tue, 20 Oct 2015 08:58:21 -0700 Subject: [PATCH 39/63] OffStage Introduces a new Widget that lays its child out, but does not render it. Also, moves RenderOverflowBox to its own file since it has nothing to do with proxy box really. --- packages/flutter/lib/rendering.dart | 1 + .../flutter/lib/src/rendering/overflow.dart | 170 ++++++++++++++++++ .../flutter/lib/src/rendering/proxy_box.dart | 119 ------------ packages/flutter/lib/src/widgets/basic.dart | 7 + 4 files changed, 178 insertions(+), 119 deletions(-) create mode 100644 packages/flutter/lib/src/rendering/overflow.dart diff --git a/packages/flutter/lib/rendering.dart b/packages/flutter/lib/rendering.dart index 24e7b46054..52a57e8e8c 100644 --- a/packages/flutter/lib/rendering.dart +++ b/packages/flutter/lib/rendering.dart @@ -20,6 +20,7 @@ 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'; diff --git a/packages/flutter/lib/src/rendering/overflow.dart b/packages/flutter/lib/src/rendering/overflow.dart new file mode 100644 index 0000000000..7090f44b55 --- /dev/null +++ b/packages/flutter/lib/src/rendering/overflow.dart @@ -0,0 +1,170 @@ +// 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(); + } + + 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'; + } +} + + +/// 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/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index a0456d57e0..b98ba838a0 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -239,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 _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(); - } - - bool get sizedByParent => true; - - void performResize() { - size = constraints.biggest; - } - - void performLayout() { - if (child != null) - child.layout(_getInnerConstraints(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 diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index f048dfe520..8e21acc985 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -346,6 +346,13 @@ class OverflowBox extends OneChildRenderObjectWidget { } } +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) { From 1e9e4e159d8d42aa9411d4b3f6e3b0c44bb8e235 Mon Sep 17 00:00:00 2001 From: Hixie Date: Tue, 20 Oct 2015 09:50:10 -0700 Subject: [PATCH 40/63] RenderOverflowBox baseline logic I accidentally lost this when extracting RenderOverflowBox from RenderProxyBox. --- examples/rendering/baseline.dart | 2 +- .../flutter/lib/src/rendering/overflow.dart | 6 +++ .../unit/test/rendering/overflow_test.dart | 42 +++++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 packages/unit/test/rendering/overflow_test.dart diff --git a/examples/rendering/baseline.dart b/examples/rendering/baseline.dart index 8d9e04c216..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, - onPaint: (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)); diff --git a/packages/flutter/lib/src/rendering/overflow.dart b/packages/flutter/lib/src/rendering/overflow.dart index 7090f44b55..586cdeeba7 100644 --- a/packages/flutter/lib/src/rendering/overflow.dart +++ b/packages/flutter/lib/src/rendering/overflow.dart @@ -108,6 +108,12 @@ class RenderOverflowBox extends RenderBox with RenderObjectWithChildMixin true; void performResize() { 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)); + }); +} From 2cb9a00f464e3b7f4baa66ec638aafe4d2dba329 Mon Sep 17 00:00:00 2001 From: Jim Beveridge Date: Tue, 20 Oct 2015 09:10:06 -0700 Subject: [PATCH 41/63] Close the UrlLoaderProxy on error. Fixes #1680. --- packages/flutter/lib/src/services/fetch.dart | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/flutter/lib/src/services/fetch.dart b/packages/flutter/lib/src/services/fetch.dart index 7a9253628d..047241bf07 100644 --- a/packages/flutter/lib/src/services/fetch.dart +++ b/packages/flutter/lib/src/services/fetch.dart @@ -36,24 +36,25 @@ class Response { } Future 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 { From ff76ceb40eb4a4c74fb34eca90d3d2d042e06707 Mon Sep 17 00:00:00 2001 From: Hixie Date: Tue, 20 Oct 2015 10:17:05 -0700 Subject: [PATCH 42/63] RenderOffStage test Also, give RenderViewport a default offset. --- .../flutter/lib/src/rendering/viewport.dart | 2 +- .../unit/test/rendering/offstage_test.dart | 32 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 packages/unit/test/rendering/offstage_test.dart 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 Date: Tue, 20 Oct 2015 10:35:40 -0700 Subject: [PATCH 43/63] Adds sprite physics groups --- .../flutter_sprites/lib/flutter_sprites.dart | 1 + packages/flutter_sprites/lib/src/node.dart | 46 +++++++- .../lib/src/physics_group.dart | 107 ++++++++++++++++++ .../lib/src/physics_world.dart | 10 ++ 4 files changed, 158 insertions(+), 6 deletions(-) create mode 100644 packages/flutter_sprites/lib/src/physics_group.dart diff --git a/packages/flutter_sprites/lib/flutter_sprites.dart b/packages/flutter_sprites/lib/flutter_sprites.dart index 4203fd978d..97b48b3d5d 100644 --- a/packages/flutter_sprites/lib/flutter_sprites.dart +++ b/packages/flutter_sprites/lib/flutter_sprites.dart @@ -35,6 +35,7 @@ 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_shape.dart'; part 'src/physics_world.dart'; diff --git a/packages/flutter_sprites/lib/src/node.dart b/packages/flutter_sprites/lib/src/node.dart index 51011e949c..7b9e0e0464 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 PhysicsWorld) { - PhysicsWorld physicsNode = parent; - physicsNode._updateRotation(this.physicsBody, rotation); + if (_physicsBody != null && (parent is PhysicsWorld || parent is PhysicsGroup)) { + _updatePhysicsRotation(physicsBody, rotation, parent); return; } @@ -142,6 +141,19 @@ 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; @@ -166,9 +178,8 @@ class Node { void set position(Point position) { assert(position != null); - if (_physicsBody != null && parent is PhysicsWorld) { - PhysicsWorld physicsNode = parent; - physicsNode._updatePosition(this.physicsBody, position); + if (_physicsBody != null && (parent is PhysicsWorld || parent is PhysicsGroup)) { + _updatePhysicsPosition(this.physicsBody, position, parent); return; } @@ -176,6 +187,20 @@ 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; @@ -310,6 +335,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); @@ -318,6 +344,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. @@ -330,6 +360,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. 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_world.dart b/packages/flutter_sprites/lib/src/physics_world.dart index d8bf889b6b..fd27e95bcc 100644 --- a/packages/flutter_sprites/lib/src/physics_world.dart +++ b/packages/flutter_sprites/lib/src/physics_world.dart @@ -43,6 +43,8 @@ class PhysicsWorld extends Node { List _bodiesScheduledForDestruction = []; + List _bodiesScheduledForUpdate = []; + _PhysicsDebugDraw _debugDraw; double b2WorldToNodeConversionFactor = 10.0; @@ -71,6 +73,14 @@ class PhysicsWorld 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(); From ca724ae151d45057fab0db5ca984133a20ace136 Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Tue, 20 Oct 2015 10:47:58 -0700 Subject: [PATCH 44/63] Adds support for scaling sprite physics groups --- examples/game/test_physics.dart | 4 +++- packages/flutter_sprites/lib/src/node.dart | 18 +++++++++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/examples/game/test_physics.dart b/examples/game/test_physics.dart index b645d36516..add66dd23a 100644 --- a/examples/game/test_physics.dart +++ b/examples/game/test_physics.dart @@ -51,6 +51,8 @@ class TestBed extends NodeWithSize { TestBed() : super(new Size(1024.0, 1024.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(512.0, 800.0); @@ -62,7 +64,7 @@ class TestBed extends NodeWithSize { friction: 0.5, tag: "obstacle" ); - _physicsNode.addChild(_obstacle); + group.addChild(_obstacle); _physicsNode.addContactCallback(myCallback, "obstacle", "ship", PhysicsContactType.begin); // Animate obstacle diff --git a/packages/flutter_sprites/lib/src/node.dart b/packages/flutter_sprites/lib/src/node.dart index 7b9e0e0464..67982bf59c 100644 --- a/packages/flutter_sprites/lib/src/node.dart +++ b/packages/flutter_sprites/lib/src/node.dart @@ -277,15 +277,27 @@ class Node { void set scale(double scale) { assert(scale != null); - if (_physicsBody != null && parent is PhysicsWorld) { - PhysicsWorld physicsNode = parent; - physicsNode._updateScale(this.physicsBody, scale); + 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; From d54d35d3d12a8f9d62c04770defa43c35775ae84 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Tue, 20 Oct 2015 09:43:46 -0700 Subject: [PATCH 45/63] Adds EnterExitTransition widget This widget smoothly resizes as its child changes and lets you provide entrance and exit transitions for its children. --- examples/widgets/smooth_resize.dart | 115 +++++++++++ .../flutter/lib/src/rendering/overflow.dart | 61 ++++++ .../flutter/lib/src/rendering/proxy_box.dart | 8 +- packages/flutter/lib/src/widgets/basic.dart | 13 ++ .../src/widgets/enter_exit_transition.dart | 185 ++++++++++++++++++ packages/flutter/lib/widgets.dart | 1 + 6 files changed, 381 insertions(+), 2 deletions(-) create mode 100644 examples/widgets/smooth_resize.dart create mode 100644 packages/flutter/lib/src/widgets/enter_exit_transition.dart 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/packages/flutter/lib/src/rendering/overflow.dart b/packages/flutter/lib/src/rendering/overflow.dart index 586cdeeba7..24b3ec081b 100644 --- a/packages/flutter/lib/src/rendering/overflow.dart +++ b/packages/flutter/lib/src/rendering/overflow.dart @@ -146,6 +146,67 @@ class RenderOverflowBox 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 diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index b98ba838a0..1b50c2b4a9 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -861,8 +861,12 @@ class RenderSizeObserver extends RenderProxyBox { void performLayout() { Size oldSize = hasSize ? size : null; super.performLayout(); - if (oldSize != size) - onSizeChanged(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)); + } } } diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index 8e21acc985..c9ed90652a 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -346,6 +346,19 @@ 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); 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/widgets.dart b/packages/flutter/lib/widgets.dart index 2ecb32b564..434ebf1258 100644 --- a/packages/flutter/lib/widgets.dart +++ b/packages/flutter/lib/widgets.dart @@ -11,6 +11,7 @@ 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'; From 845c50be9e4d9584291a286ab9fecf4312e42b6d Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Tue, 20 Oct 2015 16:10:06 -0700 Subject: [PATCH 46/63] Improve comments describing FractionalOffset Fixes #1702 --- packages/flutter/lib/src/rendering/box.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/flutter/lib/src/rendering/box.dart b/packages/flutter/lib/src/rendering/box.dart index 486aac8954..db5655459c 100644 --- a/packages/flutter/lib/src/rendering/box.dart +++ b/packages/flutter/lib/src/rendering/box.dart @@ -740,8 +740,8 @@ abstract class RenderBoxContainerDefaultsMixin Date: Tue, 20 Oct 2015 16:23:43 -0700 Subject: [PATCH 47/63] Rev pub packages --- packages/flutter/pubspec.yaml | 6 +++--- packages/flutter_sprites/pubspec.yaml | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/flutter/pubspec.yaml b/packages/flutter/pubspec.yaml index 5851cef409..0404b2a4b3 100644 --- a/packages/flutter/pubspec.yaml +++ b/packages/flutter/pubspec.yaml @@ -1,5 +1,5 @@ name: flutter -version: 0.0.7 +version: 0.0.8 author: Flutter Authors description: A framework for writing Flutter applications homepage: http://flutter.io @@ -9,8 +9,8 @@ dependencies: mojo_services: '>=0.3.0 <0.4.0' mojo: '>=0.2.0 <0.3.0' newton: '>=0.1.4 <0.2.0' - sky_engine: 0.0.38 - sky_services: 0.0.38 + sky_engine: 0.0.39 + sky_services: 0.0.39 sky_tools: '>=0.0.25 <0.1.0' vector_math: '>=1.4.3 <2.0.0' intl: '>=0.12.4+2 <0.13.0' diff --git a/packages/flutter_sprites/pubspec.yaml b/packages/flutter_sprites/pubspec.yaml index 5ef0ca10fc..f31ba60632 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.5 +version: 0.0.6 author: Flutter Authors homepage: http://flutter.io dependencies: - flutter: ">=0.0.7 <0.1.0" + flutter: ">=0.0.8 <0.1.0" sky_tools: ">=0.0.20 <0.1.0" box2d: ">=0.2.0 <0.3.0" From 44f6cfff9f6b160ebb77a9afa513fac52cbb5f1c Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Tue, 20 Oct 2015 18:10:56 -0700 Subject: [PATCH 48/63] Tighten flutter's dependency on mojo The 0.2.1 release of the mojo package isn't actually compatible with Flutter despite claiming to be a minor release. The real fix is to make Flutter compatible with that release, but there are several yak shaves involved. --- packages/flutter/pubspec.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/flutter/pubspec.yaml b/packages/flutter/pubspec.yaml index 0404b2a4b3..4ffee40971 100644 --- a/packages/flutter/pubspec.yaml +++ b/packages/flutter/pubspec.yaml @@ -1,5 +1,5 @@ name: flutter -version: 0.0.8 +version: 0.0.9 author: Flutter Authors description: A framework for writing Flutter applications homepage: http://flutter.io @@ -7,7 +7,7 @@ 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: 0.2.0 newton: '>=0.1.4 <0.2.0' sky_engine: 0.0.39 sky_services: 0.0.39 From 188aade214b51c9a6864fe37ca5d274d048aa1d0 Mon Sep 17 00:00:00 2001 From: Hixie Date: Wed, 21 Oct 2015 10:03:11 -0700 Subject: [PATCH 49/63] UniqueKey Sometimes you need a Key (not a GlobalKey) that is only equal to itself but can be used multiple times in the tree. Enter UniqueKey! --- packages/flutter/lib/src/widgets/framework.dart | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index 2a5aedc7b8..a3b6409d8d 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -42,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 From 7acc24e48633d565837acc82a09dfb35fe4e0514 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Wed, 21 Oct 2015 11:05:59 -0700 Subject: [PATCH 50/63] Rev pub packages --- packages/flutter/pubspec.yaml | 6 +++--- packages/updater/pubspec.yaml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/flutter/pubspec.yaml b/packages/flutter/pubspec.yaml index 4ffee40971..e8d50b5dab 100644 --- a/packages/flutter/pubspec.yaml +++ b/packages/flutter/pubspec.yaml @@ -1,13 +1,13 @@ name: flutter -version: 0.0.9 +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 + mojo_services: 0.4.0 + mojo: 0.3.0 newton: '>=0.1.4 <0.2.0' sky_engine: 0.0.39 sky_services: 0.0.39 diff --git a/packages/updater/pubspec.yaml b/packages/updater/pubspec.yaml index a1eb2a6f57..caced20b6d 100644 --- a/packages/updater/pubspec.yaml +++ b/packages/updater/pubspec.yaml @@ -4,7 +4,7 @@ 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 From 789031b5bdc0006726240f139c2a4e92cd0c4d1a Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Wed, 21 Oct 2015 11:13:08 -0700 Subject: [PATCH 51/63] Rev pub packages --- packages/flutter/pubspec.yaml | 4 ++-- packages/flutter_sprites/pubspec.yaml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/flutter/pubspec.yaml b/packages/flutter/pubspec.yaml index e8d50b5dab..e80192caad 100644 --- a/packages/flutter/pubspec.yaml +++ b/packages/flutter/pubspec.yaml @@ -9,8 +9,8 @@ dependencies: mojo_services: 0.4.0 mojo: 0.3.0 newton: '>=0.1.4 <0.2.0' - sky_engine: 0.0.39 - sky_services: 0.0.39 + 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' diff --git a/packages/flutter_sprites/pubspec.yaml b/packages/flutter_sprites/pubspec.yaml index f31ba60632..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.6 +version: 0.0.7 author: Flutter Authors homepage: http://flutter.io dependencies: - flutter: ">=0.0.8 <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" From babba2f0ec40aac005cc567eaa2ea245a3100010 Mon Sep 17 00:00:00 2001 From: Hixie Date: Wed, 21 Oct 2015 10:53:40 -0700 Subject: [PATCH 52/63] Make Route.build() arguments match RouteBuilder() Assert at build time that PageRoute route builders do not return null widget trees. Also very minor new code comments and code reorg to help make the heroes patch easier to review. (These are changes that are unrelated to Heroes but that were part of the Heroes patch.) --- packages/flutter/lib/src/material/dialog.dart | 6 +- packages/flutter/lib/src/material/drawer.dart | 2 +- .../lib/src/material/material_app.dart | 4 +- .../flutter/lib/src/material/popup_menu.dart | 2 +- .../flutter/lib/src/material/snack_bar.dart | 2 +- .../flutter/lib/src/widgets/drag_target.dart | 3 +- .../flutter/lib/src/widgets/navigator.dart | 109 ++++++++++++------ 7 files changed, 82 insertions(+), 46 deletions(-) diff --git a/packages/flutter/lib/src/material/dialog.dart b/packages/flutter/lib/src/material/dialog.dart index bb6157919f..e31b2f5f07 100644 --- a/packages/flutter/lib/src/material/dialog.dart +++ b/packages/flutter/lib/src/material/dialog.dart @@ -139,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, + performance: args.previousPerformance, opacity: new AnimatedValue(0.0, end: 1.0, curve: Curves.easeOut), - child: builder(new RouteArguments(navigator: navigator, previousPerformance: this.performance, nextPerformance: nextRoutePerformance)) + child: builder(args) ); } diff --git a/packages/flutter/lib/src/material/drawer.dart b/packages/flutter/lib/src/material/drawer.dart index d0dcdcb338..4f9151cacf 100644 --- a/packages/flutter/lib/src/material/drawer.dart +++ b/packages/flutter/lib/src/material/drawer.dart @@ -112,7 +112,7 @@ class _DrawerRoute extends Route { bool _interactive = true; - Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance) { + Widget build(RouteArguments args) { return new Focus( key: new GlobalObjectKey(this), autofocus: true, diff --git a/packages/flutter/lib/src/material/material_app.dart b/packages/flutter/lib/src/material/material_app.dart index 0d41ab62cd..afe72df031 100644 --- a/packages/flutter/lib/src/material/material_app.dart +++ b/packages/flutter/lib/src/material/material_app.dart @@ -26,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/popup_menu.dart b/packages/flutter/lib/src/material/popup_menu.dart index f20540e7fb..38dd165149 100644 --- a/packages/flutter/lib/src/material/popup_menu.dart +++ b/packages/flutter/lib/src/material/popup_menu.dart @@ -134,7 +134,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, diff --git a/packages/flutter/lib/src/material/snack_bar.dart b/packages/flutter/lib/src/material/snack_bar.dart index 340174daa0..7a0683e06a 100644 --- a/packages/flutter/lib/src/material/snack_bar.dart +++ b/packages/flutter/lib/src/material/snack_bar.dart @@ -102,7 +102,7 @@ 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 }) { diff --git a/packages/flutter/lib/src/widgets/drag_target.dart b/packages/flutter/lib/src/widgets/drag_target.dart index 5a6f237860..45590155fe 100644 --- a/packages/flutter/lib/src/widgets/drag_target.dart +++ b/packages/flutter/lib/src/widgets/drag_target.dart @@ -4,7 +4,6 @@ import 'dart:collection'; -import 'package:flutter/animation.dart'; import 'package:flutter/rendering.dart'; import 'basic.dart'; @@ -257,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/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index 358cab089e..99d5a34c77 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -9,8 +9,10 @@ import 'focus.dart'; import 'framework.dart'; import 'transitions.dart'; +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,7 +30,8 @@ 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; @@ -38,18 +41,21 @@ class Navigator extends StatefulComponent { NavigatorState createState() => new NavigatorState(); } +// The navigator tracks which "page" we are on. +// It also animates between these pages. + 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); + PageRoute route = new PageRoute(config.routes[kDefaultRouteName], name: kDefaultRouteName); + assert(route.hasContent); assert(!route.ephemeral); _insertRoute(route); } @@ -67,17 +73,20 @@ class NavigatorState extends State { 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)); } void push(Route route) { assert(!_debugCurrentlyHaveRoute(route)); setState(() { + // pop ephemeral routes (like popup menus) while (currentRoute.ephemeral) { currentRoute.didPop(null); _currentPosition -= 1; } + // add the new route _currentPosition += 1; _insertRoute(route); }); @@ -87,21 +96,21 @@ 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); + // pop the route currentRoute.didPop(result); _currentPosition -= 1; }); @@ -142,8 +151,8 @@ class NavigatorState extends State { Widget build(BuildContext context) { List visibleRoutes = new List(); - bool alreadyInsertModalBarrier = false; - PerformanceView nextPerformance; + bool alreadyInsertedModalBarrier = false; + Route nextContentRoute; for (int i = _history.length-1; i >= 0; i -= 1) { Route route = _history[i]; if (!route.hasContent) { @@ -153,20 +162,20 @@ class NavigatorState extends State { visibleRoutes.add( new KeyedSubtree( key: new ObjectKey(route), - child: route.build(this, nextPerformance) + child: route._internalBuild(nextContentRoute) ) ); if (route.isActuallyOpaque) 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; } return new Focus(child: new Stack(visibleRoutes.reversed.toList())); } @@ -227,13 +236,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,22 +252,36 @@ 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. + Widget _internalBuild(Route nextRoute) { + assert(navigator != null); + return build(new RouteArguments( + navigator, + previousPerformance: performance, + nextPerformance: nextRoute?.performance + )); + } + + Widget build(RouteArguments args); + + String get debugLabel => '$runtimeType'; + String toString() => '$runtimeType(performance: $performance)'; } abstract class PerformanceRoute extends Route { @@ -272,14 +294,12 @@ 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); - void didPush(NavigatorState navigator) { super.didPush(navigator); _performance?.forward(); @@ -294,15 +314,21 @@ 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. class PageRoute extends PerformanceRoute { - PageRoute(this.builder); + PageRoute(this._builder, { + this.name: '' + }) { + assert(_builder != null); + } - final RouteBuilder builder; + final RouteBuilder _builder; + final String name; bool get opaque => true; Duration get transitionDuration => _kTransitionDuration; - Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance) { + Widget build(RouteArguments args) { // TODO(jackson): Hit testing should ignore transform // TODO(jackson): Block input unless content is interactive return new SlideTransition( @@ -311,10 +337,23 @@ class PageRoute extends PerformanceRoute { child: new FadeTransition( performance: performance, opacity: new AnimatedValue(0.0, end: 1.0, curve: Curves.easeOut), - child: builder(new RouteArguments(navigator: navigator, previousPerformance: this.performance, nextPerformance: nextRoutePerformance)) + 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 { @@ -335,5 +374,5 @@ class StateRoute extends Route { super.didPop(result); } - Widget build(NavigatorState navigator, PerformanceView nextRoutePerformance) => null; + Widget build(RouteArguments args) => null; } From 86087cbb081b45a0ca7d2cd925f1ddd36686bd88 Mon Sep 17 00:00:00 2001 From: Hixie Date: Wed, 21 Oct 2015 10:07:15 -0700 Subject: [PATCH 53/63] RotationTransition A transition that rotates its contents. --- .../flutter/lib/src/widgets/transitions.dart | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/packages/flutter/lib/src/widgets/transitions.dart b/packages/flutter/lib/src/widgets/transitions.dart index c696131a40..6278378904 100644 --- a/packages/flutter/lib/src/widgets/transitions.dart +++ b/packages/flutter/lib/src/widgets/transitions.dart @@ -2,9 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:math' as math; + import 'package:flutter/animation.dart'; -import 'package:vector_math/vector_math_64.dart' show Matrix4; import 'package:flutter/rendering.dart'; +import 'package:vector_math/vector_math_64.dart' show Matrix4; import 'basic.dart'; import 'framework.dart'; @@ -90,6 +92,29 @@ class SlideTransition extends TransitionWithChild { } } +class RotationTransition extends TransitionWithChild { + RotationTransition({ + Key key, + this.turns, + PerformanceView performance, + Widget child + }) : super(key: key, + performance: performance, + child: child); + + final AnimatedValue 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, From 545db87ace573452b7d0304b7674d9a5d66ec06a Mon Sep 17 00:00:00 2001 From: Hixie Date: Wed, 21 Oct 2015 09:51:34 -0700 Subject: [PATCH 54/63] AlwaysCompletePerformance, ReversePerformance These new PerformanceView classes are transforms over PerformanceViews. The first is a cheap way to tell code that expects a performance to not animate after all, and the other is a way to replace a view of a performance going in one direction with a view of a performance going in the other direction. See also https://github.com/flutter/engine/issues/1708 --- .../lib/src/animation/performance.dart | 100 ++++++++++++++++-- 1 file changed, 92 insertions(+), 8 deletions(-) diff --git a/packages/flutter/lib/src/animation/performance.dart b/packages/flutter/lib/src/animation/performance.dart index e959d16961..f269e0886d 100644 --- a/packages/flutter/lib/src/animation/performance.dart +++ b/packages/flutter/lib/src/animation/performance.dart @@ -44,9 +44,19 @@ 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; @@ -58,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 @@ -86,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 @@ -103,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(); From bc6d17db3b27a81659fafbc9a6cf784a27da8994 Mon Sep 17 00:00:00 2001 From: Hixie Date: Wed, 21 Oct 2015 11:57:26 -0700 Subject: [PATCH 55/63] Use a card for the stock symbol viewer page. --- examples/stocks/lib/stock_home.dart | 4 +- examples/stocks/lib/stock_row.dart | 97 ++++++++++---------- examples/stocks/lib/stock_symbol_viewer.dart | 60 ++++++------ 3 files changed, 80 insertions(+), 81 deletions(-) diff --git a/examples/stocks/lib/stock_home.dart b/examples/stocks/lib/stock_home.dart index f613dc74cb..45dd149e53 100644 --- a/examples/stocks/lib/stock_home.dart +++ b/examples/stocks/lib/stock_home.dart @@ -186,13 +186,13 @@ 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, GlobalKey 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) { + onOpen: (Stock stock, GlobalKey arrowKey) { config.navigator.pushNamed('/stock/${stock.symbol}'); } ); diff --git a/examples/stocks/lib/stock_row.dart b/examples/stocks/lib/stock_row.dart index 3014eb21ff..c57c119d7b 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 GlobalKey { + 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, GlobalKey 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), + _arrowKey = new StockRowPartKey(stock, StockRowPartKind.arrow), super(key: new GlobalObjectKey(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)}"; - 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,38 @@ 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( + 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 + ) + ), + 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_symbol_viewer.dart b/examples/stocks/lib/stock_symbol_viewer.dart index 4faf71d458..c5e06a2895 100644 --- a/examples/stocks/lib/stock_symbol_viewer.dart +++ b/examples/stocks/lib/stock_symbol_viewer.dart @@ -4,49 +4,53 @@ part of stocks; -class StockSymbolViewer extends StatefulComponent { +class StockSymbolViewer extends StatelessComponent { StockSymbolViewer(this.navigator, 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.pop ), - center: new Text('${config.stock.name} (${config.stock.symbol})') + center: new Text(stock.name) ), 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 + new Container( + 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 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}'), + ]) + ) + ) ) - ) ]) ); } From 4ab0720189397dec7434acd99392491ef97900b9 Mon Sep 17 00:00:00 2001 From: Hixie Date: Wed, 21 Oct 2015 12:05:58 -0700 Subject: [PATCH 56/63] Debug grid over the navigator stack This grid makes it significantly easier to track down errors when you're looking at coordinates in a render tree dump and want to see if they're what you expect or if they're wildly away from the right location. --- .../flutter/lib/src/widgets/gridpaper.dart | 36 +++++++++++++++++++ .../flutter/lib/src/widgets/navigator.dart | 19 ++++++++-- 2 files changed, 53 insertions(+), 2 deletions(-) create mode 100644 packages/flutter/lib/src/widgets/gridpaper.dart 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/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index 99d5a34c77..5dbb6966fd 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -3,11 +3,19 @@ // 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 '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 = '/'; @@ -149,8 +157,15 @@ class NavigatorState extends State { }); } - Widget build(BuildContext context) { - List visibleRoutes = new List(); + Widget build(BuildContext context) { + List visibleRoutes = []; + + assert(() { + if (debugShowGrid) + visibleRoutes.add(new GridPaper(color: debugGridColor)); + return true; + }); + bool alreadyInsertedModalBarrier = false; Route nextContentRoute; for (int i = _history.length-1; i >= 0; i -= 1) { From 9a0b1f815c437c24e800a09de13fd2b416a7e707 Mon Sep 17 00:00:00 2001 From: Hixie Date: Wed, 21 Oct 2015 13:35:41 -0700 Subject: [PATCH 57/63] Export gridpaper.dart --- packages/flutter/lib/widgets.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/flutter/lib/widgets.dart b/packages/flutter/lib/widgets.dart index 434ebf1258..53a4b1c31b 100644 --- a/packages/flutter/lib/widgets.dart +++ b/packages/flutter/lib/widgets.dart @@ -15,6 +15,7 @@ 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/homogeneous_viewport.dart'; export 'src/widgets/mimic.dart'; export 'src/widgets/mixed_viewport.dart'; From 104e125d932cb2c344355103a7ac341ed2570f75 Mon Sep 17 00:00:00 2001 From: Matt Perry Date: Wed, 21 Oct 2015 17:20:25 -0400 Subject: [PATCH 58/63] Create new 'flx' package. Just a copy for now. This will be shared by sky/updater and flutter_tools. Currently bundle.dart and signing.dart are unmodified copies of the files from updater and flutter_tools, respectively. This is so future changes are easier to see. --- packages/flx/lib/bundle.dart | 75 ++++++++++++++++++++++++++++ packages/flx/lib/signing.dart | 94 +++++++++++++++++++++++++++++++++++ packages/flx/pubspec.yaml | 18 +++++++ 3 files changed, 187 insertions(+) create mode 100644 packages/flx/lib/bundle.dart create mode 100644 packages/flx/lib/signing.dart create mode 100644 packages/flx/pubspec.yaml 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..a1eb2a6f57 --- /dev/null +++ b/packages/flx/pubspec.yaml @@ -0,0 +1,18 @@ +name: updater +version: 0.0.1 +author: Flutter Authors +description: The autoupdater for flutter +homepage: http://flutter.io +dependencies: + mojo: '>=0.2.0 <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 +environment: + sdk: '>=1.12.0 <2.0.0' From 6c007406637986c7192d8abc5edca38167697540 Mon Sep 17 00:00:00 2001 From: Matt Perry Date: Wed, 21 Oct 2015 17:55:20 -0400 Subject: [PATCH 59/63] deps --- packages/flx/pubspec.yaml | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/packages/flx/pubspec.yaml b/packages/flx/pubspec.yaml index a1eb2a6f57..323cd8c5cd 100644 --- a/packages/flx/pubspec.yaml +++ b/packages/flx/pubspec.yaml @@ -1,18 +1,13 @@ -name: updater +name: flx version: 0.0.1 author: Flutter Authors -description: The autoupdater for flutter +description: Library for dealing with Flutter bundle (.flx) files homepage: http://flutter.io dependencies: - mojo: '>=0.2.0 <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 + 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' From 82887696617af9a750bae5f516baaaf187d60b4e Mon Sep 17 00:00:00 2001 From: Jason Simmons Date: Wed, 21 Oct 2015 16:40:02 -0700 Subject: [PATCH 60/63] Fix a type mismatch in IconThemeData.operator== --- packages/flutter/lib/src/material/icon_theme_data.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/flutter/lib/src/material/icon_theme_data.dart b/packages/flutter/lib/src/material/icon_theme_data.dart index 9ba71ab451..e4a925c697 100644 --- a/packages/flutter/lib/src/material/icon_theme_data.dart +++ b/packages/flutter/lib/src/material/icon_theme_data.dart @@ -12,7 +12,7 @@ class IconThemeData { if (other is! IconThemeData) return false; final IconThemeData typedOther = other; - return color == typedOther; + return color == typedOther.color; } int get hashCode => color.hashCode; From fa8c45151f9de9ddbd7e9dc21250001bed4e3b09 Mon Sep 17 00:00:00 2001 From: Hixie Date: Fri, 2 Oct 2015 15:07:35 -0700 Subject: [PATCH 61/63] Heroes --- examples/stocks/lib/stock_home.dart | 8 +- examples/stocks/lib/stock_row.dart | 17 +- examples/stocks/lib/stock_symbol_viewer.dart | 9 +- packages/flutter/lib/src/widgets/heroes.dart | 389 ++++++++++++++++++ .../flutter/lib/src/widgets/navigator.dart | 222 +++++++++- packages/flutter/lib/widgets.dart | 1 + 6 files changed, 615 insertions(+), 31 deletions(-) create mode 100644 packages/flutter/lib/src/widgets/heroes.dart diff --git a/examples/stocks/lib/stock_home.dart b/examples/stocks/lib/stock_home.dart index 45dd149e53..e8b143ef39 100644 --- a/examples/stocks/lib/stock_home.dart +++ b/examples/stocks/lib/stock_home.dart @@ -186,14 +186,16 @@ class StockHomeState extends State { Widget buildStockList(BuildContext context, Iterable stocks) { return new StockList( stocks: stocks.toList(), - onAction: (Stock stock, GlobalKey arrowKey) { + onAction: (Stock stock, Key arrowKey) { setState(() { stock.percentChange = 100.0 * (1.0 / stock.lastSale); stock.lastSale += 1.0; }); }, - onOpen: (Stock stock, GlobalKey arrowKey) { - 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); } ); } diff --git a/examples/stocks/lib/stock_row.dart b/examples/stocks/lib/stock_row.dart index c57c119d7b..5f2010ce8d 100644 --- a/examples/stocks/lib/stock_row.dart +++ b/examples/stocks/lib/stock_row.dart @@ -6,7 +6,7 @@ part of stocks; enum StockRowPartKind { arrow } -class StockRowPartKey extends GlobalKey { +class StockRowPartKey extends Key { const StockRowPartKey(this.stock, this.part) : super.constructor(); final Stock stock; final StockRowPartKind part; @@ -21,7 +21,7 @@ class StockRowPartKey extends GlobalKey { String toString() => '[StockRowPartKey ${stock.symbol}:${part.toString().split(".")[1]})]'; } -typedef void StockRowActionCallback(Stock stock, GlobalKey arrowKey); +typedef void StockRowActionCallback(Stock stock, Key arrowKey); class StockRow extends StatelessComponent { StockRow({ @@ -30,7 +30,7 @@ class StockRow extends StatelessComponent { this.onLongPressed }) : this.stock = stock, _arrowKey = new StockRowPartKey(stock, StockRowPartKind.arrow), - super(key: new GlobalObjectKey(stock)); + super(key: new ObjectKey(stock)); final Stock stock; final StockRowActionCallback onPressed; @@ -53,7 +53,7 @@ class StockRow extends StatelessComponent { } 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; @@ -69,9 +69,12 @@ class StockRow extends StatelessComponent { ), child: new Row([ new Container( - key: _arrowKey, - child: new StockArrow(percentChange: stock.percentChange), - margin: const EdgeDims.only(right: 5.0) + 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([ diff --git a/examples/stocks/lib/stock_symbol_viewer.dart b/examples/stocks/lib/stock_symbol_viewer.dart index c5e06a2895..bef0c27f52 100644 --- a/examples/stocks/lib/stock_symbol_viewer.dart +++ b/examples/stocks/lib/stock_symbol_viewer.dart @@ -36,7 +36,11 @@ class StockSymbolViewer extends StatelessComponent { '${stock.symbol}', style: Theme.of(context).text.display2 ), - new StockArrow(percentChange: stock.percentChange) + new Hero( + tag: StockRowPartKind.arrow, + turns: 2, + child: new StockArrow(percentChange: stock.percentChange) + ), ], justifyContent: FlexJustifyContent.spaceBetween ), @@ -51,7 +55,8 @@ class StockSymbolViewer extends StatelessComponent { ) ) ) - ]) + ] + ) ); } diff --git a/packages/flutter/lib/src/widgets/heroes.dart b/packages/flutter/lib/src/widgets/heroes.dart new file mode 100644 index 0000000000..cb0465c712 --- /dev/null +++ b/packages/flutter/lib/src/widgets/heroes.dart @@ -0,0 +1,389 @@ +// 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 'navigator.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.navigator, + this.tag, + this.child, + this.turns: 1 + }) : super(key: key) { + assert(tag != null); + } + + final NavigatorState navigator; + 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/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index 5dbb6966fd..df59effe94 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -8,6 +8,7 @@ import 'package:flutter/rendering.dart'; import 'basic.dart'; import 'focus.dart'; import 'framework.dart'; +import 'heroes.dart'; import 'transitions.dart'; import 'gridpaper.dart'; @@ -51,6 +52,40 @@ class Navigator extends StatefulComponent { // 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 { @@ -62,6 +97,7 @@ class NavigatorState extends State { void initState() { super.initState(); + _activeHeroes = new HeroParty(onQuestFinished: _handleHeroQuestFinished); PageRoute route = new PageRoute(config.routes[kDefaultRouteName], name: kDefaultRouteName); assert(route.hasContent); assert(!route.ephemeral); @@ -76,14 +112,22 @@ class NavigatorState extends State { )); } - void pushNamed(String name) { + void pushNamed(String name, { Set mostValuableKeys }) { RouteBuilder generateRoute() { assert(config.onGenerateRoute != null); return config.onGenerateRoute(name); } final RouteBuilder builder = config.routes[name] ?? generateRoute() ?? config.onUnknownRoute; assert(builder != null); // 404 getting your 404! - push(new PageRoute(builder, name: name)); + 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) { @@ -94,6 +138,14 @@ class NavigatorState extends State { 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); @@ -118,6 +170,14 @@ class NavigatorState extends State { 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; @@ -153,11 +213,17 @@ 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); }); } - Widget build(BuildContext context) { + PerformanceView _currentHeroPerformance; + + Widget build(BuildContext context) { List visibleRoutes = []; assert(() { @@ -166,22 +232,35 @@ class NavigatorState extends State { 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._internalBuild(nextContentRoute) - ) - ); - 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 && !alreadyInsertedModalBarrier) { visibleRoutes.add(new Listener( @@ -192,12 +271,54 @@ class NavigatorState extends State { } 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 @@ -284,21 +405,56 @@ abstract class Route { /// Called by the navigator.build() function if hasContent is true, to get the /// subtree for this route. - Widget _internalBuild(Route nextRoute) { + /// + /// 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 build(new RouteArguments( + 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)'; + + String toString() => '$runtimeType(performance: $performance; key: $_subtreeKey)'; } + abstract class PerformanceRoute extends Route { PerformanceRoute() { _performance = createPerformance(); @@ -315,6 +471,22 @@ abstract class PerformanceRoute extends Route { Duration get transitionDuration; + 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); _performance?.forward(); @@ -330,27 +502,39 @@ 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, { - this.name: '' - }) { + this.name: '', + Set mostValuableKeys + }) : _mostValuableKeys = mostValuableKeys { assert(_builder != null); } final RouteBuilder _builder; final String name; + final Set _mostValuableKeys; + + Set get mostValuableKeys => _mostValuableKeys; bool get opaque => true; Duration get transitionDuration => _kTransitionDuration; + 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, + performance: args.previousPerformance, position: new AnimatedValue(_kTransitionStartPoint, end: Point.origin, curve: Curves.easeOut), child: new FadeTransition( - performance: performance, + performance: args.previousPerformance, opacity: new AnimatedValue(0.0, end: 1.0, curve: Curves.easeOut), child: invokeBuilder(args) ) diff --git a/packages/flutter/lib/widgets.dart b/packages/flutter/lib/widgets.dart index 53a4b1c31b..a18ebef3d7 100644 --- a/packages/flutter/lib/widgets.dart +++ b/packages/flutter/lib/widgets.dart @@ -16,6 +16,7 @@ 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'; From de395582d5c83a7927572ee91c120d186e8d2cb7 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Thu, 22 Oct 2015 11:17:20 -0700 Subject: [PATCH 62/63] Add Navigator.of Now you don't need to pass the navigator around everywhere. --- examples/address_book/lib/main.dart | 6 +- examples/fitness/lib/feed.dart | 20 ++--- examples/fitness/lib/measurement.dart | 25 ++++--- examples/fitness/lib/settings.dart | 18 +++-- examples/stocks/lib/main.dart | 2 +- examples/stocks/lib/stock_home.dart | 20 ++--- examples/stocks/lib/stock_menu.dart | 73 +++++++++---------- examples/stocks/lib/stock_settings.dart | 15 ++-- examples/stocks/lib/stock_symbol_viewer.dart | 7 +- examples/widgets/card_collection.dart | 10 +-- examples/widgets/indexed_stack.dart | 10 +-- examples/widgets/pageable_list.dart | 8 +- examples/widgets/scrollbar.dart | 6 +- packages/flutter/lib/src/material/dialog.dart | 6 +- packages/flutter/lib/src/material/drawer.dart | 5 +- .../flutter/lib/src/material/popup_menu.dart | 19 ++--- .../flutter/lib/src/material/snack_bar.dart | 4 +- packages/flutter/lib/src/widgets/heroes.dart | 7 +- .../flutter/lib/src/widgets/navigator.dart | 18 ++++- packages/unit/test/widget/drawer_test.dart | 4 +- packages/unit/test/widget/snack_bar_test.dart | 2 +- 21 files changed, 139 insertions(+), 146 deletions(-) diff --git a/examples/address_book/lib/main.dart b/examples/address_book/lib/main.dart index 9f79aeeb00..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"), @@ -96,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 4208a112fb..e49473ccf8 100644 --- a/examples/fitness/lib/feed.dart +++ b/examples/fitness/lib/feed.dart @@ -67,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( @@ -117,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: () { @@ -191,7 +191,7 @@ class FeedFragmentState extends State { } 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); }); @@ -220,10 +220,6 @@ class FeedFragmentState extends State { } class AddItemDialog extends StatefulComponent { - AddItemDialog(this.navigator); - - final NavigatorState navigator; - AddItemDialogState createState() => new AddItemDialogState(); } @@ -253,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/measurement.dart b/examples/fitness/lib/measurement.dart index 394d86c507..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,16 +158,16 @@ 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) { diff --git a/examples/fitness/lib/settings.dart b/examples/fitness/lib/settings.dart index f33b6f0c9c..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,24 +72,25 @@ 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) { 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_home.dart b/examples/stocks/lib/stock_home.dart index e8b143ef39..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') ), @@ -246,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_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_settings.dart b/examples/stocks/lib/stock_settings.dart index d618bae8cb..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; } } diff --git a/examples/stocks/lib/stock_symbol_viewer.dart b/examples/stocks/lib/stock_symbol_viewer.dart index bef0c27f52..4ef3eb697b 100644 --- a/examples/stocks/lib/stock_symbol_viewer.dart +++ b/examples/stocks/lib/stock_symbol_viewer.dart @@ -5,9 +5,8 @@ part of stocks; class StockSymbolViewer extends StatelessComponent { - StockSymbolViewer(this.navigator, this.stock); + StockSymbolViewer(this.stock); - final NavigatorState navigator; final Stock stock; Widget build(BuildContext context) { @@ -20,7 +19,9 @@ class StockSymbolViewer extends StatelessComponent { toolBar: new ToolBar( left: new IconButton( icon: 'navigation/arrow_back', - onPressed: navigator.pop + onPressed: () { + Navigator.of(context).pop(); + } ), center: new Text(stock.name) ), diff --git a/examples/widgets/card_collection.dart b/examples/widgets/card_collection.dart index 756e0fc6d5..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) { @@ -374,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/indexed_stack.dart b/examples/widgets/indexed_stack.dart index a4e6a25de1..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,7 +29,7 @@ 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( @@ -61,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/pageable_list.dart b/examples/widgets/pageable_list.dart index 98a5e0fdb5..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( @@ -161,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/scrollbar.dart b/examples/widgets/scrollbar.dart index 66893bc7bd..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(); } @@ -65,7 +61,7 @@ void main() { accentColor: Colors.redAccent[200] ), routes: { - '/': (RouteArguments args) => new ScrollbarApp(navigator: args.navigator), + '/': (RouteArguments args) => new ScrollbarApp(), } )); } diff --git a/packages/flutter/lib/src/material/dialog.dart b/packages/flutter/lib/src/material/dialog.dart index e31b2f5f07..934b672b34 100644 --- a/packages/flutter/lib/src/material/dialog.dart +++ b/packages/flutter/lib/src/material/dialog.dart @@ -153,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 4f9151cacf..bfc7796ac1 100644 --- a/packages/flutter/lib/src/material/drawer.dart +++ b/packages/flutter/lib/src/material/drawer.dart @@ -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/popup_menu.dart b/packages/flutter/lib/src/material/popup_menu.dart index 38dd165149..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] )) ); @@ -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() { @@ -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/snack_bar.dart b/packages/flutter/lib/src/material/snack_bar.dart index 7a0683e06a..6783836555 100644 --- a/packages/flutter/lib/src/material/snack_bar.dart +++ b/packages/flutter/lib/src/material/snack_bar.dart @@ -105,7 +105,7 @@ class _SnackBarRoute extends PerformanceRoute { 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, @@ -113,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/widgets/heroes.dart b/packages/flutter/lib/src/widgets/heroes.dart index cb0465c712..49723869ab 100644 --- a/packages/flutter/lib/src/widgets/heroes.dart +++ b/packages/flutter/lib/src/widgets/heroes.dart @@ -7,7 +7,6 @@ import 'package:flutter/rendering.dart'; import 'basic.dart'; import 'framework.dart'; -import 'navigator.dart'; import 'transitions.dart'; // Heroes are the parts of an application's screen-to-screen transitions where a @@ -51,7 +50,7 @@ import 'transitions.dart'; // 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 +// their value at the target. See: https://github.com/flutter/engine/issues/1698 final Object centerOfAttentionHeroTag = new Object(); @@ -77,7 +76,6 @@ abstract class HeroHandle { class Hero extends StatefulComponent { Hero({ Key key, - this.navigator, this.tag, this.child, this.turns: 1 @@ -85,7 +83,6 @@ class Hero extends StatefulComponent { assert(tag != null); } - final NavigatorState navigator; final Object tag; final Widget child; final int turns; @@ -205,7 +202,7 @@ class HeroState extends State implements HeroHandle { child: config.child ) ); - case _HeroMode.taken: + case _HeroMode.taken: return new SizedBox(width: _size.width, height: _size.height); } } diff --git a/packages/flutter/lib/src/widgets/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index df59effe94..b8c072a77a 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -47,6 +47,22 @@ class Navigator extends StatefulComponent { 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(); } @@ -54,7 +70,7 @@ class Navigator extends StatefulComponent { // 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 diff --git a/packages/unit/test/widget/drawer_test.dart b/packages/unit/test/widget/drawer_test.dart index cc5fe28eae..0406bf5d4c 100644 --- a/packages/unit/test/widget/drawer_test.dart +++ b/packages/unit/test/widget/drawer_test.dart @@ -21,7 +21,7 @@ void main() { ); 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 @@ -50,7 +50,7 @@ void main() { ); 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/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) ); From 33c7820d7ec27c153b733d695b02bddadbc38c26 Mon Sep 17 00:00:00 2001 From: Hans Muller Date: Wed, 21 Oct 2015 16:51:16 -0700 Subject: [PATCH 63/63] Adds initial versions of DropdownButton DropdownMenuItem Adds a dropdown menu button as shown in the Material design spec here: https://www.google.com/design/spec/components/buttons.html#buttons-dropdown-buttons. It's the video at the bottom of this section of the Material design spec. This version of the component doesn't deal with scrollable menus or constrain the height of the menu. --- examples/widgets/dropdown.dart | 57 ++++ packages/flutter/lib/material.dart | 1 + .../flutter/lib/src/material/dropdown.dart | 257 ++++++++++++++++++ 3 files changed, 315 insertions(+) create mode 100644 examples/widgets/dropdown.dart create mode 100644 packages/flutter/lib/src/material/dropdown.dart 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/packages/flutter/lib/material.dart b/packages/flutter/lib/material.dart index 40c668cd63..aae1359b89 100644 --- a/packages/flutter/lib/material.dart +++ b/packages/flutter/lib/material.dart @@ -18,6 +18,7 @@ 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'; 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); + } + ); + } +}