Commit 1b9cd520 authored by Ian Hickson's avatar Ian Hickson

Enable ALL THE LINTS

Well, all the easy ones, anyway.

For some reason `// ignore:` isn't working for me so I've disabled
lints that need that. Also disabled those that require a ton of work
(which I'm doing, but not in this PR, to keep it reviewable).

This adds:
- avoid_init_to_null
- library_names
- package_api_docs
- package_names
- package_prefixed_library_names
- prefer_is_not_empty
- sort_constructors_first
- sort_unnamed_constructors_first
- unnecessary_getters_setters
parent 75445144
......@@ -37,7 +37,7 @@ class RawKeyboardDemo extends StatefulComponent {
}
class _HardwareKeyDemoState extends State<RawKeyboardDemo> {
mojom.InputEvent _event = null;
mojom.InputEvent _event;
void _handleKey(mojom.InputEvent event) {
setState(() {
......
......@@ -5,14 +5,14 @@
part of cassowary;
class ConstantMember extends _EquationMember {
ConstantMember(this.value);
@override
final double value;
@override
bool get isConstant => true;
ConstantMember(this.value);
@override
Expression asExpression() => new Expression([], this.value);
}
......
......@@ -5,6 +5,11 @@
part of cassowary;
class Expression extends _EquationMember {
Expression(this.terms, this.constant);
Expression.fromExpression(Expression expr)
: this.terms = new List<Term>.from(expr.terms),
this.constant = expr.constant;
final List<Term> terms;
final double constant;
......@@ -15,11 +20,6 @@ class Expression extends _EquationMember {
@override
double get value => terms.fold(constant, (value, term) => value + term.value);
Expression(this.terms, this.constant);
Expression.fromExpression(Expression expr)
: this.terms = new List<Term>.from(expr.terms),
this.constant = expr.constant;
@override
Expression asExpression() => this;
......
......@@ -5,6 +5,8 @@
part of cassowary;
class Term extends _EquationMember {
Term(this.variable, this.coefficient);
final Variable variable;
final double coefficient;
......@@ -12,8 +14,6 @@ class Term extends _EquationMember {
double get value => coefficient * variable.value;
Term(this.variable, this.coefficient);
Expression asExpression() =>
new Expression([new Term(this.variable, this.coefficient)], 0.0);
......
......@@ -100,7 +100,7 @@ class GestureArena {
return; // This arena is being held for a long-lived member
}
_arenas.remove(arenaKey);
if (!state.members.isEmpty) {
if (state.members.isNotEmpty) {
// First member wins
state.members.first.acceptGesture(arenaKey);
// Give all the other members the bad news
......
......@@ -5,12 +5,12 @@
import 'events.dart';
/// An object that can hit-test pointers.
abstract class HitTestable {
abstract class HitTestable { // ignore: one_member_abstracts
void hitTest(HitTestResult result, Point position);
}
/// An object that can handle events.
abstract class HitTestTarget {
abstract class HitTestTarget { // ignore: one_member_abstracts
/// Override this function to receive events.
void handleEvent(PointerEvent event, HitTestEntry entry);
}
......
......@@ -226,7 +226,7 @@ class DayPicker extends StatelessComponent {
item = new Text("");
} else {
// Put a light circle around the selected day
BoxDecoration decoration = null;
BoxDecoration decoration;
if (selectedDate.year == year &&
selectedDate.month == month &&
selectedDate.day == day)
......
......@@ -304,7 +304,7 @@ class _PopupMenuRoute<T> extends PopupRoute<T> {
Color get barrierColor => null;
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> forwardAnimation) {
double selectedItemOffset = null;
double selectedItemOffset;
if (initialValue != null) {
selectedItemOffset = 0.0;
for (int i = 0; i < items.length; i++) {
......
......@@ -28,55 +28,6 @@ const Color _kDarkThemeHighlightColor = const Color(0x40CCCCCC);
const Color _kDarkThemeSplashColor = const Color(0x40CCCCCC);
class ThemeData {
ThemeData.raw({
this.brightness,
this.primaryColor,
this.primaryColorBrightness,
this.accentColor,
this.accentColorBrightness,
this.canvasColor,
this.cardColor,
this.dividerColor,
this.highlightColor,
this.splashColor,
this.unselectedColor,
this.disabledColor,
this.buttonColor,
this.selectionColor,
this.backgroundColor,
this.indicatorColor,
this.hintColor,
this.hintOpacity,
this.errorColor,
this.text,
this.primaryTextTheme,
this.primaryIconTheme
}) {
assert(brightness != null);
assert(primaryColor != null);
assert(primaryColorBrightness != null);
assert(accentColor != null);
assert(accentColorBrightness != null);
assert(canvasColor != null);
assert(cardColor != null);
assert(dividerColor != null);
assert(highlightColor != null);
assert(splashColor != null);
assert(unselectedColor != null);
assert(disabledColor != null);
assert(buttonColor != null);
assert(selectionColor != null);
assert(disabledColor != null);
assert(indicatorColor != null);
assert(hintColor != null);
assert(hintOpacity != null);
assert(errorColor != null);
assert(text != null);
assert(primaryTextTheme != null);
assert(primaryIconTheme != null);
}
factory ThemeData({
ThemeBrightness brightness,
Map<int, Color> primarySwatch,
......@@ -152,6 +103,54 @@ class ThemeData {
);
}
ThemeData.raw({
this.brightness,
this.primaryColor,
this.primaryColorBrightness,
this.accentColor,
this.accentColorBrightness,
this.canvasColor,
this.cardColor,
this.dividerColor,
this.highlightColor,
this.splashColor,
this.unselectedColor,
this.disabledColor,
this.buttonColor,
this.selectionColor,
this.backgroundColor,
this.indicatorColor,
this.hintColor,
this.hintOpacity,
this.errorColor,
this.text,
this.primaryTextTheme,
this.primaryIconTheme
}) {
assert(brightness != null);
assert(primaryColor != null);
assert(primaryColorBrightness != null);
assert(accentColor != null);
assert(accentColorBrightness != null);
assert(canvasColor != null);
assert(cardColor != null);
assert(dividerColor != null);
assert(highlightColor != null);
assert(splashColor != null);
assert(unselectedColor != null);
assert(disabledColor != null);
assert(buttonColor != null);
assert(selectionColor != null);
assert(disabledColor != null);
assert(indicatorColor != null);
assert(hintColor != null);
assert(hintOpacity != null);
assert(errorColor != null);
assert(text != null);
assert(primaryTextTheme != null);
assert(primaryIconTheme != null);
}
factory ThemeData.light() => new ThemeData(brightness: ThemeBrightness.light);
factory ThemeData.dark() => new ThemeData(brightness: ThemeBrightness.dark);
factory ThemeData.fallback() => new ThemeData.light();
......
......@@ -23,6 +23,6 @@ abstract class Decoration {
String toString([String prefix = '']) => '$prefix$runtimeType';
}
abstract class BoxPainter {
abstract class BoxPainter { // ignore: one_member_abstracts
void paint(Canvas canvas, Rect rect);
}
......@@ -773,7 +773,7 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget {
bool get debugDoingThisResize => _debugDoingThisResize;
bool _debugDoingThisLayout = false;
bool get debugDoingThisLayout => _debugDoingThisLayout;
static RenderObject _debugActiveLayout = null;
static RenderObject _debugActiveLayout;
static RenderObject get debugActiveLayout => _debugActiveLayout;
bool _debugMutationsLocked = false;
bool _debugCanParentUseSize;
......@@ -1140,7 +1140,7 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget {
static bool get debugDoingPaint => _debugDoingPaint;
bool _debugDoingThisPaint = false;
bool get debugDoingThisPaint => _debugDoingThisPaint;
static RenderObject _debugActivePaint = null;
static RenderObject _debugActivePaint;
static RenderObject get debugActivePaint => _debugActivePaint;
static List<RenderObject> _nodesNeedingPaint = <RenderObject>[];
......
......@@ -25,6 +25,9 @@ double timeDilation = 1.0;
typedef void FrameCallback(Duration timeStamp);
typedef void SchedulerExceptionHandler(dynamic exception, StackTrace stack);
typedef bool SchedulingStrategy({ int priority, Scheduler scheduler });
/// 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
......@@ -97,7 +100,7 @@ abstract class Scheduler extends BindingBase {
static Scheduler _instance;
static Scheduler get instance => _instance;
SchedulingStrategy schedulingStrategy = new DefaultSchedulingStrategy();
SchedulingStrategy schedulingStrategy = defaultSchedulingStrategy;
static int _taskSorter (_TaskEntry e1, _TaskEntry e2) {
// Note that we inverse the priority.
......@@ -130,7 +133,7 @@ abstract class Scheduler extends BindingBase {
if (_taskQueue.isEmpty)
return;
_TaskEntry entry = _taskQueue.first;
if (schedulingStrategy.shouldRunTaskWithPriority(priority: entry.priority, scheduler: this)) {
if (schedulingStrategy(priority: entry.priority, scheduler: this)) {
try {
(_taskQueue.removeFirst().task)();
} finally {
......@@ -308,17 +311,10 @@ abstract class Scheduler extends BindingBase {
}
}
abstract class SchedulingStrategy {
bool shouldRunTaskWithPriority({ int priority, Scheduler scheduler });
}
class DefaultSchedulingStrategy implements SchedulingStrategy {
// TODO(floitsch): for now we only expose the priority. It might be
// interesting to provide more info (like, how long the task ran the last
// time).
bool shouldRunTaskWithPriority({ int priority, Scheduler scheduler }) {
if (scheduler.transientCallbackCount > 0)
return priority >= Priority.animation._value;
return true;
}
// TODO(floitsch): for now we only expose the priority. It might be interesting
// to provide more info (like, how long the task ran the last time).
bool defaultSchedulingStrategy({ int priority, Scheduler scheduler }) {
if (scheduler.transientCallbackCount > 0)
return priority >= Priority.animation._value;
return true;
}
......@@ -12,18 +12,18 @@ import 'fetch.dart';
import 'image_decoder.dart';
import 'image_resource.dart';
/// Implements a way to retrieve an image, for example by fetching it from the network.
/// Also used as a key in the image cache.
abstract class ImageProvider {
/// Implements a way to retrieve an image, for example by fetching it from the
/// network. Also used as a key in the image cache.
abstract class ImageProvider { // ignore: one_member_abstracts
Future<ImageInfo> loadImage();
}
class _UrlFetcher implements ImageProvider {
_UrlFetcher(this._url, this._scale);
final String _url;
final double _scale;
_UrlFetcher(this._url, this._scale);
Future<ImageInfo> loadImage() async {
UrlResponse response = await fetchUrl(_url);
if (response.statusCode >= 400) {
......
......@@ -15,7 +15,7 @@ import 'basic.dart';
import 'framework.dart';
// Base class for asset resolvers.
abstract class _AssetResolver {
abstract class _AssetResolver { // ignore: one_member_abstracts
// Return a resolved asset key for the asset named [name].
Future<String> resolve(String name);
}
......@@ -77,12 +77,15 @@ class _ResolutionAwareAssetBundle extends _ResolvingAssetBundle {
// of asset variants to choose from.
abstract class _VariantAssetResolver extends _AssetResolver {
_VariantAssetResolver({ this.bundle });
final AssetBundle bundle;
// TODO(kgiesing): Ideally, this cache would be on an object with the same
// lifetime as the asset bundle it wraps. However, that won't matter until we
// need to change AssetVendors frequently; as of this writing we only have
// one.
Map<String, List<String>> _assetManifest;
Future _initializer;
Future _loadManifest() async {
......
......@@ -18,12 +18,12 @@ export 'package:flutter/rendering.dart' show RenderObject, RenderBox, debugPrint
///
/// Keys must be unique amongst the Elements with the same parent.
abstract class Key {
/// Default constructor, used by subclasses.
const Key.constructor(); // so that subclasses can call us, since the Key() factory constructor shadows the implicit constructor
/// Construct a ValueKey<String> with the given String.
/// This is the simplest way to create keys.
factory Key(String value) => new ValueKey<String>(value);
/// Default constructor, used by subclasses.
const Key.constructor(); // so that subclasses can call us, since the Key() factory constructor shadows the implicit constructor
}
/// A kind of [Key] that uses a value of a particular type to identify itself.
......@@ -72,12 +72,12 @@ typedef void GlobalKeyRemoveListener(GlobalKey key);
/// used by components that need to communicate with other components across the
/// application's element tree.
abstract class GlobalKey<T extends State<StatefulComponent>> extends Key {
const GlobalKey.constructor() : super.constructor(); // so that subclasses can call us, since the Key() factory constructor shadows the implicit constructor
/// Constructs a LabeledGlobalKey, which is a GlobalKey with a label used for debugging.
/// The label is not used for comparing the identity of the key.
factory GlobalKey({ String debugLabel }) => new LabeledGlobalKey<T>(debugLabel); // the label is purely for debugging purposes and is otherwise ignored
const GlobalKey.constructor() : super.constructor(); // so that subclasses can call us, since the Key() factory constructor shadows the implicit constructor
static final Map<GlobalKey, Element> _registry = new Map<GlobalKey, Element>();
static final Map<GlobalKey, int> _debugDuplicates = new Map<GlobalKey, int>();
static final Map<GlobalKey, Set<GlobalKeyRemoveListener>> _removeListeners = new Map<GlobalKey, Set<GlobalKeyRemoveListener>>();
......@@ -149,7 +149,7 @@ abstract class GlobalKey<T extends State<StatefulComponent>> extends Key {
message += 'The following GlobalKey was found multiple times among mounted elements: $key (${_debugDuplicates[key]} instances)\n';
message += 'The most recently registered instance is: ${_registry[key]}\n';
}
if (!_debugDuplicates.isEmpty) {
if (_debugDuplicates.isNotEmpty) {
throw new WidgetError(
'Incorrect GlobalKey usage.\n'
'$message'
......@@ -1678,7 +1678,7 @@ abstract class RenderObjectElement<T extends RenderObjectWidget> extends Buildab
}
// clean up any of the remaining middle nodes from the old list
if (haveOldChildren && !oldKeyedChildren.isEmpty) {
if (haveOldChildren && oldKeyedChildren.isNotEmpty) {
for (Element oldChild in oldKeyedChildren.values)
_deactivateChild(oldChild);
}
......
......@@ -210,7 +210,7 @@ class _MixedViewportElement extends RenderObjectElement<MixedViewport> {
assert(renderObject != null);
final int startIndex = _firstVisibleChildIndex;
int lastIndex = startIndex + _childrenByKey.length - 1;
Element previousChild = null;
Element previousChild;
for (int index = startIndex; index <= lastIndex; index += 1) {
final Widget newWidget = _buildWidgetAt(index);
final _ChildKey key = new _ChildKey.fromWidget(newWidget);
......@@ -598,7 +598,7 @@ class _MixedViewportElement extends RenderObjectElement<MixedViewport> {
assert(index != null);
// Place all our children in our RenderObject.
// All the children we are placing are in builtChildren and newChildren.
Element previousChild = null;
Element previousChild;
for (int i = startIndex; i < index; ++i) {
final Element element = builtChildren[i];
if (element.slot != previousChild)
......
......@@ -10,7 +10,7 @@ import 'package:test/test.dart';
class TestSchedulerBinding extends BindingBase with Scheduler { }
class TestStrategy implements SchedulingStrategy {
class TestStrategy {
int allowedPriority = 10000;
bool shouldRunTaskWithPriority({ int priority, Scheduler scheduler }) {
......@@ -22,7 +22,7 @@ void main() {
test("Tasks are executed in the right order", () {
Scheduler scheduler = new TestSchedulerBinding();
TestStrategy strategy = new TestStrategy();
scheduler.schedulingStrategy = strategy;
scheduler.schedulingStrategy = strategy.shouldRunTaskWithPriority;
List<int> input = <int>[2, 23, 23, 11, 0, 80, 3];
List<int> executedTasks = <int>[];
......
......@@ -45,7 +45,7 @@ class TestAssetBundle extends AssetBundle {
return null;
}
Future<core.MojoDataPipeConsumer> load(String key) {
core.MojoDataPipeConsumer pipe = null;
core.MojoDataPipeConsumer pipe;
switch (key) {
case 'assets/image.png':
pipe = new TestMojoDataPipeConsumer(1.0);
......
......@@ -10,7 +10,7 @@ import 'package:test/test.dart';
Size pageSize = new Size(600.0, 300.0);
const List<int> defaultPages = const <int>[0, 1, 2, 3, 4, 5];
final List<GlobalKey> globalKeys = defaultPages.map((_) => new GlobalKey()).toList();
int currentPage = null;
int currentPage;
Widget buildPage(int page) {
return new Container(
......
......@@ -26,6 +26,7 @@ typedef dynamic EvaluatorFunction();
/// Drives a Flutter Application running in another process.
class FlutterDriver {
FlutterDriver.connectedTo(this._serviceClient, this._appIsolate);
static const String _kFlutterExtensionMethod = 'ext.flutter_driver';
static const Duration _kDefaultTimeout = const Duration(seconds: 5);
......@@ -140,8 +141,6 @@ class FlutterDriver {
return driver;
}
FlutterDriver.connectedTo(this._serviceClient, this._appIsolate);
/// Client connected to the Dart VM running the Flutter application
final VMServiceClient _serviceClient;
/// The main isolate hosting the Flutter application
......
......@@ -124,27 +124,27 @@ class ByValueKey extends SearchSpecification {
/// Command to read the text from a given element.
class GetText extends CommandWithTarget {
/// [targetRef] identifies an element that contains a piece of text.
GetText(ObjectRef targetRef) : super(targetRef);
final String kind = 'get_text';
static GetText deserialize(Map<String, String> json) {
return new GetText(new ObjectRef(json['targetRef']));
}
/// [targetRef] identifies an element that contains a piece of text.
GetText(ObjectRef targetRef) : super(targetRef);
Map<String, String> serialize() => super.serialize();
}
class GetTextResult extends Result {
static GetTextResult fromJson(Map<String, dynamic> json) {
return new GetTextResult(json['text']);
}
GetTextResult(this.text);
final String text;
static GetTextResult fromJson(Map<String, dynamic> json) {
return new GetTextResult(json['text']);
}
Map<String, dynamic> toJson() => {
'text': text,
};
......
......@@ -16,7 +16,7 @@ abstract class Command {
/// An object sent from a Flutter application back to the Flutter Driver in
/// response to a command.
abstract class Result {
abstract class Result { // ignore: one_member_abstracts
/// Serializes this message to a JSON map.
Map<String, dynamic> toJson();
}
......
......@@ -24,9 +24,9 @@ Future<dynamic> retry(Action action, Duration timeout,
assert(pauseBetweenRetries != null);
Stopwatch sw = stopwatchFactory()..start();
dynamic result = null;
dynamic lastError = null;
dynamic lastStackTrace = null;
dynamic result;
dynamic lastError;
dynamic lastStackTrace;
bool success = false;
while(!success && sw.elapsed < timeout) {
......
......@@ -211,7 +211,7 @@ class _Renderer implements md.NodeVisitor {
_Block newBlock = new _Block(element.tag, element.attributes, _markdownStyle, new List<String>.from(_listIndents), blockList.length);
blockList.add(newBlock);
} else {
_LinkInfo linkInfo = null;
_LinkInfo linkInfo;
if (element.tag == 'a') {
linkInfo = _linkHandler.createLinkInfo(element.attributes['href']);
}
......@@ -419,7 +419,7 @@ class _Block {
children.add(_stackToTextSpan(list[i]));
}
String text = null;
String text;
if (children.length == 1 && _isPlainText(children[0])) {
text = children[0].text;
children = null;
......@@ -493,12 +493,13 @@ class _LinkHandler {
}
}
abstract class SyntaxHighlighter {
abstract class SyntaxHighlighter { // ignore: one_member_abstracts
TextSpan format(String source);
}
class _DefaultSyntaxHighlighter extends SyntaxHighlighter{
_DefaultSyntaxHighlighter(this.style);
final TextStyle style;
TextSpan format(String source) {
......
......@@ -42,22 +42,21 @@ typedef void SetterCallback(dynamic value);
/// The abstract class for an action that changes properties over a time
/// interval, optionally using an easing curve.
abstract class ActionInterval extends Action {
double _duration;
bool _firstTick = true;
double _elapsed = 0.0;
ActionInterval([this._duration = 0.0, this.curve]);
/// The duration, in seconds, of the action.
///
/// double myTime = myAction.duration;
double get duration => _duration;
double _duration;
/// The animation curve used to ease the animation.
///
/// myAction.curve = bounceOut;
Curve curve;
ActionInterval([this._duration = 0.0, this.curve]);
bool _firstTick = true;
double _elapsed = 0.0;
void step(double dt) {
if (_firstTick) {
......
......@@ -15,6 +15,14 @@ double convertRadians2Degrees(double radians) => radians * 180.0/math.PI;
/// rotation, and scaling) of a node also affects its children.
class Node {
// Constructors
/// Creates a new [Node] without any transformation.
///
/// Node myNode = new Node();
Node();
// Member variables
SpriteBox _spriteBox;
......@@ -101,12 +109,6 @@ class Node {
}
}
// Constructors
/// Creates a new [Node] without any transformation.
///
/// Node myNode = new Node();
Node();
// Property setters and getters
......
......@@ -310,7 +310,7 @@ class PhysicsBody {
double gravityScale;
Object _collisionCategory = null;
Object _collisionCategory;
/// The collision category assigned to this body. The default value is
/// "Default". The body will only collide with bodies that have the either
......@@ -326,7 +326,7 @@ class PhysicsBody {
_updateFilter();
}
List<Object> _collisionMask = null;
List<Object> _collisionMask;
/// A list of collision categories that this object will collide with. If set
/// to null (the default value) the body will collide with all other bodies.
......
......@@ -385,8 +385,8 @@ class _ContactHandler extends box2d.ContactListener {
if (match) {
// We have contact and a matched callback, setup contact info
List<Point> touchingPoints = null;
Offset touchingNormal = null;
List<Point> touchingPoints;
Offset touchingNormal;
// Fetch touching points, if any
if (b2Contact.isTouching()) {
......
......@@ -135,12 +135,6 @@ class SoundTrack {
SoundTrackPlayer _sharedSoundTrackPlayer;
class SoundTrackPlayer {
Set<SoundTrack> _soundTracks = new HashSet<SoundTrack>();
static SoundTrackPlayer sharedInstance() {
return _sharedSoundTrackPlayer ??= new SoundTrackPlayer();
}
SoundTrackPlayer() {
_mediaService = new MediaServiceProxy.unbound();
shell.connectToService("mojo:media_service", _mediaService);
......@@ -148,6 +142,12 @@ class SoundTrackPlayer {
MediaServiceProxy _mediaService;
Set<SoundTrack> _soundTracks = new HashSet<SoundTrack>();
static SoundTrackPlayer sharedInstance() {
return _sharedSoundTrackPlayer ??= new SoundTrackPlayer();
}
Future<SoundTrack> load(Future<MojoDataPipeConsumer> pipe) async {
// Create media player
SoundTrack soundTrack = new SoundTrack();
......
......@@ -23,6 +23,45 @@ enum SpriteBoxTransformMode {
class SpriteBox extends RenderBox {
// Setup
/// Creates a new SpriteBox with a node as its content, by default uses letterboxing.
///
/// The [rootNode] provides the content of the node tree, typically it's a custom subclass of [NodeWithSize]. The
/// [mode] provides different ways to scale the content to best fit it to the screen. In most cases it's preferred to
/// use a [SpriteWidget] that automatically wraps the SpriteBox.
///
/// var spriteBox = new SpriteBox(myNode, SpriteBoxTransformMode.fixedHeight);
SpriteBox(NodeWithSize rootNode, [SpriteBoxTransformMode mode = SpriteBoxTransformMode.letterbox]) {
assert(rootNode != null);
assert(rootNode._spriteBox == null);
// Setup transform mode
this.transformMode = mode;
// Setup root node
this.rootNode = rootNode;
}
void _removeSpriteBoxReference(Node node) {
node._spriteBox = null;
for (Node child in node._children) {
_removeSpriteBoxReference(child);
}
}
void _addSpriteBoxReference(Node node) {
node._spriteBox = this;
for (Node child in node._children) {
_addSpriteBoxReference(child);
}
}
void attach() {
super.attach();
_scheduleTick();
}
// Member variables
// Root node for drawing
......@@ -92,45 +131,6 @@ class SpriteBox extends RenderBox {
bool _initialized = false;
// Setup
/// Creates a new SpriteBox with a node as its content, by default uses letterboxing.
///
/// The [rootNode] provides the content of the node tree, typically it's a custom subclass of [NodeWithSize]. The
/// [mode] provides different ways to scale the content to best fit it to the screen. In most cases it's preferred to
/// use a [SpriteWidget] that automatically wraps the SpriteBox.
///
/// var spriteBox = new SpriteBox(myNode, SpriteBoxTransformMode.fixedHeight);
SpriteBox(NodeWithSize rootNode, [SpriteBoxTransformMode mode = SpriteBoxTransformMode.letterbox]) {
assert(rootNode != null);
assert(rootNode._spriteBox == null);
// Setup transform mode
this.transformMode = mode;
// Setup root node
this.rootNode = rootNode;
}
void _removeSpriteBoxReference(Node node) {
node._spriteBox = null;
for (Node child in node._children) {
_removeSpriteBoxReference(child);
}
}
void _addSpriteBoxReference(Node node) {
node._spriteBox = this;
for (Node child in node._children) {
_addSpriteBoxReference(child);
}
}
void attach() {
super.attach();
_scheduleTick();
}
// Properties
/// The root node of the node tree that is rendered by this box.
......
......@@ -263,7 +263,7 @@ Vector2 _vectorDirection(Vector2 a, Vector2 b) {
List<Vector2> _computeMiterList(List<Vector2> points, bool closed) {
List<Vector2> out = <Vector2>[];
Vector2 curNormal = null;
Vector2 curNormal;
if (closed) {
points = new List<Vector2>.from(points);
......
......@@ -15,20 +15,30 @@ linter:
rules:
- avoid_empty_else
- always_declare_return_types
# we'll turn on avoid_as as soon as it doesn't complain about "as dynamic"
# - avoid_as
# - always_specify_types # still a lot of work to do before enabling this one
# - annotate_overrides # still a lot of work to do before enabling this one
# - avoid_as # https://github.com/dart-lang/linter/issues/195
- avoid_init_to_null
# - avoid_return_types_on_setters # still a lot of work to do before enabling this one
- camel_case_types
# sometimes we have no choice (e.g. when matching other platforms)
# - constant_identifier_names
# - constant_identifier_names # still a lot of work to do before enabling this one
- empty_constructor_bodies
- hash_and_equals
# disabled until regexp fix is pulled in (https://github.com/flutter/flutter/pull/1996)
# - library_names
# - implementation_imports # "// ignore:" isn't working yet
- library_names
- library_prefixes
- non_constant_identifier_names
# too many false-positives; code review should catch real instances
# - one_member_abstracts
# - one_member_abstracts # "// ignore:" isn't working yet
- package_api_docs
- package_names
- package_prefixed_library_names
- prefer_is_not_empty
# - public_member_api_docs # still a lot of work to do before enabling this one
- slash_for_doc_comments
- sort_constructors_first
- sort_unnamed_constructors_first
- super_goes_last
# - type_annotate_public_apis # see always_specify_types, which this is a subset of
- type_init_formals
- unnecessary_brace_in_string_interp
- unnecessary_getters_setters
......@@ -329,7 +329,7 @@ class AndroidDevice extends Device {
RegExp traceRegExp = new RegExp(r'Saving trace to (\S+)', multiLine: true);
RegExp completeRegExp = new RegExp(r'Trace complete', multiLine: true);
String tracePath = null;
String tracePath;
bool isComplete = false;
while (!isComplete) {
List<String> args = <String>['logcat', '-d'];
......
......@@ -109,9 +109,6 @@ void _addFlatPackageList(String subPath, List<String> dartFiles, Set<String> pub
class FileChanged { }
class AnalyzeCommand extends FlutterCommand {
String get name => 'analyze';
String get description => 'Analyze the project\'s Dart code.';
AnalyzeCommand() {
argParser.addFlag('flutter-repo', help: 'Include all the examples and tests from the Flutter repository.', defaultsTo: false);
argParser.addFlag('current-directory', help: 'Include all the Dart files in the current directory, if any.', defaultsTo: true);
......@@ -121,6 +118,8 @@ class AnalyzeCommand extends FlutterCommand {
argParser.addFlag('watch', help: 'Run analysis continuously, watching the filesystem for changes.', negatable: false);
}
String get name => 'analyze';
String get description => 'Analyze the project\'s Dart code.';
bool get requiresProjectRoot => false;
bool get isFlutterRepo {
......
......@@ -402,7 +402,7 @@ Future<int> buildAndroid({
printStatus('Building APK...');
if (!flxPath.isEmpty) {
if (flxPath.isNotEmpty) {
if (!FileSystemEntity.isFileSync(flxPath)) {
printError('FLX does not exist: $flxPath');
printError('(Omit the --flx option to build the FLX automatically)');
......
......@@ -5,7 +5,7 @@
import 'dart:async';
import 'package:path/path.dart' as path;
import 'package:test/src/executable.dart' as executable;
import 'package:test/src/executable.dart' as executable; // ignore: implementation_imports
import '../android/android_device.dart' show AndroidDevice;
import '../application_package.dart';
......
......@@ -6,7 +6,7 @@ import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:test/src/executable.dart' as executable;
import 'package:test/src/executable.dart' as executable; // ignore: implementation_imports
import '../artifacts.dart';
import '../build_configuration.dart';
......@@ -15,9 +15,16 @@ import '../runner/flutter_command.dart';
import '../test/flutter_platform.dart' as loader;
class TestCommand extends FlutterCommand {
TestCommand() {
argParser.addFlag(
'flutter-repo',
help: 'Run tests from the \'flutter\' package in the Flutter repository instead of the current directory.',
defaultsTo: false
);
}
String get name => 'test';
String get description => 'Run Flutter unit tests for the current project (Linux only).';
bool get requiresProjectRoot => false;
@override
......@@ -50,14 +57,6 @@ class TestCommand extends FlutterCommand {
}
}
TestCommand() {
argParser.addFlag(
'flutter-repo',
help: 'Run tests from the \'flutter\' package in the Flutter repository instead of the current directory.',
defaultsTo: false
);
}
Iterable<String> _findTests(Directory directory) {
return directory.listSync(recursive: true, followLinks: false)
.where((FileSystemEntity entity) => entity.path.endsWith('_test.dart') &&
......
......@@ -223,6 +223,34 @@ class DeviceStore {
this.iOSSimulator
});
factory DeviceStore.forConfigs(List<BuildConfiguration> configs) {
AndroidDevice android;
IOSDevice iOS;
IOSSimulator iOSSimulator;
for (BuildConfiguration config in configs) {
switch (config.targetPlatform) {
case TargetPlatform.android:
assert(android == null);
android = _deviceForConfig(config, getAdbDevices());
break;
case TargetPlatform.iOS:
assert(iOS == null);
iOS = _deviceForConfig(config, IOSDevice.getAttachedDevices());
break;
case TargetPlatform.iOSSimulator:
assert(iOSSimulator == null);
iOSSimulator = _deviceForConfig(config, IOSSimulatorUtils.instance.getAttachedDevices());
break;
case TargetPlatform.mac:
case TargetPlatform.linux:
break;
}
}
return new DeviceStore(android: android, iOS: iOS, iOSSimulator: iOSSimulator);
}
final AndroidDevice android;
final IOSDevice iOS;
final IOSSimulator iOSSimulator;
......@@ -239,7 +267,7 @@ class DeviceStore {
}
static Device _deviceForConfig(BuildConfiguration config, List<Device> devices) {
Device device = null;
Device device;
if (config.deviceId != null) {
// Step 1: If a device identifier is specified, try to find a device
......@@ -259,32 +287,4 @@ class DeviceStore {
return device;
}
factory DeviceStore.forConfigs(List<BuildConfiguration> configs) {
AndroidDevice android;
IOSDevice iOS;
IOSSimulator iOSSimulator;
for (BuildConfiguration config in configs) {
switch (config.targetPlatform) {
case TargetPlatform.android:
assert(android == null);
android = _deviceForConfig(config, getAdbDevices());
break;
case TargetPlatform.iOS:
assert(iOS == null);
iOS = _deviceForConfig(config, IOSDevice.getAttachedDevices());
break;
case TargetPlatform.iOSSimulator:
assert(iOSSimulator == null);
iOSSimulator = _deviceForConfig(config, IOSSimulatorUtils.instance.getAttachedDevices());
break;
case TargetPlatform.mac:
case TargetPlatform.linux:
break;
}
}
return new DeviceStore(android: android, iOS: iOS, iOSSimulator: iOSSimulator);
}
}
......@@ -25,12 +25,6 @@ const String _kCopyTemplateExtension = '.copy.tmpl';
/// Files in the destination will not contain either the '.tmpl' or '.copy.tmpl'
/// extensions.
class Template {
factory Template.fromName(String name) {
// All named templates are placed in the 'templates' directory
Directory templateDir = _templateDirectoryInPackage(name);
return new Template(templateDir, templateDir);
}
Template(Directory templateSource, Directory baseDir) {
_templateFilePaths = new Map<String, String>();
......@@ -58,6 +52,12 @@ class Template {
}
}
factory Template.fromName(String name) {
// All named templates are placed in the 'templates' directory
Directory templateDir = _templateDirectoryInPackage(name);
return new Template(templateDir, templateDir);
}
Map<String /* relative */, String /* absolute source */> _templateFilePaths;
void render(Directory destination, Map<String, dynamic> context,
......
......@@ -10,9 +10,9 @@ import 'package:async/async.dart';
import 'package:path/path.dart' as path;
import 'package:stream_channel/stream_channel.dart';
import 'package:test/src/backend/test_platform.dart';
import 'package:test/src/runner/plugin/platform.dart';
import 'package:test/src/runner/plugin/hack_register_platform.dart' as hack;
import 'package:test/src/backend/test_platform.dart'; // ignore: implementation_imports
import 'package:test/src/runner/plugin/platform.dart'; // ignore: implementation_imports
import 'package:test/src/runner/plugin/hack_register_platform.dart' as hack; // ignore: implementation_imports
import '../artifacts.dart';
......
......@@ -8,17 +8,27 @@ import 'simulation.dart';
import 'tolerance.dart';
class FrictionSimulation extends Simulation {
FrictionSimulation(double drag, double position, double velocity)
: _drag = drag,
_dragLog = math.log(drag),
_x = position,
_v = velocity;
// A friction simulation that starts and ends at the specified positions
// and velocities.
factory FrictionSimulation.through(double startPosition, double endPosition, double startVelocity, double endVelocity) {
return new FrictionSimulation(
_dragFor(startPosition, endPosition, startVelocity, endVelocity),
startPosition,
startVelocity)
.. tolerance = new Tolerance(velocity: endVelocity.abs());
}
final double _drag;
final double _dragLog;
final double _x;
final double _v;
FrictionSimulation(double drag, double position, double velocity)
: _drag = drag,
_dragLog = math.log(drag),
_x = position,
_v = velocity;
// Return the drag value for a FrictionSimulation whose x() and dx() values pass
// through the specified start and end position/velocity values.
//
......@@ -30,16 +40,6 @@ class FrictionSimulation extends Simulation {
return math.pow(math.E, (startVelocity - endVelocity) / (startPosition - endPosition));
}
// A friction simulation that starts and ends at the specified positions
// and velocities.
factory FrictionSimulation.through(double startPosition, double endPosition, double startVelocity, double endVelocity) {
return new FrictionSimulation(
_dragFor(startPosition, endPosition, startVelocity, endVelocity),
startPosition,
startVelocity)
.. tolerance = new Tolerance(velocity: endVelocity.abs());
}
double x(double time) => _x + _v * math.pow(_drag, time) / _dragLog - _v / _dragLog;
double dx(double time) => _v * math.pow(_drag, time);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment