From 955b3e21f757755019bbaea17a1862bfda62e452 Mon Sep 17 00:00:00 2001 From: Ian Hickson Date: Mon, 15 Aug 2016 12:50:24 -0700 Subject: [PATCH] A Flutter logo widget. (#5382) Instead of a PNG, the Flutter gallery widget is now drawn in code. There's now a FlutterLogoDecoration class that paints the flutter logo anywhere you can use a Decoration (e.g. AnimatedContainer). There's now a FlutterLogo class that honors the IconTheme. The About dialog box API now takes a Widget for the applicationIcon, instead of an ImageProvider. It uses IconTheme to make the icon the right size instead of using an Image widget. Add padding, duration, and curve properties to the DrawerHeader. Make the child of a DrawerHeader optional. Clean up UserAccuntsDrawerHeader a bit. Add some useful properties and methods to EdgeInsets. Add some debug logic to RenderDecoratedBox to catch unpaired save/restore calls when possible. Make GestureDetector fill its parent if it has no children. Fixes https://github.com/flutter/flutter/issues/5380 --- .../flutter_gallery/lib/gallery/drawer.dart | 86 +++- packages/flutter/lib/material.dart | 1 + packages/flutter/lib/painting.dart | 1 + packages/flutter/lib/src/material/about.dart | 30 +- .../lib/src/material/drawer_header.dart | 46 +- .../lib/src/material/flutter_logo.dart | 76 +++ .../material/user_accounts_drawer_header.dart | 34 +- .../flutter/lib/src/painting/decoration.dart | 4 + .../flutter/lib/src/painting/edge_insets.dart | 63 +++ .../lib/src/painting/flutter_logo.dart | 486 ++++++++++++++++++ .../flutter/lib/src/rendering/proxy_box.dart | 20 + packages/flutter/lib/src/widgets/image.dart | 2 +- .../lib/src/widgets/implicit_animations.dart | 2 + .../user_accounts_drawer_header_test.dart | 2 +- 14 files changed, 788 insertions(+), 65 deletions(-) create mode 100644 packages/flutter/lib/src/material/flutter_logo.dart create mode 100644 packages/flutter/lib/src/painting/flutter_logo.dart diff --git a/examples/flutter_gallery/lib/gallery/drawer.dart b/examples/flutter_gallery/lib/gallery/drawer.dart index 167c550751..231aefaeed 100644 --- a/examples/flutter_gallery/lib/gallery/drawer.dart +++ b/examples/flutter_gallery/lib/gallery/drawer.dart @@ -2,6 +2,8 @@ // 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/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -16,6 +18,69 @@ class LinkTextSpan extends TextSpan { ); } +class GalleryDrawerHeader extends StatefulWidget { + const GalleryDrawerHeader({ Key key }) : super(key: key); + + @override + _GalleryDrawerHeaderState createState() => new _GalleryDrawerHeaderState(); +} + +class _GalleryDrawerHeaderState extends State { + bool _logoHasName = true; + bool _logoHorizontal = true; + Map _swatch = Colors.blue; + + @override + Widget build(BuildContext context) { + final double systemTopPadding = MediaQuery.of(context).padding.top; + + return new DrawerHeader( + decoration: new FlutterLogoDecoration( + margin: new EdgeInsets.fromLTRB(12.0, 12.0 + systemTopPadding, 12.0, 12.0), + style: _logoHasName ? _logoHorizontal ? FlutterLogoStyle.horizontal + : FlutterLogoStyle.stacked + : FlutterLogoStyle.markOnly, + swatch: _swatch, + ), + duration: const Duration(milliseconds: 750), + child: new GestureDetector( + onLongPress: () { + setState(() { + _logoHorizontal = !_logoHorizontal; + if (!_logoHasName) + _logoHasName = true; + }); + }, + onTap: () { + setState(() { + _logoHasName = !_logoHasName; + }); + }, + onDoubleTap: () { + setState(() { + final List> options = >[]; + if (_swatch != Colors.blue) + options.addAll(>[Colors.blue, Colors.blue, Colors.blue, Colors.blue, Colors.blue, Colors.blue, Colors.blue]); + if (_swatch != Colors.amber) + options.addAll(>[Colors.amber, Colors.amber, Colors.amber]); + if (_swatch != Colors.red) + options.addAll(>[Colors.red, Colors.red, Colors.red]); + if (_swatch != Colors.indigo) + options.addAll(>[Colors.indigo, Colors.indigo, Colors.indigo]); + if (_swatch != Colors.pink) + options.addAll(>[Colors.pink]); + if (_swatch != Colors.purple) + options.addAll(>[Colors.purple]); + if (_swatch != Colors.cyan) + options.addAll(>[Colors.cyan]); + _swatch = options[new math.Random().nextInt(options.length)]; + }); + } + ) + ); + } +} + class GalleryDrawer extends StatelessWidget { GalleryDrawer({ Key key, @@ -41,24 +106,14 @@ class GalleryDrawer extends StatelessWidget { @override Widget build(BuildContext context) { - ThemeData themeData = Theme.of(context); - TextStyle aboutTextStyle = themeData.textTheme.body2; - TextStyle aboutLinkStyle = themeData.textTheme.body2.copyWith(color: themeData.accentColor); + final ThemeData themeData = Theme.of(context); + final TextStyle aboutTextStyle = themeData.textTheme.body2; + final TextStyle aboutLinkStyle = themeData.textTheme.body2.copyWith(color: themeData.accentColor); return new Drawer( child: new Block( children: [ - new DrawerHeader( - child: new Center( - child: new Padding( - padding: const EdgeInsets.all(16.0), - child: new Image.asset( - 'packages/flutter_gallery_assets/drawer_logo.png', - fit: ImageFit.contain - ) - ) - ) - ), + new GalleryDrawerHeader(), new DrawerItem( icon: new Icon(Icons.brightness_5), onPressed: () { onThemeChanged(true); }, @@ -119,8 +174,9 @@ class GalleryDrawer extends StatelessWidget { ) ), new AboutDrawerItem( + icon: new FlutterLogo(), applicationVersion: '2016 Q3 Preview', - applicationIcon: new AssetImage('packages/flutter_gallery_assets/about_logo.png'), + applicationIcon: new FlutterLogo(), applicationLegalese: '© 2016 The Chromium Authors', aboutBoxChildren: [ new Padding( diff --git a/packages/flutter/lib/material.dart b/packages/flutter/lib/material.dart index 95526b2d37..4dc39de22a 100644 --- a/packages/flutter/lib/material.dart +++ b/packages/flutter/lib/material.dart @@ -37,6 +37,7 @@ export 'src/material/drop_down.dart'; export 'src/material/flat_button.dart'; export 'src/material/flexible_space_bar.dart'; export 'src/material/floating_action_button.dart'; +export 'src/material/flutter_logo.dart'; export 'src/material/grid_tile.dart'; export 'src/material/grid_tile_bar.dart'; export 'src/material/icon.dart'; diff --git a/packages/flutter/lib/painting.dart b/packages/flutter/lib/painting.dart index a75db9b1a7..aceab78182 100644 --- a/packages/flutter/lib/painting.dart +++ b/packages/flutter/lib/painting.dart @@ -24,6 +24,7 @@ export 'src/painting/decoration.dart'; export 'src/painting/image_fit.dart'; export 'src/painting/edge_insets.dart'; export 'src/painting/fractional_offset.dart'; +export 'src/painting/flutter_logo.dart'; export 'src/painting/text_editing.dart'; export 'src/painting/text_painter.dart'; export 'src/painting/text_span.dart'; diff --git a/packages/flutter/lib/src/material/about.dart b/packages/flutter/lib/src/material/about.dart index 8254357c38..febe537294 100644 --- a/packages/flutter/lib/src/material/about.dart +++ b/packages/flutter/lib/src/material/about.dart @@ -4,7 +4,6 @@ import 'dart:async'; -import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:meta/meta.dart'; @@ -14,6 +13,8 @@ import 'dialog.dart'; import 'drawer_item.dart'; import 'flat_button.dart'; import 'icon.dart'; +import 'icon_theme.dart'; +import 'icon_theme_data.dart'; import 'page.dart'; import 'progress_indicator.dart'; import 'scaffold.dart'; @@ -84,9 +85,12 @@ class AboutDrawerItem extends StatelessWidget { /// /// By default no icon is shown. /// + /// Typically this will be an [ImageIcon] widget. It should honor the + /// [IconTheme]'s [IconThemeData.size]. + /// /// This is not necessarily the same as the icon shown on the drawer item /// itself, which is controlled by the [icon] property. - final ImageProvider applicationIcon; + final Widget applicationIcon; /// A string to show in small print in the [AboutDialog]. /// @@ -137,7 +141,7 @@ void showAboutDialog({ @required BuildContext context, String applicationName, String applicationVersion, - ImageProvider applicationIcon, + Widget applicationIcon, String applicationLegalese, List children }) { @@ -168,7 +172,7 @@ void showLicensePage({ @required BuildContext context, String applicationName, String applicationVersion, - ImageProvider applicationIcon, + Widget applicationIcon, String applicationLegalese }) { // TODO(ianh): remove pop once https://github.com/flutter/flutter/issues/4667 is fixed @@ -220,7 +224,10 @@ class AboutDialog extends StatelessWidget { /// The icon to show next to the application name. /// /// By default no icon is shown. - final ImageProvider applicationIcon; + /// + /// Typically this will be an [ImageIcon] widget. It should honor the + /// [IconTheme]'s [IconThemeData.size]. + final Widget applicationIcon; /// A string to show in small print. /// @@ -241,15 +248,10 @@ class AboutDialog extends StatelessWidget { Widget build(BuildContext context) { final String name = applicationName ?? _defaultApplicationName(context); final String version = applicationVersion ?? _defaultApplicationVersion(context); - final ImageProvider icon = applicationIcon ?? _defaultApplicationIcon(context); + final Widget icon = applicationIcon ?? _defaultApplicationIcon(context); List body = []; - if (icon != null) { - body.add(new Image( - image: icon, - width: 48.0, - height: 48.0 - )); - } + if (icon != null) + body.add(new IconTheme(data: new IconThemeData(size: 48.0), child: icon)); body.add(new Flexible( child: new Padding( padding: new EdgeInsets.symmetric(horizontal: 24.0), @@ -454,7 +456,7 @@ String _defaultApplicationVersion(BuildContext context) { return ''; } -ImageProvider _defaultApplicationIcon(BuildContext context) { +Widget _defaultApplicationIcon(BuildContext context) { // TODO(ianh): Get this from the embedder somehow. return null; } diff --git a/packages/flutter/lib/src/material/drawer_header.dart b/packages/flutter/lib/src/material/drawer_header.dart index 24fab981ee..2d9851c967 100644 --- a/packages/flutter/lib/src/material/drawer_header.dart +++ b/packages/flutter/lib/src/material/drawer_header.dart @@ -10,8 +10,8 @@ import 'theme.dart'; const double _kDrawerHeaderHeight = 160.0 + 1.0; // bottom edge /// The top-most region of a material design drawer. The header's [child] -/// widget is placed inside of a [Container] whose [decoration] can be passed as -/// an argument. +/// widget, if any, is placed inside a [Container] whose [decoration] can be +/// passed as an argument, inset by the given [padding]. /// /// Part of the material design [Drawer]. /// @@ -20,9 +20,10 @@ const double _kDrawerHeaderHeight = 160.0 + 1.0; // bottom edge /// See also: /// /// * [Drawer] +/// * [UserAccountsDrawerHeader], a variant of [DrawerHeader] that is +/// specialized for showing user accounts. /// * [DrawerItem] /// * - class DrawerHeader extends StatelessWidget { /// Creates a material design drawer header. /// @@ -30,15 +31,35 @@ class DrawerHeader extends StatelessWidget { const DrawerHeader({ Key key, this.decoration, + this.padding: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 8.0), + this.duration: const Duration(milliseconds: 250), + this.curve: Curves.fastOutSlowIn, this.child }) : super(key: key); /// Decoration for the main drawer header [Container]; useful for applying /// backgrounds. - final BoxDecoration decoration; + /// + /// This decoration will extend under the system status bar. + /// + /// If this is changed, it will be animated according to [duration] and [curve]. + final Decoration decoration; - /// A widget that extends behind the system status bar and is placed inside a - /// [Container]. + /// The padding by which to inset [child]. + /// + /// The [DrawerHeader] additionally offsets the child by the height of the + /// system status bar. + /// + /// If the child is null, the padding has no effect. + final EdgeInsets padding; + + /// The duration for animations of the [decoration]. + final Duration duration; + + /// The curve for animations of the [decoration]. + final Curve curve; + + /// A widget to be placed inside the drawer header, inset by the [padding]. final Widget child; @override @@ -56,15 +77,12 @@ class DrawerHeader extends StatelessWidget { ) ) ), - child: new Container( - padding: new EdgeInsets.only( - top: 16.0 + statusBarHeight, - left: 16.0, - right: 16.0, - bottom: 8.0 - ), + child: new AnimatedContainer( + padding: padding + new EdgeInsets.only(top: statusBarHeight), decoration: decoration, - child: new DefaultTextStyle( + duration: duration, + curve: curve, + child: child == null ? null : new DefaultTextStyle( style: Theme.of(context).textTheme.body2, child: child ) diff --git a/packages/flutter/lib/src/material/flutter_logo.dart b/packages/flutter/lib/src/material/flutter_logo.dart new file mode 100644 index 0000000000..0c3ead847d --- /dev/null +++ b/packages/flutter/lib/src/material/flutter_logo.dart @@ -0,0 +1,76 @@ +// Copyright 2016 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.dart'; +import 'icon_theme_data.dart'; +import 'colors.dart'; + +/// The Flutter logo, in widget form. This widget respects the [IconTheme]. +/// +/// See also: +/// +/// * [IconTheme], which provides ambient configuration for icons. +/// * [Icon], for showing icons the Material design icon library. +/// * [ImageIcon], for showing icons from [AssetImage]s or other [ImageProvider]s. +class FlutterLogo extends StatelessWidget { + /// Creates a widget that paints the Flutter logo. + /// + /// The [size] and [color] default to the value given by the current [IconTheme]. + const FlutterLogo({ + Key key, + this.size, + this.swatch: Colors.blue, + this.style: FlutterLogoStyle.markOnly, + this.duration: const Duration(milliseconds: 750), + }) : super(key: key); + + /// The size of the logo in logical pixels. + /// + /// The logo will be fit into a square this size. + /// + /// Defaults to the current [IconTheme] size, if any. If there is no + /// [IconTheme], or it does not specify an explicit size, then it defaults to + /// 24.0. + final double size; + + /// The colors to use to paint the logo. This map should contain at least two + /// values, one for 400 and one for 900. + /// + /// If possible, the default should be used. It corresponds to the + /// [Colors.blue] swatch. + /// + /// If for some reason that color scheme is impractical, the [Colors.amber], + /// [Colors.red], or [Colors.indigo] swatches can be used. These are Flutter's + /// secondary colors. + /// + /// In extreme cases where none of those four color schemes will work, + /// [Colors.pink], [Colors.purple], or [Colors.cyan] swatches can be used. + /// These are Flutter's tertiary colors. + final Map swatch; + + /// Whether and where to draw the "Flutter" text. By default, only the logo + /// itself is drawn. + final FlutterLogoStyle style; + + /// The length of time for the animation if the [style] or [swatch] properties + /// are changed. + final Duration duration; + + @override + Widget build(BuildContext context) { + final IconThemeData iconTheme = IconTheme.of(context).fallback(); + final double iconSize = size ?? iconTheme.size; + return new AnimatedContainer( + width: iconSize, + height: iconSize, + duration: duration, + decoration: new FlutterLogoDecoration( + swatch: swatch, + style: style, + ), + ); + } +} diff --git a/packages/flutter/lib/src/material/user_accounts_drawer_header.dart b/packages/flutter/lib/src/material/user_accounts_drawer_header.dart index f2ab14b525..7b970bef0b 100644 --- a/packages/flutter/lib/src/material/user_accounts_drawer_header.dart +++ b/packages/flutter/lib/src/material/user_accounts_drawer_header.dart @@ -22,9 +22,8 @@ import 'debug.dart'; /// See also: /// /// * [Drawer] -/// * [DrawerItem] +/// * [DrawerHeader], for a drawer header that doesn't show user acounts /// * - class UserAccountsDrawerHeader extends StatefulWidget { /// Creates a material design drawer header. /// @@ -43,41 +42,37 @@ class UserAccountsDrawerHeader extends StatefulWidget { /// section is pressed. final VoidCallback onDetailsPressed; - /// Decoration for the main drawer header container useful for applying - /// backgrounds. - final BoxDecoration decoration; + /// The background to show in the drawer header. + final Decoration decoration; /// A widget placed in the upper-left corner representing the current /// account picture. Normally a [CircleAvatar]. final Widget currentAccountPicture; - /// A list of widgets that represent the user's accounts. Up to three of them - /// are arranged in a row in the header's upper-right corner. Normally a list + /// A list of widgets that represent the user's accounts. Up to three of will + /// be arranged in a row in the header's upper-right corner. Normally a list /// of [CircleAvatar] widgets. final List otherAccountsPictures; - /// A widget placed on the top row of the account details representing - /// account name. + /// A widget placed on the top row of the account details representing the + /// account's name. final Widget accountName; - /// A widget placed on the bottom row of the account details representing - /// account email. + /// A widget placed on the bottom row of the account details representing the + /// account's e-mail address. final Widget accountEmail; @override - _UserAccountsDrawerHeaderState createState() => - new _UserAccountsDrawerHeaderState(); + _UserAccountsDrawerHeaderState createState() => new _UserAccountsDrawerHeaderState(); } class _UserAccountsDrawerHeaderState extends State { - /// Saves whether the account dropdown is open or not. - bool isOpen = false; + bool _isOpen = false; @override Widget build(BuildContext context) { assert(debugCheckHasMaterial(context)); - final List otherAccountsPictures = config.otherAccountsPictures ?? - []; + final List otherAccountsPictures = config.otherAccountsPictures ?? []; return new DrawerHeader( decoration: config.decoration, child: new Column( @@ -117,7 +112,7 @@ class _UserAccountsDrawerHeaderState extends State { child: new InkWell( onTap: () { setState(() { - isOpen = !isOpen; + _isOpen = !_isOpen; }); if (config.onDetailsPressed != null) config.onDetailsPressed(); @@ -146,8 +141,7 @@ class _UserAccountsDrawerHeaderState extends State { child: new Align( alignment: FractionalOffset.centerRight, child: new Icon( - isOpen ? Icons.arrow_drop_up : - Icons.arrow_drop_down, + _isOpen ? Icons.arrow_drop_up : Icons.arrow_drop_down, color: Colors.white ) ) diff --git a/packages/flutter/lib/src/painting/decoration.dart b/packages/flutter/lib/src/painting/decoration.dart index 198a10665c..3ff75cf8fa 100644 --- a/packages/flutter/lib/src/painting/decoration.dart +++ b/packages/flutter/lib/src/painting/decoration.dart @@ -114,6 +114,10 @@ abstract class BoxPainter { /// However, when its size changes, it could continue using those /// same instances, since the previous resources would no longer be /// relevant and thus losing them would not be an issue. + /// + /// Implementations should paint their decorations on the canvas in a + /// rectangle whose top left corner is at the given `offset` and whose size is + /// given by `configuration.size`. void paint(Canvas canvas, Offset offset, ImageConfiguration configuration); /// Callback that is invoked if an asynchronously-loading resource used by the diff --git a/packages/flutter/lib/src/painting/edge_insets.dart b/packages/flutter/lib/src/painting/edge_insets.dart index aede3926e7..a4a4272721 100644 --- a/packages/flutter/lib/src/painting/edge_insets.dart +++ b/packages/flutter/lib/src/painting/edge_insets.dart @@ -56,6 +56,22 @@ class EdgeInsets { /// The offset from the bottom. final double bottom; + /// An Offset describing the vector from the top left of a rectangle to the + /// top left of that rectangle inset by this object. + Offset get topLeft => new Offset(left, top); + + /// An Offset describing the vector from the top right of a rectangle to the + /// top right of that rectangle inset by this object. + Offset get topRight => new Offset(-right, top); + + /// An Offset describing the vector from the bottom left of a rectangle to the + /// bottom left of that rectangle inset by this object. + Offset get bottomLeft => new Offset(left, -bottom); + + /// An Offset describing the vector from the bottom right of a rectangle to the + /// bottom right of that rectangle inset by this object. + Offset get bottomRight => new Offset(-right, -bottom); + /// Whether every dimension is non-negative. bool get isNonNegative => left >= 0.0 && top >= 0.0 && right >= 0.0 && bottom >= 0.0; @@ -88,10 +104,57 @@ class EdgeInsets { /// rect is moved left by [left], the top edge of the rect is moved up by /// [top], the right edge of the rect is moved right by [right], and the /// bottom edge of the rect is moved down by [bottom]. + /// + /// See also: + /// + /// * [inflateSize], to inflate a [Size] rather than a [Rect]. + /// * [deflateRect], to deflate a [Rect] rather than inflating it. Rect inflateRect(Rect rect) { return new Rect.fromLTRB(rect.left - left, rect.top - top, rect.right + right, rect.bottom + bottom); } + /// Returns a new rect that is smaller than the given rect in each direction by + /// the amount of inset in each direction. Specifically, the left edge of the + /// rect is moved right by [left], the top edge of the rect is moved down by + /// [top], the right edge of the rect is moved left by [right], and the + /// bottom edge of the rect is moved up by [bottom]. + /// + /// If the argument's [Rect.size] is smaller than [collapsedSize], then the + /// resulting rectangle will have negative dimensions. + /// + /// See also: + /// + /// * [deflateSize], to deflate a [Size] rather than a [Rect]. + /// * [inflateRect], to inflate a [Rect] rather than deflating it. + Rect deflateRect(Rect rect) { + return new Rect.fromLTRB(rect.left + left, rect.top + top, rect.right - right, rect.bottom - bottom); + } + + /// Returns a new size that is bigger than the given size by the amount of + /// inset in the horizontal and vertical directions. + /// + /// See also: + /// + /// * [inflateRect], to inflate a [Rect] rather than a [Size]. + /// * [deflateSize], to deflate a [Size] rather than inflating it. + Size inflateSize(Size size) { + return new Size(size.width + horizontal, size.height + vertical); + } + + /// Returns a new size that is smaller than the given size by the amount of + /// inset in the horizontal and vertical directions. + /// + /// If the argument is smaller than [collapsedSize], then the resulting size + /// will have negative dimensions. + /// + /// See also: + /// + /// * [deflateRect], to deflate a [Rect] rather than a [Size]. + /// * [inflateSize], to inflate a [Size] rather than deflating it. + Size deflateSize(Size size) { + return new Size(size.width - horizontal, size.height - vertical); + } + /// Returns the difference between two EdgeInsets. EdgeInsets operator -(EdgeInsets other) { return new EdgeInsets.fromLTRB( diff --git a/packages/flutter/lib/src/painting/flutter_logo.dart b/packages/flutter/lib/src/painting/flutter_logo.dart new file mode 100644 index 0000000000..1062571b47 --- /dev/null +++ b/packages/flutter/lib/src/painting/flutter_logo.dart @@ -0,0 +1,486 @@ +// Copyright 2016 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:ui' as ui show Gradient, TextBox, lerpDouble; +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:flutter/services.dart'; + +import 'basic_types.dart'; +import 'decoration.dart'; +import 'fractional_offset.dart'; +import 'image_fit.dart'; +import 'text_editing.dart'; +import 'text_painter.dart'; +import 'text_span.dart'; +import 'text_style.dart'; + +/// Possible ways to draw Flutter's logo. +enum FlutterLogoStyle { + /// Show only Flutter's logo, not the "Flutter" label. + /// + /// This is the default behavior for [FlutterLogoDecoration] objects. + markOnly, + + /// Show Flutter's logo on the left, and the "Flutter" label to its right. + horizontal, + + /// Show Flutter's logo above the "Flutter" label. + stacked, +} + +const int _lightShade = 400; +const int _darkShade = 900; +const Map _kDefaultSwatch = const { + _lightShade: const Color(0xFF42A5F5), + _darkShade: const Color(0xFF0D47A1) +}; + +/// An immutable description of how to paint Flutter's logo. +class FlutterLogoDecoration extends Decoration { + /// Creates a decoration that knows how to paint Flutter's logo. + /// + /// The [swatch] controls the color used. The [style] controls whether and + /// where to draw the "Flutter" label. + /// + /// The [swatch] and [style] arguments must not be null. + const FlutterLogoDecoration({ + this.swatch: _kDefaultSwatch, + FlutterLogoStyle style: FlutterLogoStyle.markOnly, + this.margin: EdgeInsets.zero, + }) : style = style, + _position = style == FlutterLogoStyle.markOnly ? 0.0 : style == FlutterLogoStyle.horizontal ? 1.0 : -1.0, // ignore: CONST_EVAL_TYPE_BOOL_NUM_STRING + // (see https://github.com/dart-lang/sdk/issues/26980 for details about that ignore statement) + _opacity = 1.0; + + FlutterLogoDecoration._(this.swatch, this.style, this._position, this._opacity, this.margin); + + /// The colors to use to paint the logo. This map should contain at least two + /// values, one for 400 and one for 900. + /// + /// If possible, the default should be used. It corresponds to the + /// [Colors.blue] swatch from the Material library. + /// + /// If for some reason that color scheme is impractical, the [Colors.amber], + /// [Colors.red], or [Colors.indigo] swatches can be used. These are Flutter's + /// secondary colors. + /// + /// In extreme cases where none of those four color schemes will work, + /// [Colors.pink], [Colors.purple], or [Colors.cyan] swatches can be used. + /// These are Flutter's tertiary colors. + final Map swatch; + + /// Whether and where to draw the "Flutter" text. By default, only the logo + /// itself is drawn. + // This property isn't actually used when painting. It's only really used to + // set the internal _position property. + final FlutterLogoStyle style; + + // The following are set when lerping, to represent states that can't be + // represented by the constructor. + final double _position; // -1.0 for stacked, 1.0 for horizontal, 0.0 for no logo + final double _opacity; // 0.0 .. 1.0 + + /// How far to inset the logo from the edge of the container. + final EdgeInsets margin; + + bool get _inTransition => _opacity != 1.0 || (_position != -1.0 && _position != 0.0 && _position != 1.0); + + @override + bool debugAssertValid() { + assert(swatch != null + && swatch[_lightShade] != null + && swatch[_darkShade] != null + && style != null + && _position != null + && _position.isFinite + && _opacity != null + && _opacity >= 0.0 + && _opacity <= 1.0 + && margin != null); + return true; + } + + @override + bool get isComplex => !_inTransition; + + /// Linearly interpolate between two Flutter logo descriptions. + /// + /// Interpolates both the color and the style in a continuous fashion. + /// + /// See also [Decoration.lerp]. + static FlutterLogoDecoration lerp(FlutterLogoDecoration a, FlutterLogoDecoration b, double t) { + assert(a == null || a.debugAssertValid()); + assert(b == null || b.debugAssertValid()); + if (a == null && b == null) + return null; + if (a == null) { + return new FlutterLogoDecoration._( + b.swatch, + b.style, + b._position, + b._opacity * t.clamp(0.0, 1.0), + b.margin * t, + ); + } + if (b == null) { + return new FlutterLogoDecoration._( + a.swatch, + a.style, + a._position, + a._opacity * (1.0 - t).clamp(0.0, 1.0), + a.margin * t, + ); + } + return new FlutterLogoDecoration._( + _lerpSwatch(a.swatch, b.swatch, t), + t < 0.5 ? a.style : b.style, + a._position + (b._position - a._position) * t, + (a._opacity + (b._opacity - a._opacity) * t).clamp(0.0, 1.0), + EdgeInsets.lerp(a.margin, b.margin, t), + ); + } + + static Map _lerpSwatch(Map a, Map b, double t) { + assert(a != null); + assert(b != null); + return { + _lightShade: Color.lerp(a[_lightShade], b[_lightShade], t), + _darkShade: Color.lerp(a[_darkShade], b[_darkShade], t), + }; + } + + @override + FlutterLogoDecoration lerpFrom(Decoration a, double t) { + assert(debugAssertValid()); + if (a is! FlutterLogoDecoration) + return lerp(null, this, t); + assert(a.debugAssertValid); + return lerp(a, this, t); + } + + @override + FlutterLogoDecoration lerpTo(Decoration b, double t) { + assert(debugAssertValid()); + if (b is! FlutterLogoDecoration) + return lerp(this, null, t); + assert(b.debugAssertValid()); + return lerp(this, b, t); + } + + @override + // TODO(ianh): better hit testing + bool hitTest(Size size, Point position) => true; + + @override + BoxPainter createBoxPainter([VoidCallback onChanged]) { + assert(debugAssertValid()); + return new _FlutterLogoPainter(this); + } + + @override + bool operator ==(dynamic other) { + assert(debugAssertValid()); + if (identical(this, other)) + return true; + if (other is! FlutterLogoDecoration) + return false; + final FlutterLogoDecoration typedOther = other; + return swatch[_lightShade] == typedOther.swatch[_lightShade] + && swatch[_darkShade] == typedOther.swatch[_darkShade] + && _position == typedOther._position + && _opacity == typedOther._opacity; + } + + @override + int get hashCode { + assert(debugAssertValid()); + return hashValues( + swatch[_lightShade], + swatch[_darkShade], + _position, + _opacity + ); + } + + @override + String toString([String prefix = '']) { + final String extra = _inTransition ? ', transition $_position:$_opacity' : ''; + if (swatch == null) + return '$prefix$runtimeType(null, $style$extra)'; + return '$prefix$runtimeType(${swatch[_lightShade]}/${swatch[_darkShade]}, $style$extra)'; + } +} + + +/// An object that paints a [BoxDecoration] into a canvas. +class _FlutterLogoPainter extends BoxPainter { + _FlutterLogoPainter(this._config) : super(null) { + assert(_config != null); + _prepareText(); + } + + final FlutterLogoDecoration _config; + + // these are configured assuming a font size of 100.0. + TextPainter _textPainter; + Rect _textBoundingRect; + + void _prepareText() { + const String kLabel = 'Flutter'; + _textPainter = new TextPainter( + text: new TextSpan( + text: kLabel, + style: new TextStyle( + color: const Color(0xFF616161), + fontFamily: 'Roboto', + fontSize: 100.0 * 350.0 / 247.0, // 247 is the height of the F when the fontSize is 350, assuming device pixel ratio 1.0 + fontWeight: FontWeight.w300, + textBaseline: TextBaseline.alphabetic + ) + ) + ); + _textPainter.layout(); + final ui.TextBox textSize = _textPainter.getBoxesForSelection(new TextSelection(baseOffset: 0, extentOffset: kLabel.length)).single; + _textBoundingRect = new Rect.fromLTRB(textSize.left, textSize.top, textSize.right, textSize.bottom); + } + + // This class contains a lot of magic numbers. They were derived from the + // values in the SVG files exported from the original artwork source. + + void _paintLogo(Canvas canvas, Rect rect) { + assert(rect.width.truncate() == rect.height.truncate()); + + // Our points are in a coordinate space that's 166 pixels wide and 202 pixels high. + // First, transform the rectangle so that our coordinate space is a square 202 pixels + // to a side, with the top left at the origin. + canvas.save(); + canvas.translate(rect.left, rect.top); + canvas.scale(rect.width / 202.0, rect.height / 202.0); + // Next, offset it some more so that the 166 horizontal pixels are centered + // in that square (as opposed to being on the left side of it). This means + // that if we draw in the rectangle from 0,0 to 166,202, we are drawing in + // the center of the given rect. + canvas.translate((202.0 - 166.0) / 2.0, 0.0); + + // Set up the styles. + final Paint lightPaint = new Paint() + ..color = _config.swatch[_lightShade].withOpacity(0.8); + final Paint mediumPaint = new Paint() + ..color = _config.swatch[_lightShade]; + final Paint darkPaint = new Paint() + ..color = _config.swatch[_darkShade]; + + final ui.Gradient triangleGradient = new ui.Gradient.linear( + const [ + const Point(87.2623 + 37.9092, 28.8384 + 123.4389), + const Point(42.9205 + 37.9092, 35.0952 + 123.4389), + ], + [ + const Color(0xBFFFFFFF), + const Color(0xBFFCFCFC), + const Color(0xBFF4F4F4), + const Color(0xBFE5E5E5), + const Color(0xBFD1D1D1), + const Color(0xBFB6B6B6), + const Color(0xBF959595), + const Color(0xBF6E6E6E), + const Color(0xBF616161), + ], + [ 0.2690, 0.4093, 0.4972, 0.5708, 0.6364, 0.6968, 0.7533, 0.8058, 0.8219 ] + ); + final Paint trianglePaint = new Paint() + ..shader = triangleGradient + ..transferMode = TransferMode.multiply; + + final ui.Gradient rectangleGradient = new ui.Gradient.linear( + const [ + const Point(62.3643 + 37.9092, 40.135 + 123.4389), + const Point(54.0376 + 37.9092, 31.8083 + 123.4389), + ], + [ + const Color(0x80FFFFFF), + const Color(0x80FCFCFC), + const Color(0x80F4F4F4), + const Color(0x80E5E5E5), + const Color(0x80D1D1D1), + const Color(0x80B6B6B6), + const Color(0x80959595), + const Color(0x806E6E6E), + const Color(0x80616161), + ], + [ 0.4588, 0.5509, 0.6087, 0.6570, 0.7001, 0.7397, 0.7768, 0.8113, 0.8219 ], + ); + final Paint rectanglePaint = new Paint() + ..shader = rectangleGradient + ..transferMode = TransferMode.multiply; + + // Draw the basic shape. + final Path topBeam = new Path() + ..moveTo(37.7, 128.9) + ..lineTo(9.8, 101.0) + ..lineTo(100.4, 10.4) + ..lineTo(156.2, 10.4); + canvas.drawPath(topBeam, lightPaint); + + final Path middleBeam = new Path() + ..moveTo(156.2, 94.0) + ..lineTo(100.4, 94.0) + ..lineTo(79.5, 114.9) + ..lineTo(107.4, 142.8); + canvas.drawPath(middleBeam, lightPaint); + + final Path bottomBeam = new Path() + ..moveTo(79.5, 170.7) + ..lineTo(100.4, 191.6) + ..lineTo(156.2, 191.6) + ..lineTo(156.2, 191.6) + ..lineTo(107.4, 142.8); + canvas.drawPath(bottomBeam, darkPaint); + + canvas.save(); + canvas.transform(new Float64List.fromList(const [ + // careful, this is in _column_-major order + 0.7071, -0.7071, 0.0, 0.0, + 0.7071, 0.7071, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + -77.697, 98.057, 0.0, 1.0, + ])); + canvas.drawRect(new Rect.fromLTWH(59.8, 123.1, 39.4, 39.4), mediumPaint); + canvas.restore(); + + // The two gradients. + final Path triangle = new Path() + ..moveTo(79.5, 170.7) + ..lineTo(120.9, 156.4) + ..lineTo(107.4, 142.8); + canvas.drawPath(triangle, trianglePaint); + + final Path rectangle = new Path() + ..moveTo(107.4, 142.8) + ..lineTo(79.5, 170.7) + ..lineTo(86.1, 177.3) + ..lineTo(114.0, 149.4); + canvas.drawPath(rectangle, rectanglePaint); + + canvas.restore(); + } + + @override + void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { + offset += _config.margin.topLeft; + Size canvasSize = _config.margin.deflateSize(configuration.size); + Size logoSize; + if (_config._position > 0.0) { + // horizontal style + logoSize = const Size(820.0, 232.0); + } else if (_config._position < 0.0) { + // stacked style + logoSize = const Size(252.0, 306.0); + } else { + // only the mark + logoSize = const Size(202.0, 202.0); + } + final FittedSizes fittedSize = applyImageFit(ImageFit.contain, logoSize, canvasSize); + assert(fittedSize.source == logoSize); + final Rect rect = FractionalOffset.center.inscribe(fittedSize.destination, offset & canvasSize); + final double centerSquareHeight = canvasSize.shortestSide; + final Rect centerSquare = new Rect.fromLTWH( + offset.dx + (canvasSize.width - centerSquareHeight) / 2.0, + offset.dy + (canvasSize.height - centerSquareHeight) / 2.0, + centerSquareHeight, + centerSquareHeight + ); + + Rect logoTargetSquare; + if (_config._position > 0.0) { + // horizontal style + logoTargetSquare = new Rect.fromLTWH(rect.left, rect.top, rect.height, rect.height); + } else if (_config._position < 0.0) { + // stacked style + final double logoHeight = rect.height * 191.0 / 306.0; + logoTargetSquare = new Rect.fromLTWH( + rect.left + (rect.width - logoHeight) / 2.0, + rect.top, + logoHeight, + logoHeight + ); + } else { + // only the mark + logoTargetSquare = centerSquare; + } + final Rect logoSquare = Rect.lerp(centerSquare, logoTargetSquare, _config._position.abs()); + + if (_config._opacity < 1.0) { + canvas.saveLayer( + offset & canvasSize, + new Paint() + ..colorFilter = new ColorFilter.mode( + const Color(0xFFFFFFFF).withOpacity(_config._opacity), + TransferMode.modulate, + ) + ); + } + if (_config._position != 0.0) { + if (_config._position > 0.0) { + // horizontal style + final double fontSize = 2.0 / 3.0 * logoSquare.height * (1 - (10.4 * 2.0) / 202.0); + final double scale = fontSize / 100.0; + final double finalLeftTextPosition = // position of text in rest position + (256.4 / 820.0) * rect.width - // 256.4 is the distance from the left edge to the left of the F when the whole logo is 820.0 wide + (32.0 / 350.0) * fontSize; // 32 is the distance from the text bounding box edge to the left edge of the F when the font size is 350 + final double initialLeftTextPosition = // position of text when just starting the animation + rect.width / 2.0 - _textBoundingRect.width * scale; + final Offset textOffset = new Offset( + rect.left + ui.lerpDouble(initialLeftTextPosition, finalLeftTextPosition, _config._position), + rect.top + (rect.height - _textBoundingRect.height * scale) / 2.0 + ); + canvas.save(); + if (_config._position < 1.0) { + final Point center = logoSquare.center; + final Path path = new Path() + ..moveTo(center.x, center.y) + ..lineTo(center.x + rect.width, center.y - rect.width) + ..lineTo(center.x + rect.width, center.y + rect.width) + ..close(); + canvas.clipPath(path); + } + canvas.translate(textOffset.dx, textOffset.dy); + canvas.scale(scale, scale); + _textPainter.paint(canvas, Offset.zero); + canvas.restore(); + } else if (_config._position < 0.0) { + // stacked style + final double fontSize = 0.35 * logoTargetSquare.height * (1 - (10.4 * 2.0) / 202.0); + final double scale = fontSize / 100.0; + if (_config._position > -1.0) { + canvas.saveLayer(_textBoundingRect, new Paint()); + } else { + canvas.save(); + } + canvas.translate( + logoTargetSquare.center.x - (_textBoundingRect.width * scale / 2.0), + logoTargetSquare.bottom + ); + canvas.scale(scale, scale); + _textPainter.paint(canvas, Offset.zero); + if (_config._position > -1.0) { + canvas.drawRect(_textBoundingRect.inflate(_textBoundingRect.width * 0.5), new Paint() + ..transferMode = TransferMode.modulate + ..shader = new ui.Gradient.linear( + [new Point(_textBoundingRect.width * -0.5, 0.0), new Point(_textBoundingRect.width * 1.5, 0.0)], + [const Color(0xFFFFFFFF), const Color(0xFFFFFFFF), const Color(0x00FFFFFF), const Color(0x00FFFFFF)], + [ 0.0, math.max(0.0, _config._position.abs() - 0.1), math.min(_config._position.abs() + 0.1, 1.0), 1.0 ], + ) + ); + } + canvas.restore(); + } + } + _paintLogo(canvas, logoSquare); + if (_config._opacity < 1.0) + canvas.restore(); + } +} diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index 3c7e8d10e9..68a6f9d57e 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -1168,7 +1168,27 @@ class RenderDecoratedBox extends RenderProxyBox { _painter ??= _decoration.createBoxPainter(markNeedsPaint); final ImageConfiguration filledConfiguration = configuration.copyWith(size: size); if (position == DecorationPosition.background) { + int debugSaveCount; + assert(() { + debugSaveCount = context.canvas.getSaveCount(); + return true; + }); _painter.paint(context.canvas, offset, filledConfiguration); + assert(() { + if (debugSaveCount != context.canvas.getSaveCount()) { + throw new FlutterError( + '${_decoration.runtimeType} painter had mismatching save and restore calls.\n' + 'Before painting the decoration, the canvas save count was $debugSaveCount. ' + 'After painting it, the canvas save count was ${context.canvas.getSaveCount()}. ' + 'Every call to save() or saveLayer() must be matched by a call to restore().\n' + 'The decoration was:\n' + '${decoration.toString(" ")}\n' + 'The painter was:\n' + ' $_painter' + ); + } + return true; + }); if (decoration.isComplex) context.setIsComplexHint(); } diff --git a/packages/flutter/lib/src/widgets/image.dart b/packages/flutter/lib/src/widgets/image.dart index 7ee99fbc23..3b35af7c0e 100644 --- a/packages/flutter/lib/src/widgets/image.dart +++ b/packages/flutter/lib/src/widgets/image.dart @@ -21,7 +21,7 @@ ImageConfiguration createLocalImageConfiguration(BuildContext context, { Size si return new ImageConfiguration( bundle: DefaultAssetBundle.of(context), devicePixelRatio: MediaQuery.of(context).devicePixelRatio, - // TODO(ianh): provide the locale, + // TODO(ianh): provide the locale size: size, platform: Platform.operatingSystem ); diff --git a/packages/flutter/lib/src/widgets/implicit_animations.dart b/packages/flutter/lib/src/widgets/implicit_animations.dart index 9db7a76613..0c4e3be3c1 100644 --- a/packages/flutter/lib/src/widgets/implicit_animations.dart +++ b/packages/flutter/lib/src/widgets/implicit_animations.dart @@ -215,6 +215,8 @@ abstract class AnimatedWidgetBaseState exten /// different parameters to [Container]. For more complex animations, you'll /// likely want to use a subclass of [Transition] or use an /// [AnimationController] yourself. +/// +/// Properties that are null are not animated. class AnimatedContainer extends ImplicitlyAnimatedWidget { /// Creates a container that animates its parameters implicitly. /// diff --git a/packages/flutter/test/material/user_accounts_drawer_header_test.dart b/packages/flutter/test/material/user_accounts_drawer_header_test.dart index 0c58560e55..66009e8572 100644 --- a/packages/flutter/test/material/user_accounts_drawer_header_test.dart +++ b/packages/flutter/test/material/user_accounts_drawer_header_test.dart @@ -7,7 +7,7 @@ import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('UserAccuntsDrawerHeader test', (WidgetTester tester) async { + testWidgets('UserAccountsDrawerHeader test', (WidgetTester tester) async { final Key avatarA = new Key('A'); final Key avatarC = new Key('C'); final Key avatarD = new Key('D');