// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test that no wakeups are being dropped if we cancel timers.
// WARNING: For this test to work it cannot rely on any other async features
// and will just timeout if it is failing.

library timer_regress22626_test;

import 'dart:async';
import 'dart:math';
import 'package:expect/expect.dart';

int countdown = 10;
var rng = new Random(1234);

void test(int delay, int delta) {
  var t0 = new Timer(new Duration(milliseconds: delay + delta),
                     () => Expect.fail("should have been cancelled by now"));
  new Timer(Duration.ZERO, () => t0.cancel());
  new Timer(Duration.ZERO,
            () => new Timer(new Duration(milliseconds: delay),
                            () {
                              if (--countdown == 0) {
                                print("done");
                              } else {
                                test(delay, max(0, delta + rng.nextInt(2) - 1));
                              }
                            }));
}

void main() {
  test(50, 2);
}

Make timer test more robust.

// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test that no wakeups are being dropped if we cancel timers.
// WARNING: For this test to work it cannot rely on any other async features
// and will just timeout if it is failing.

library timer_regress22626_test;

import 'dart:async';
import 'dart:math';
import 'package:expect/expect.dart';

int countdown = 5;
var rng = new Random(1234);

void test(int delay, int delta) {
  var t0 = new Timer(new Duration(milliseconds: delay + delta),
                     () => Expect.fail("should have been cancelled by now"));
  new Timer(Duration.ZERO, () => t0.cancel());
  new Timer(Duration.ZERO,
            () => new Timer(new Duration(milliseconds: delay),
                            () {
                              if (--countdown == 0) {
                                print("done");
                              } else {
                                test(delay, max(0, delta + rng.nextInt(2) - 1));
                              }
                            }));
}

void main() {
  test(200, 2);
}


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library dart._collection.dev;

import 'dart:collection';

part 'arrays.dart';
part 'iterable.dart';
part 'list.dart';
part 'sort.dart';
part 'to_string.dart';

// TODO(floitsch): move this into core, another hidden library or remove it.
const deprecated = 0;

Remove deprecated declaration in collections_dev.


import 'dart:async';
import 'package:flutter/services.dart';
import 'rtc_peerconnection.dart';
import 'utils.dart';

Future<RTCPeerConnection> createPeerConnection(Map<String,dynamic> configuration, Map<String,dynamic> constraints) async {
  MethodChannel channel = WebRTC.methodChannel();

  Map<String, dynamic> defaultConstraints = {
      "mandatory": {},
      "optional": [
        {"DtlsSrtpKeyAgreement": true },
      ],
    };

    final Map<dynamic, dynamic> response = await channel.invokeMethod(
      'createPeerConnection',
      <String, dynamic>{
        'configuration': configuration,
        'constraints': constraints.length == 0? defaultConstraints : constraints
      },
    );

    String peerConnectionId = response['peerConnectionId'];
    return new RTCPeerConnection(peerConnectionId);
}

Fix indentation in peer connection factory

import 'dart:async';
import 'package:flutter/services.dart';
import 'rtc_peerconnection.dart';
import 'utils.dart';

Future<RTCPeerConnection> createPeerConnection(Map<String, dynamic> configuration, Map<String, dynamic> constraints) async {
  MethodChannel channel = WebRTC.methodChannel();

  Map<String, dynamic> defaultConstraints = {
    "mandatory": {},
    "optional": [
      {"DtlsSrtpKeyAgreement": true},
    ],
  };

  final Map<dynamic, dynamic> response = await channel.invokeMethod(
    'createPeerConnection',
    <String, dynamic>{
      'configuration': configuration,
      'constraints': constraints.length == 0 ? defaultConstraints : constraints
    },
  );

  String peerConnectionId = response['peerConnectionId'];
  return new RTCPeerConnection(peerConnectionId);
}


enum MediaType {
  album,
  clip,
  collection,
  episode,
  movie,
  photo,
  playlist,
  season,
  show,
  track,
  unknown,
}

Add artist option to MediaType type.

enum MediaType {
  album,
  artist,
  clip,
  collection,
  episode,
  movie,
  photo,
  playlist,
  season,
  show,
  track,
  unknown,
}


library hop_runner;

import 'dart:async';
import "dart:io";

import 'package:hop/hop.dart';
import 'package:hop/hop_tasks.dart';
import 'package:yaml/yaml.dart';

part 'docgen.dart';
part 'utils.dart';
part 'version.dart';

void main(List<String> args) {
  addTask("docs", createDocGenTask("."));
  addTask("analyze", createAnalyzerTask(["lib/irc.dart", "example/log.dart", "example/debug.dart", "example/example.dart"]));
  addTask("version", createVersionTask());
  addTask("publish", createProcessTask("pub", args: ["publish", "-f"], description: "Publishes a New Version"));
  addChainedTask("check", ["analyze"]);
  runHop(args);
}

Add Dependency on `version` for `publish`

library hop_runner;

import 'dart:async';
import "dart:io";

import 'package:hop/hop.dart';
import 'package:hop/hop_tasks.dart';
import 'package:yaml/yaml.dart';

part 'docgen.dart';
part 'utils.dart';
part 'version.dart';

void main(List<String> args) {
  addTask("docs", createDocGenTask("."));
  addTask("analyze", createAnalyzerTask(["lib/irc.dart", "example/log.dart", "example/debug.dart", "example/example.dart"]));
  addTask("version", createVersionTask());
  addTask("publish", createProcessTask("pub", args: ["publish", "-f"], description: "Publishes a New Version"), dependencies: ["version"]);
  addChainedTask("check", ["analyze"]);
  runHop(args);
}


import 'package:flutter/material.dart';

class CheckboxSettingsListTile extends StatelessWidget {
  final bool subtitleIsTwoLines;
  final Widget leading;
  final String title;
  final String? subtitle;
  final bool value;
  final Function(bool?)? onChanged;

  const CheckboxSettingsListTile({
    Key? key,
    this.subtitleIsTwoLines = false,
    required this.leading,
    required this.title,
    this.subtitle,
    required this.value,
    this.onChanged,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Theme.of(context).colorScheme.primary,
      child: CheckboxListTile(
        secondary: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              width: 35,
              child: leading,
            ),
          ],
        ),
        title: Text(
          title,
          overflow: TextOverflow.ellipsis,
        ),
        subtitle: subtitle != null
            ? Text(
                subtitle!,
                overflow: subtitleIsTwoLines ? null : TextOverflow.ellipsis,
                maxLines: subtitleIsTwoLines ? 2 : 1,
                style: Theme.of(context).textTheme.subtitle2,
              )
            : null,
        value: value,
        onChanged: onChanged,
      ),
    );
  }
}

Allow the title to be two lines.

import 'package:flutter/material.dart';

class CheckboxSettingsListTile extends StatelessWidget {
  final bool titleIsTwoLines;
  final bool subtitleIsTwoLines;
  final Widget leading;
  final String title;
  final String? subtitle;
  final bool value;
  final Function(bool?)? onChanged;

  const CheckboxSettingsListTile({
    Key? key,
    this.titleIsTwoLines = false,
    this.subtitleIsTwoLines = false,
    required this.leading,
    required this.title,
    this.subtitle,
    required this.value,
    this.onChanged,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Theme.of(context).colorScheme.primary,
      child: CheckboxListTile(
        secondary: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              width: 35,
              child: leading,
            ),
          ],
        ),
        title: Text(
          title,
          overflow: titleIsTwoLines ? null : TextOverflow.ellipsis,
          maxLines: titleIsTwoLines ? 2 : 1,
        ),
        subtitle: subtitle != null
            ? Text(
                subtitle!,
                overflow: subtitleIsTwoLines ? null : TextOverflow.ellipsis,
                maxLines: subtitleIsTwoLines ? 2 : 1,
                style: Theme.of(context).textTheme.subtitle2,
              )
            : null,
        value: value,
        onChanged: onChanged,
      ),
    );
  }
}


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. 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:collection';

import 'package:angular_components/model/ui/has_renderer.dart';

/// Sorts a list of items using the ItemRenderer to obtain a string
/// representation.
List<String> sortItems(ItemRenderer itemRenderer, Iterable entities,
    {bool ignoreCase: false}) {
  if (ignoreCase) {
    return new SplayTreeMap<dynamic, String>.fromIterable(entities,
        key: (Object c) => itemRenderer(c).toLowerCase()).values.toList();
  }
  return new SplayTreeMap<dynamic, String>.fromIterable(entities,
      key: (Object c) => itemRenderer(c)).values.toList();
}

Fix columns to be ordered alphabetically by columnGroup first, then by display name.

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. 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:collection';

import 'package:angular_components/model/ui/has_renderer.dart';

/// Returns a new list of items sorted according to the string obtained from
/// [itemRenderer].
///
/// [itemRenderer] should return a unique string representation for each item.
List<T> sortItems<T>(ItemRenderer<T> itemRenderer, Iterable<T> items,
    {bool ignoreCase: false}) {
  if (ignoreCase) {
    return new SplayTreeMap<String, T>.fromIterable(items,
        key: (T item) => itemRenderer(item).toLowerCase()).values.toList();
  }
  return new SplayTreeMap<String, T>.fromIterable(items,
      key: (T item) => itemRenderer(item)).values.toList();
}


// Copyright 2016 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

const String defaultTempSpecsName = 'tmp.spec';
const String defaultCodeCoverageDirectoryPath = 'coverage/code_coverage';

Change code coverage report locatoin

// Copyright 2016 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

const String defaultTempSpecsName = 'tmp.spec';
const String defaultCodeCoverageDirectoryPath = 'code_coverage';


// 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.

library playfair;

import 'dart:sky' as sky;
import 'dart:math' as math;

import 'package:sky/rendering.dart';
import 'package:sky/theme/typography.dart';
import 'package:sky/widgets.dart';

part 'src/base.dart';

Update imports after material.dart rename

// 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.

library playfair;

import 'dart:sky' as sky;
import 'dart:math' as math;

import 'package:sky/material.dart';
import 'package:sky/rendering.dart';
import 'package:sky/widgets.dart';

part 'src/base.dart';


// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Dart test for testing implicit super calls with bad arguments or no default
// constructor in super class.

class A {
  A(
    this.x;  /// 01: compile-time error
  );
  final foo = 499;
}

class B extends A {}

class B2 extends A {
  B2();
  B2.named() : this.x = 499;
  var x;
}

class C {
  C
  .named  /// 02: compile-time error
  ();
  final foo = 499;
}

class D extends C {}
class D2 extends C {
  D2();
  D2.named() : this.x = 499;
  var x;
}

main() {
  Expect.equals(499, new B().foo);
  Expect.equals(499, new B2().foo);
  Expect.equals(499, new B2.named().foo);
  Expect.equals(499, new D().foo);
  Expect.equals(499, new D2().foo);
  Expect.equals(499, new D2.named().foo);
}

Remove bad semicolon in negative test.

// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Dart test for testing implicit super calls with bad arguments or no default
// constructor in super class.

class A {
  A(
    this.x  /// 01: compile-time error
  );
  final foo = 499;
}

class B extends A {}

class B2 extends A {
  B2();
  B2.named() : this.x = 499;
  var x;
}

class C {
  C
  .named  /// 02: compile-time error
  ();
  final foo = 499;
}

class D extends C {}
class D2 extends C {
  D2();
  D2.named() : this.x = 499;
  var x;
}

main() {
  Expect.equals(499, new B().foo);
  Expect.equals(499, new B2().foo);
  Expect.equals(499, new B2.named().foo);
  Expect.equals(499, new D().foo);
  Expect.equals(499, new D2().foo);
  Expect.equals(499, new D2.named().foo);
}


// 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:sky' as sky;

/// Helper class to build a Paint DrawLooper that adds shadows to the Paint's
/// operation.
class ShadowDrawLooperBuilder {
  var builder_ = new sky.LayerDrawLooperBuilder();

  void addShadow(sky.Size offset, sky.Color color, double blur) {
    builder_.addLayerOnTop(
          new sky.DrawLooperLayerInfo()
            ..setPaintBits(PaintBits.all)
            ..setOffset(offset.toPoint())
            ..setColorMode(sky.TransferMode.srcMode),
          (sky.Paint layerPaint) {
        layerPaint.color = color;
        layerPaint.setMaskFilter(
          new sky.MaskFilter.blur(sky.BlurStyle.normal,
                                  blur,
                                  highQuality: true));
      });
  }

  sky.DrawLooper build() {
    builder_.addLayerOnTop(new sky.DrawLooperLayerInfo(), (_) {});
    return builder_.build();
  }
}

Fix crash in stocks2 app caused by unspecified PaintBits.

// 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:sky' as sky;

/// Helper class to build a Paint DrawLooper that adds shadows to the Paint's
/// operation.
class ShadowDrawLooperBuilder {
  var builder_ = new sky.LayerDrawLooperBuilder();

  void addShadow(sky.Size offset, sky.Color color, double blur) {
    builder_.addLayerOnTop(
          new sky.DrawLooperLayerInfo()
            ..setPaintBits(sky.PaintBits.all)
            ..setOffset(offset.toPoint())
            ..setColorMode(sky.TransferMode.srcMode),
          (sky.Paint layerPaint) {
        layerPaint.color = color;
        layerPaint.setMaskFilter(
          new sky.MaskFilter.blur(sky.BlurStyle.normal,
                                  blur,
                                  highQuality: true));
      });
  }

  sky.DrawLooper build() {
    builder_.addLayerOnTop(new sky.DrawLooperLayerInfo(), (_) {});
    return builder_.build();
  }
}


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test that it is legal to override a field with a field in an interface.

abstract class IA {
  final int foo;
}

abstract class IB implements IA {
  final int foo;
}

class B implements IB {
  int _f = 123;
  int get foo => _f;
}

main() {
  IB b = new B();
  print('b.foo = ${b.foo}');
}

Mark uninitialized final fields as expecting a warning

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test that it is legal to override a field with a field in an interface.

abstract class IA {
  final int foo; /// static warning
}

abstract class IB implements IA {
  final int foo; /// static warning
}

class B implements IB {
  int _f = 123;
  int get foo => _f;
}

main() {
  IB b = new B();
  print('b.foo = ${b.foo}');
}


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. 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:angular/angular.dart';
import 'package:angular_components/laminate/overlay/overlay.dart';
import 'package:angular_components/laminate/portal/portal.dart';

/// An internal directive that is used by the modal component to hoist content.
@Directive(
  selector: '[modalController]',
  // TODO(google): Change to `Visibility.local` to reduce code size.
  visibility: Visibility.all,
)
class ModalControllerDirective extends TemplatePortal implements OnDestroy {
  ModalControllerDirective(
      TemplateRef templateRef, ViewContainerRef viewContainerRef)
      : super(templateRef, viewContainerRef);

  @override
  void ngOnDestroy() {
    if (isAttached) {
      detach();
    }
  }

  /// Attaches content to the provided [overlayRef].
  @Input('modalController')
  set overlay(OverlayRef overlayRef) {
    if (overlayRef == null) {
      if (isAttached) {
        this.detach();
      }
    } else {
      overlayRef.attach(this);
    }
  }
}

Remove visibility.all from @Component annotations. This is potentially BREAKING change.

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. 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:angular/angular.dart';
import 'package:angular_components/laminate/overlay/overlay.dart';
import 'package:angular_components/laminate/portal/portal.dart';

/// An internal directive that is used by the modal component to hoist content.
@Directive(
  selector: '[modalController]',
)
class ModalControllerDirective extends TemplatePortal implements OnDestroy {
  ModalControllerDirective(
      TemplateRef templateRef, ViewContainerRef viewContainerRef)
      : super(templateRef, viewContainerRef);

  @override
  void ngOnDestroy() {
    if (isAttached) {
      detach();
    }
  }

  /// Attaches content to the provided [overlayRef].
  @Input('modalController')
  set overlay(OverlayRef overlayRef) {
    if (overlayRef == null) {
      if (isAttached) {
        this.detach();
      }
    } else {
      overlayRef.attach(this);
    }
  }
}


import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:code_builder/code_builder.dart';

ReferenceBuilder toBuilder(DartType type, List<ImportElement> imports) =>
    reference(type.name, _importFrom(type, imports))
        .toTyped(_coerceTypeArgs(type, imports));

String _importFrom(DartType dartType, List<ImportElement> imports) {
  for (final import in imports) {
    final exportedElement =
        import.importedLibrary.exportNamespace?.get(dartType.element.name);
    if (exportedElement == dartType.element &&
        _isAllowedByCombinators(dartType.element, import)) {
      return import.uri;
    }
  }
  return null;
}

bool _isAllowedByCombinators(Element element, ImportElement import) {
  if (import.combinators.isEmpty) return true;
  Iterable<HideElementCombinator> hideCombinators = import.combinators
      .where((combinator) => combinator is HideElementCombinator);
  Iterable<ShowElementCombinator> showCombinators = import.combinators
      .where((combinator) => combinator is ShowElementCombinator);
  var isHidden = hideCombinators
      .any((combinator) => combinator.hiddenNames.contains(element.name));

  if (isHidden) return false;
  if (showCombinators.isEmpty) return true;
  return showCombinators
      .any((combinator) => combinator.shownNames.contains(element.name));
}

Iterable<TypeBuilder> _coerceTypeArgs(
    DartType type, List<ImportElement> imports) {
  if (type is! ParameterizedType) return const [];
  var typeArgs = (type as ParameterizedType).typeArguments;
  if (typeArgs.every((t) => t.isDynamic)) return const [];
  return typeArgs.map((type) => toBuilder(type, imports));
}

Use NamespaceBuilder to properly handle show/hide combinators.

import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/resolver/scope.dart';
import 'package:code_builder/code_builder.dart';

ReferenceBuilder toBuilder(DartType type, List<ImportElement> imports) =>
    reference(type.name, _importFrom(type, imports))
        .toTyped(_coerceTypeArgs(type, imports));

String _importFrom(DartType dartType, List<ImportElement> imports) {
  final NamespaceBuilder builder = new NamespaceBuilder();
  for (final import in imports) {
    final namespace = builder.createImportNamespaceForDirective(import);
    final exportedElement = import.prefix != null
        ? namespace.getPrefixed(import.prefix.name, dartType.element.name)
        : namespace.get(dartType.element.name);
    if (exportedElement == dartType.element) {
      return import.uri;
    }
  }
  return null;
}

Iterable<TypeBuilder> _coerceTypeArgs(
    DartType type, List<ImportElement> imports) {
  if (type is! ParameterizedType) return const [];
  var typeArgs = (type as ParameterizedType).typeArguments;
  if (typeArgs.every((t) => t.isDynamic)) return const [];
  return typeArgs.map((type) => toBuilder(type, imports));
}


library font_awesome_flutter;

import 'package:flutter/widgets.dart';

class IconDataBrands extends IconData {
  const IconDataBrands(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeBrands',
          fontPackage: 'font_awesome_flutter',
        );
}

class IconDataSolid extends IconData {
  const IconDataSolid(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeSolid',
          fontPackage: 'font_awesome_flutter',
        );
}

class IconDataRegular extends IconData {
  const IconDataRegular(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeRegular',
          fontPackage: 'font_awesome_flutter',
        );
}

Update IconDatas to allow light, pro icons

library font_awesome_flutter;

import 'package:flutter/widgets.dart';

class IconDataBrands extends IconData {
  const IconDataBrands(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeBrands',
          fontPackage: 'font_awesome_flutter',
        );
}

class IconDataSolid extends IconData {
  const IconDataSolid(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeSolid',
          fontPackage: 'font_awesome_flutter',
        );
}

class IconDataRegular extends IconData {
  const IconDataRegular(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeRegular',
          fontPackage: 'font_awesome_flutter',
        );
}

// Pro only
class IconDataLight extends IconData {
  const IconDataLight(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeLight',
          fontPackage: 'font_awesome_flutter',
        );
}


import 'package:flutter/material.dart';

class ResponsiveDialog extends StatelessWidget {
  final Widget? title;
  final Widget child;
  final List<Widget> actions;
  final Function()? onCancel;

  const ResponsiveDialog(
      {Key? key,
      required this.child,
      this.title,
      this.actions = const [],
      this.onCancel})
      : super(key: key);

  @override
  Widget build(BuildContext context) =>
      LayoutBuilder(builder: ((context, constraints) {
        if (constraints.maxWidth < 540) {
          // Fullscreen
          return Dialog(
              insetPadding: const EdgeInsets.all(0),
              child: Scaffold(
                appBar: AppBar(
                  title: title,
                  actions: actions,
                  leading: BackButton(
                    onPressed: () {
                      onCancel?.call();
                      Navigator.of(context).pop();
                    },
                  ),
                ),
                body: SingleChildScrollView(
                  padding: const EdgeInsets.all(18.0),
                  child: child,
                ),
              ));
        } else {
          // Dialog
          return AlertDialog(
            insetPadding: EdgeInsets.zero,
            title: title,
            scrollable: true,
            content: SizedBox(
              width: 380,
              child: child,
            ),
            actions: [
              TextButton(
                child: const Text('Cancel'),
                onPressed: () {
                  onCancel?.call();
                  Navigator.of(context).pop();
                },
              ),
              ...actions
            ],
          );
        }
      }));
}

Improve retaining state for children of ResponsiveDialog.

import 'package:flutter/material.dart';

class ResponsiveDialog extends StatefulWidget {
  final Widget? title;
  final Widget child;
  final List<Widget> actions;
  final Function()? onCancel;

  const ResponsiveDialog(
      {Key? key,
      required this.child,
      this.title,
      this.actions = const [],
      this.onCancel})
      : super(key: key);

  @override
  State<ResponsiveDialog> createState() => _ResponsiveDialogState();
}

class _ResponsiveDialogState extends State<ResponsiveDialog> {
  final Key _childKey = GlobalKey();

  @override
  Widget build(BuildContext context) =>
      LayoutBuilder(builder: ((context, constraints) {
        if (constraints.maxWidth < 540) {
          // Fullscreen
          return Dialog(
              insetPadding: const EdgeInsets.all(0),
              child: Scaffold(
                appBar: AppBar(
                  title: widget.title,
                  actions: widget.actions,
                  leading: BackButton(
                    onPressed: () {
                      widget.onCancel?.call();
                      Navigator.of(context).pop();
                    },
                  ),
                ),
                body: SingleChildScrollView(
                  padding: const EdgeInsets.all(18.0),
                  child: Container(key: _childKey, child: widget.child),
                ),
              ));
        } else {
          // Dialog
          return AlertDialog(
            insetPadding: EdgeInsets.zero,
            title: widget.title,
            scrollable: true,
            content: SizedBox(
              width: 380,
              child: Container(key: _childKey, child: widget.child),
            ),
            actions: [
              TextButton(
                child: const Text('Cancel'),
                onPressed: () {
                  widget.onCancel?.call();
                  Navigator.of(context).pop();
                },
              ),
              ...widget.actions
            ],
          );
        }
      }));
}


// 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:sky';
import 'package:sky/framework/app.dart';
import 'package:sky/framework/rendering/box.dart';
import 'package:sky/framework/rendering/flex.dart';
import 'package:sky/framework/theme2/shadows.dart';

AppView app;

void main() {
  var coloredBox = new RenderDecoratedBox(
    decoration: new BoxDecoration(
      backgroundColor: const Color(0xFFFAFAFA),
      boxShadow: Shadow[3])
  );
  var paddedBox = new RenderPadding(
    padding: const EdgeDims.all(50.0),
    child: coloredBox);
  app = new AppView(new RenderDecoratedBox(
    decoration: const BoxDecoration(
      backgroundColor: const Color(0xFFFFFFFF)
    ),
    child: paddedBox
  ));
}

Add LinearBoxGradient and RadialBoxGradient decorations for RenderDecoratedBox.

// 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:sky';
import 'package:sky/framework/app.dart';
import 'package:sky/framework/rendering/box.dart';
import 'package:sky/framework/rendering/flex.dart';
import 'package:sky/framework/theme2/colors.dart';
import 'package:sky/framework/theme2/shadows.dart';

AppView app;

void main() {
  var coloredBox = new RenderDecoratedBox(
    decoration: new BoxDecoration(
      gradient: new RadialGradient(
        center: Point.origin, radius: 500.0,
        colors: [Yellow[500], Blue[500]]),
      boxShadow: Shadow[3])
  );
  var paddedBox = new RenderPadding(
    padding: const EdgeDims.all(50.0),
    child: coloredBox);
  app = new AppView(new RenderDecoratedBox(
    decoration: const BoxDecoration(
      backgroundColor: const Color(0xFFFFFFFF)
    ),
    child: paddedBox
  ));
}


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import '../../../tools/test.dart' as test_dart;
import '../../../tools/testing/dart/launch_browser.dart' as launch_browser;

// The purpose of this test is to run the analyzer on it and make sure our
// testing scripts are free of warnings/errors.

void main() {}

Fix path to test.dart in analyzer test for it.

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import '../../../tools/testing/dart/main.dart' as test_dart;
import '../../../tools/testing/dart/launch_browser.dart' as launch_browser;

// The purpose of this test is to run the analyzer on it and make sure our
// testing scripts are free of warnings/errors.

void main() {}


part of pin;

class PinUtility {

  static void setCwdToRoot([String relative = '']) {
    String root = LibPath.join(LibPath.dirname(Platform.script.toFilePath()), relative);

    PinLogger.instance.fine('[PinUtility] Set Directory.current to: $root');

    Directory.current = root;
  }

  static void validate(bool condition, String message) {
    if (condition) {
      return;
    }
    throw new FormatException('Wrong format: {$message}.');
  }

  static Object readJsonFileSync(String path) {
    Object data;

    File file = new File(path);
    String fileContent = '';

    if (file.existsSync()) {
      fileContent = new File(path).readAsStringSync();
    } else {
      PinLogger.instance.warning('[PinUtility] readJsonFileSync: Target file does not exist or is not file: {$path}');
    }

    if (fileContent.isNotEmpty) {
      try {
        data = JSON.decode(fileContent);
      } catch (e) {
        PinLogger.instance.shout('[PinUtility] readJsonFileSync: Error in JSON parsing file: {$path}, content: {$fileContent}');
      }
    }

    return data;
  }

  static Future writeJsonFile(String path, Object json) {
    final comp = new Completer();
    String jsonStr = '';

    try {
      jsonStr = JSON.encode(json);
    } catch (e) {
      PinLogger.instance.shout('[PinUtility] writeJsonFile: Error in encoding JSON obj: {$json}');
      comp.complete(); // complete it immediately, since it's just the place holder
      return comp.future;
    }

    File file = new File(path);
    return file.writeAsString(jsonStr);
  }

}

Use future replace the completer.

part of pin;

class PinUtility {

  static void setCwdToRoot([String relative = '']) {
    String root = LibPath.join(LibPath.dirname(Platform.script.toFilePath()), relative);

    PinLogger.instance.fine('[PinUtility] Set Directory.current to: $root');

    Directory.current = root;
  }

  static void validate(bool condition, String message) {
    if (condition) {
      return;
    }
    throw new FormatException('Wrong format: {$message}.');
  }

  static Object readJsonFileSync(String path) {
    Object data;

    File file = new File(path);
    String fileContent = '';

    if (file.existsSync()) {
      fileContent = new File(path).readAsStringSync();
    } else {
      PinLogger.instance.warning('[PinUtility] readJsonFileSync: Target file does not exist or is not file: {$path}');
    }

    if (fileContent.isNotEmpty) {
      try {
        data = JSON.decode(fileContent);
      } catch (e) {
        PinLogger.instance.shout('[PinUtility] readJsonFileSync: Error in JSON parsing file: {$path}, content: {$fileContent}');
      }
    }

    return data;
  }

  static Future writeJsonFile(String path, Object json) {
    String jsonStr = '';

    try {
      jsonStr = JSON.encode(json);
    } catch (e) {
      PinLogger.instance.shout('[PinUtility] writeJsonFile: Error in encoding JSON obj: {$json}');
      return new Future(null);
    }

    File file = new File(path);
    return file.writeAsString(jsonStr);
  }

}


part of app;

@Controller(selector: '[sign-in]', publishAs: 'ctrl')
class SignInController {
  final SessionService _sessionService;
  final Router _router;
  final MessageService _messageService;

  String identifier;
  String password;
  bool longLife = false;

  SignInController(this._sessionService, this._router, this._messageService);

  void signIn() {
    _sessionService.establish(identifier, password, longLife).then((_) {
      _messageService.prepareSuccess('Přihlášen.', 'Přihlášení proběhlo úspěšně.');
      _router.go('homepage', {});
    }).catchError((ApiError e) {
      switch (e.error) {
        case 'UNKNOWN_IDENTIFIER':
          _messageService.showError('Neznámý uživatel.', 'Bohužel neznáme žádného uživatele, který by měl zadaný email nebo uživatelské jméno.');
          break;

        case 'INVALID_CREDENTIAL':
          _messageService.showError('Chybné heslo.', 'Zkuste to prosím znovu.');
        break;
      }
    });
  }
}

Load notifications after signing in

part of app;

@Controller(selector: '[sign-in]', publishAs: 'ctrl')
class SignInController {
  final SessionService _sessionService;
  final Router _router;
  final MessageService _messageService;
  final NotificationService _notificationService;

  String identifier;
  String password;
  bool longLife = false;

  SignInController(this._sessionService, this._router, this._messageService, this._notificationService);

  void signIn() {
    _sessionService.establish(identifier, password, longLife).then((_) {
      _notificationService.loadNotifications();
      _messageService.prepareSuccess('Přihlášen.', 'Přihlášení proběhlo úspěšně.');
      _router.go('homepage', {});
    }).catchError((ApiError e) {
      switch (e.error) {
        case 'UNKNOWN_IDENTIFIER':
          _messageService.showError('Neznámý uživatel.', 'Bohužel neznáme žádného uživatele, který by měl zadaný email nebo uživatelské jméno.');
          break;

        case 'INVALID_CREDENTIAL':
          _messageService.showError('Chybné heslo.', 'Zkuste to prosím znovu.');
        break;
      }
    });
  }
}


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. 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:html';

import 'package:angular/angular.dart';
import 'package:angular_components/focus/focus.dart';

/// This directive is used to [ViewChild] focusable element in your view.
///
/// Assign a [key] in order to filter items from a [QueryList].
@Directive(
  selector: '[focusActivableItem]',
  providers: const [
    const Provider(FocusableActivateItem,
        useExisting: FocusActivableItemDirective)
  ],
  // TODO(google): Change to `Visibility.local` to reduce code size.
  visibility: Visibility.all,
)
class FocusActivableItemDirective extends RootFocusable
    implements FocusableActivateItem {
  /// Key to assign to the focusable item.
  @Input('focusActivableItem')
  @override
  String key;

  FocusActivableItemDirective(HtmlElement root) : super(root);
}

/// A focusable component with a matching [key].
abstract class FocusableActivateItem implements Focusable {
  String get key;
}

Remove visibility.all from @Component annotations. This is potentially BREAKING change.

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. 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:html';

import 'package:angular/angular.dart';
import 'package:angular_components/focus/focus.dart';

/// This directive is used to [ViewChild] focusable element in your view.
///
/// Assign a [key] in order to filter items from a [QueryList].
@Directive(
  selector: '[focusActivableItem]',
  providers: const [
    const Provider(FocusableActivateItem,
        useExisting: FocusActivableItemDirective)
  ],
)
class FocusActivableItemDirective extends RootFocusable
    implements FocusableActivateItem {
  /// Key to assign to the focusable item.
  @Input('focusActivableItem')
  @override
  String key;

  FocusActivableItemDirective(HtmlElement root) : super(root);
}

/// A focusable component with a matching [key].
abstract class FocusableActivateItem implements Focusable {
  String get key;
}


/// A representation of the abstract "rate-limiting window" in which
/// a [user] is accessing some API or endpoint.
class RateLimitingWindow<User> {
  /// The user who is accessing the endpoint.
  final User user;

  /// The time at which the user's current window began.
  final DateTime start;

  /// The number of requests the user has already sent within
  /// the current window.
  final int requestCount;

  RateLimitingWindow(this.user, this.start, this.requestCount);
}

Add point info to window

/// A representation of the abstract "rate-limiting window" in which
/// a [user] is accessing some API or endpoint.
class RateLimitingWindow<User> {
  /// The user who is accessing the endpoint.
  final User user;

  /// The time at which the user's current window began.
  final DateTime start;

  /// The number of requests the user has already sent within
  /// the current window.
  final int requestCount;

  /// The maximum amount of points allowed within a single window.
  final int pointLimit;

  /// The amount of points the user can consume before hitting the
  /// rate limit for the current window.
  final int remainingPoints;

  /// The time at which the window will reset.
  final DateTime resetsAt;

  RateLimitingWindow(this.user, this.start, this.requestCount,
      {this.pointLimit, this.remainingPoints, this.resetsAt});
}


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#import('parser_helper.dart');
#import("../../../lib/compiler/implementation/tree/tree.dart");

testUnparse(String statement) {
  Node node = parseStatement(statement);
  Expect.equals(statement, node.unparse());
}

testGenericTypes() {
  testUnparse('var x=new List<List<int>>();');
  testUnparse('var x=new List<List<List<int>>>();');
  testUnparse('var x=new List<List<List<List<int>>>>();');
  testUnparse('var x=new List<List<List<List<List<int>>>>>();');
}

testForLoop() {
  testUnparse('for(;i<100;i++){}');
  testUnparse('for(i=0;i<100;i++){}');
}

main() {
  testGenericTypes();
  testForLoop();
}

Add a test for empty list literal unparse.

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#import('parser_helper.dart');
#import("../../../lib/compiler/implementation/tree/tree.dart");

testUnparse(String statement) {
  Node node = parseStatement(statement);
  Expect.equals(statement, node.unparse());
}

testGenericTypes() {
  testUnparse('var x=new List<List<int>>();');
  testUnparse('var x=new List<List<List<int>>>();');
  testUnparse('var x=new List<List<List<List<int>>>>();');
  testUnparse('var x=new List<List<List<List<List<int>>>>>();');
}

testForLoop() {
  testUnparse('for(;i<100;i++){}');
  testUnparse('for(i=0;i<100;i++){}');
}

testEmptyList() {
  testUnparse('var x= [];');
}

main() {
  testGenericTypes();
  testForLoop();
  testEmptyList();
}


/*
 * Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
 * for details. All rights reserved. Use of this source code is governed by a
 * BSD-style license that can be found in the LICENSE file.
 */
/**
 * @assertion Let sc be a continue statement. If sc is of the form continue L;,
 * then let sE be the the innermost labeled do, for or while statement or case
 * clause with label L enclosing sc. If sc is of the form continue; then let sE
 * be the innermost do, for or while statement enclosing sc.
 * It is a compile-time error if no such statement or case clause sE exists
 * within the innermost function in which sc occurs.
 * @description Checks that it is a compile-time error if a 'continue L;'
 * statement occurs in a case clause of switch statement with label L and there
 * is no another inclosing statement with label L.
 * @compile-error
 * @author vasya
 */

main() {
  var x = 1;
  L:
  switch (x) {
    case 1:
      print("x=$x");
      x = 0;
      continue L;
    default:
      x = 2;
  }
  print("x=$x");
  print("Ok");
}

Debug output removed and issue number added

/*
 * Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
 * for details. All rights reserved. Use of this source code is governed by a
 * BSD-style license that can be found in the LICENSE file.
 */
/**
 * @assertion Let sc be a continue statement. If sc is of the form continue L;,
 * then let sE be the the innermost labeled do, for or while statement or case
 * clause with label L enclosing sc. If sc is of the form continue; then let sE
 * be the innermost do, for or while statement enclosing sc.
 * It is a compile-time error if no such statement or case clause sE exists
 * within the innermost function in which sc occurs.
 * @description Checks that it is a compile-time error if a 'continue L;'
 * statement occurs in a case clause of switch statement with label L and there
 * is no another enclosing statement with label L.
 * @compile-error
 * @author vasya
 * @issue 42593
 */

main() {
  var x = 1;
  L:
  switch (x) {
    case 1:
      x = 0;
      continue L;
    default:
      x = 2;
  }
}


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. 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:convert";
import "dart:io";

import "package:expect/expect.dart";

void main() {
  var script = Platform.script.resolve("console_script.dart").toFilePath();
  Process.run(Platform.executable,
              ['--checked', script],
              stdoutEncoding: ASCII,
              stderrEncoding: ASCII).then((result) {
                  print(result.stdout);
                  print(result.stderr);
    Expect.equals(1, result.exitCode);
    Expect.equals('stdout\ntuodts\nABCDEFGHIJKLM\n', result.stdout);
    Expect.equals('stderr\nrredts\nABCDEFGHIJKLM\n', result.stderr);
  });
}

Fix console test for Windows

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. 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:convert";
import "dart:io";

import "package:expect/expect.dart";

void main() {
  var script = Platform.script.resolve("console_script.dart").toFilePath();
  Process.run(Platform.executable,
              ['--checked', script],
              stdoutEncoding: ASCII,
              stderrEncoding: ASCII).then((result) {
                  print(result.stdout);
                  print(result.stderr);
    Expect.equals(1, result.exitCode);
    if (Platform.isWindows) {
      Expect.equals('stdout\r\ntuodts\r\nABCDEFGHIJKLM\r\n', result.stdout);
      Expect.equals('stderr\r\nrredts\r\nABCDEFGHIJKLM\r\n', result.stderr);
    } else {
      Expect.equals('stdout\ntuodts\nABCDEFGHIJKLM\n', result.stdout);
      Expect.equals('stderr\nrredts\nABCDEFGHIJKLM\n', result.stderr);
    }
  });
}


/*
 * QR.Flutter
 * Copyright (c) 2019 the QR.Flutter authors.
 * See LICENSE for distribution and usage details.
 */
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:qr/qr.dart';

import 'qr_painter.dart';

class QrImage extends StatelessWidget {
  QrImage({
    @required String data,
    this.size,
    this.padding = const EdgeInsets.all(10.0),
    this.backgroundColor,
    Color foregroundColor = const Color(0xFF000000),
    int version = 4,
    int errorCorrectionLevel = QrErrorCorrectLevel.L,
    this.onError,
    this.gapless = false,
  }) : _painter = QrPainter(
            data: data,
            color: foregroundColor,
            version: version,
            errorCorrectionLevel: errorCorrectionLevel,
            gapless: gapless,
            onError: onError);

  final QrPainter _painter;
  final Color backgroundColor;
  final EdgeInsets padding;
  final double size;
  final QrError onError;
  final bool gapless;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final double widgetSize = size ?? constraints.biggest.shortestSide;
        return Container(
          width: widgetSize,
          height: widgetSize,
          color: backgroundColor,
          child: Padding(
            padding: padding,
            child: CustomPaint(
              painter: _painter,
            ),
          ),
        );
      },
    );
  }
}

Allow setting a Key value on QrImage

/*
 * QR.Flutter
 * Copyright (c) 2019 the QR.Flutter authors.
 * See LICENSE for distribution and usage details.
 */
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:qr/qr.dart';

import 'qr_painter.dart';

class QrImage extends StatelessWidget {
  QrImage({
    @required String data,
    Key key,
    this.size,
    this.padding = const EdgeInsets.all(10.0),
    this.backgroundColor,
    Color foregroundColor = const Color(0xFF000000),
    int version = 4,
    int errorCorrectionLevel = QrErrorCorrectLevel.L,
    this.onError,
    this.gapless = false,
  }) : _painter = QrPainter(
            data: data,
            color: foregroundColor,
            version: version,
            errorCorrectionLevel: errorCorrectionLevel,
            gapless: gapless,
            onError: onError
  ), super(key: key);

  final QrPainter _painter;
  final Color backgroundColor;
  final EdgeInsets padding;
  final double size;
  final QrError onError;
  final bool gapless;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final double widgetSize = size ?? constraints.biggest.shortestSide;
        return Container(
          width: widgetSize,
          height: widgetSize,
          color: backgroundColor,
          child: Padding(
            padding: padding,
            child: CustomPaint(
              painter: _painter,
            ),
          ),
        );
      },
    );
  }
}


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// @dart = 2.9

// ignore_for_file: directives_ordering
// ignore_for_file: library_prefixes

library js_ast;

export 'nodes.dart';
export 'builder.dart';
export 'printer.dart';
export 'template.dart';

Remove an unneeded ignore comment in dev_compiler

// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// @dart = 2.9

// ignore_for_file: directives_ordering

library js_ast;

export 'nodes.dart';
export 'builder.dart';
export 'printer.dart';
export 'template.dart';


// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. 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:test_reflective_loader/test_reflective_loader.dart';

import 'sdk_version_async_exported_from_core_test.dart'
    as sdk_version_async_exported_from_core;

main() {
  defineReflectiveSuite(() {
    sdk_version_async_exported_from_core.main();
  }, name: 'hint');
}

Add a missed test file

// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. 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:test_reflective_loader/test_reflective_loader.dart';

import 'sdk_constraint_extractor_test.dart' as sdk_constraint_extractor;
import 'sdk_version_async_exported_from_core_test.dart'
    as sdk_version_async_exported_from_core;

main() {
  defineReflectiveSuite(() {
    sdk_constraint_extractor.main();
    sdk_version_async_exported_from_core.main();
  }, name: 'hint');
}


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

final x = foo(499);
final y = foo(41) + 1;

final t = bar(499);
final u = bar(41) + 1;
final v = bar("some string");

foo(x) => x; // The return type will always be integer.
bar(x) => x; // The return type varies and can be integer or String.

main() {
  Expect.equals(499, x);
  Expect.equals(42, y);
  Expect.equals(499, t);
  Expect.equals(42, u);
  Expect.equals("some string", v);
}

Address comment of CL 10914097 .

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

final x = foo(499);
final y = foo(41) + 1;

final t = bar(499);
final u = bar(41) + 1;
final v = bar("some string");

foo(x) => x; // The return type will always be int.
bar(x) => x; // The return type varies and can be int or String.

main() {
  Expect.equals(499, x);
  Expect.equals(42, y);
  Expect.equals(499, t);
  Expect.equals(42, u);
  Expect.equals("some string", v);
}


// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

library source_path;

import 'package:polymer/polymer.dart';

@CustomTag('source-path')
class SourcePathElement extends PolymerElement {
  @published var path;
  @observable var isEmpty;

  SourcePathElement.created() : super.created();

  switchAction(event, detail, target) {
    final index = int.parse(target.attributes["data-target"]);
    path.removeRange(index + 1, path.length);
  }
}

Fix inline path bread crumbs control

// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

library source_path;

import 'package:polymer/polymer.dart';

@CustomTag('source-path')
class SourcePathElement extends PolymerElement {
  @published var path;
  @observable var isEmpty;

  SourcePathElement.created() : super.created();

  switchAction(event, detail, target) {
    final index = int.parse(target.attributes["data-target"]);
    path.removeRange(index + 1, path.length);
    event.preventDefault();
  }
}


import 'package:dynamic_color/dynamic_color.dart';
import 'package:dynamic_color/samples.dart';
import 'package:dynamic_color/test_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  testWidgets('DynamicColorBuilder', (WidgetTester tester) async {
    DynamicColorTestingUtils.setMockDynamicColors(
      colors: SampleCorePalettes.green,
    );

    const containerKey = Key('myContainer');

    await tester.pumpWidget(
      DynamicColorBuilder(
        builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) {
          return Container(
            key: containerKey,
            color: lightDynamic?.primary ?? const Color(0x00000123),
          );
        },
      ),
    );

    await tester.pumpAndSettle();

    expect(
      (tester.firstWidget(find.byKey(containerKey)) as Container).color,
      const Color(0xff286b2a),
    );
  });
}

Improve testing coverage for `DynamicColorBuilder`

import 'package:dynamic_color/dynamic_color.dart';
import 'package:dynamic_color/samples.dart';
import 'package:dynamic_color/test_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  setUp(() {
    DynamicColorTestingUtils.setMockDynamicColors(
      colorPalette: SampleCorePalettes.green,
      controlAccentColor: Colors.amber,
    );
  });

  const containerKey = Key('myContainer');

  Widget dynamicColorBuilder() => DynamicColorBuilder(
        builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) {
          return Container(
            key: containerKey,
            color: lightDynamic?.primary ?? const Color(0x00000123),
          );
        },
      );

  testWidgets('DynamicColorBuilder is correct on Android',
      (WidgetTester tester) async {
    DynamicColorTestingUtils.setMockDynamicColors(
      colorPalette: SampleCorePalettes.green,
    );

    await tester.pumpWidget(dynamicColorBuilder());
    await tester.pumpAndSettle();

    final container = tester.firstWidget(find.byKey(containerKey)) as Container;
    expect(container.color, const Color(0xff286b2a));
  });

  testWidgets('DynamicColorBuilder is correct on macOS',
      (WidgetTester tester) async {
    DynamicColorTestingUtils.setMockDynamicColors(
      controlAccentColor: Colors.amber,
    );
    await tester.pumpWidget(dynamicColorBuilder());
    await tester.pumpAndSettle();

    final container = tester.firstWidget(find.byKey(containerKey)) as Container;
    expect(container.color, const Color(0xff795900));
  });

  testWidgets('DynamicColorBuilder is correct on other platforms',
      (WidgetTester tester) async {
    DynamicColorTestingUtils.setMockDynamicColors();

    await tester.pumpWidget(dynamicColorBuilder());
    await tester.pumpAndSettle();

    final container = tester.firstWidget(find.byKey(containerKey)) as Container;
    expect(container.color, const Color(0x00000123));
  });
}


// Copyright (c) 2014, Robert Åkerblom-Andersson <Robert@dartvoid.com>

part of vane;

/// Http methods constants, declared for easy use with code completion and to
/// avoid typos.
const String GET      = "GET";
const String HEAD     = "HEAD";
const String POST     = "POST";
const String PUT      = "PUT";
const String DELETE   = "DELETE";
const String TRACE    = "TRACE";
const String OPTIONS  = "OPTIONS";
const String CONNECT  = "CONNECT";
const String PATCH    = "PATCH";

/// [Route] annotation used to declared the request handler for a specific path
class Route {
  final String path;
  final String method;
  final List<String> methods;

  const Route(this.path, {this.method: "", this.methods: const []});
}

// A class is used for this constant since the other entries in the pipeline
// list are also classes.
class _This {
  const _This();
}

/// [This] is a constant used to indentify the main handler in middleware
/// pipeline. With [This] it's possible to define where in the pipelien the
/// main handler should go, per default that is last in the the pipeline.
const This = const _This();

Fix a typo in the API doc

// Copyright (c) 2014, Robert Åkerblom-Andersson <Robert@dartvoid.com>

part of vane;

/// Http methods constants, declared for easy use with code completion and to
/// avoid typos.
const String GET      = "GET";
const String HEAD     = "HEAD";
const String POST     = "POST";
const String PUT      = "PUT";
const String DELETE   = "DELETE";
const String TRACE    = "TRACE";
const String OPTIONS  = "OPTIONS";
const String CONNECT  = "CONNECT";
const String PATCH    = "PATCH";

/// [Route] annotation used to declared the request handler for a specific path
class Route {
  final String path;
  final String method;
  final List<String> methods;

  const Route(this.path, {this.method: "", this.methods: const []});
}

// A class is used for this constant since the other entries in the pipeline
// list are also classes.
class _This {
  const _This();
}

/// [This] is a constant used to indentify the main handler in middleware
/// pipeline. With [This] it's possible to define where in the pipeline the
/// main handler should go, per default that is last in the the pipeline.
const This = const _This();


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. 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:angular/angular.dart';

/**
 * Mixin for trackLayoutChanges property pass through to material popup to
 * avoid duplicate code in multiple components.
 */
class TrackLayoutChangesMixin {
  /// Sets whether the suggestion list scrolls with the input box.
  ///
  /// This is a pass through property, as defined in [PopupInterface].
  @Input()
  bool trackLayoutChanges = true;
}

Fix violations of slash_for_doc_comments lint

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. 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:angular/angular.dart';

/// Mixin for trackLayoutChanges property pass through to material popup to
/// avoid duplicate code in multiple components.
class TrackLayoutChangesMixin {
  /// Sets whether the suggestion list scrolls with the input box.
  ///
  /// This is a pass through property, as defined in [PopupInterface].
  @Input()
  bool trackLayoutChanges = true;
}


import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'device_button.dart';
import 'main_drawer.dart';

class AppPage extends ConsumerWidget {
  final Key _scaffoldKey = GlobalKey();
  final Widget? title;
  final Widget child;
  final void Function()? onBack;
  AppPage({Key? key, this.title, required this.child, this.onBack})
      : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) => LayoutBuilder(
        builder: (context, constraints) {
          if (constraints.maxWidth < 540) {
            // Single column layout
            return _buildScaffold(context, ref, true);
          } else {
            // Two-column layout
            return Scaffold(
              body: Row(
                children: [
                  const SizedBox(
                    width: 240,
                    child: MainPageDrawer(shouldPop: false),
                  ),
                  Expanded(
                    child: _buildScaffold(context, ref, false),
                  ),
                ],
              ),
            );
          }
        },
      );

  Scaffold _buildScaffold(BuildContext context, WidgetRef ref, bool hasDrawer) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        leading: onBack != null
            ? BackButton(
                onPressed: onBack,
              )
            : null,
        title: title,
        centerTitle: true,
        actions: const [DeviceButton()],
      ),
      drawer: hasDrawer ? const MainPageDrawer() : null,
      body: child,
    );
  }
}

Make ListTile use the drawer style when drawer is embedded.

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'device_button.dart';
import 'main_drawer.dart';

class AppPage extends ConsumerWidget {
  final Key _scaffoldKey = GlobalKey();
  final Widget? title;
  final Widget child;
  final void Function()? onBack;
  AppPage({Key? key, this.title, required this.child, this.onBack})
      : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) => LayoutBuilder(
        builder: (context, constraints) {
          if (constraints.maxWidth < 540) {
            // Single column layout
            return _buildScaffold(context, ref, true);
          } else {
            // Two-column layout
            return Scaffold(
              body: Row(
                children: [
                  const SizedBox(
                    width: 240,
                    child: ListTileTheme(
                        style: ListTileStyle.drawer,
                        child: MainPageDrawer(shouldPop: false)),
                  ),
                  Expanded(
                    child: _buildScaffold(context, ref, false),
                  ),
                ],
              ),
            );
          }
        },
      );

  Scaffold _buildScaffold(BuildContext context, WidgetRef ref, bool hasDrawer) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        leading: onBack != null
            ? BackButton(
                onPressed: onBack,
              )
            : null,
        title: title,
        centerTitle: true,
        actions: const [DeviceButton()],
      ),
      drawer: hasDrawer ? const MainPageDrawer() : null,
      body: child,
    );
  }
}


part of darn;

class BuildCommand extends Command {
  @override
  ArgParser get arguments =>
    new ArgParser()
      ..addFlag("verbose", abbr: "v", defaultsTo: false, negatable: false, help: "Enables Verbose Output")
      ..addOption("arch", abbr: "a", allowed: POSSIBLE_ARCHS, allowMultiple: false, defaultsTo: "ia32")
      ..addOption("mode", abbr: "m", allowed: POSSIBLE_MODES, allowMultiple: false, defaultsTo: "release");

  @override
  String get name => "build";

  @override
  void run(ArgResults args) {

    String arch = args['arch'];

    String mode = args['mode'];

    var targets = args.rest.isNotEmpty ? args.rest : ["create_sdk"];

    verifyDartSource();

    var commands = [];

    var cmd = "python2 tools/build.py -m ${mode} -a ${arch} ${targets.join(" ")}";

    commands.add(cmd);

    executeCommands(commands);
  }
}

Build Command: Actually Follow the Verbose Flag

part of darn;

class BuildCommand extends Command {
  @override
  ArgParser get arguments =>
    new ArgParser()
      ..addFlag("verbose", abbr: "v", defaultsTo: false, negatable: false, help: "Enables Verbose Output")
      ..addOption("arch", abbr: "a", allowed: POSSIBLE_ARCHS, allowMultiple: false, defaultsTo: "ia32")
      ..addOption("mode", abbr: "m", allowed: POSSIBLE_MODES, allowMultiple: false, defaultsTo: "release");

  @override
  String get name => "build";

  @override
  void run(ArgResults args) {

    String arch = args['arch'];

    String mode = args['mode'];

    bool verbose = args['verbose'];

    var targets = args.rest.isNotEmpty ? args.rest : ["create_sdk"];

    verifyDartSource();

    var commands = [];

    var cmd = "python2 tools/build.py ${verbose ? "-v" : ""} -m ${mode} -a ${arch} ${targets.join(" ")}";

    commands.add(cmd);

    executeCommands(commands);
  }
}


library events;

import "dart:async";

class Event {
  String type;
  Event(this.type);
}

class Emitter {

  final _evtController = new StreamController<Event>.broadcast();

  Stream<Event> operator[] (type) => _evtController.stream.where((e) => e.type == type);

  Stream<T> getEventStream<T extends Event>(String type) {
    final controller = new StreamController<T>();
    _evtController.stream.where((e) => e.type == type).listen(
        controller.add,
        onDone: controller.close,
        onError: controller.addError);
    return controller.stream;
  }

  dispatch(evtOrType) {
    var evt = (evtOrType is String) ? new Event(evtOrType) : evtOrType;
    _evtController.add(evt);
  }
}

Use .where().map() instead of StreamController

library events;

import "dart:async";

class Event {
  String type;
  Event(this.type);
}

class Emitter {

  final _evtController = new StreamController<Event>.broadcast();

  Stream<Event> operator[] (type) => _evtController.stream.where((e) => e.type == type);

  Stream<T> getEventStream<T extends Event>(String type) {
    return _evtController.stream.where((e) => e.type == type).map((e) => e as T);
  }

  dispatch(evtOrType) {
    var evt = (evtOrType is String) ? new Event(evtOrType) : evtOrType;
    _evtController.add(evt);
  }
}


#!/usr/bin/env dart
// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// @dart = 2.9

/// Tool that consumes the .dill file of an entire dart-sdk and produces the
/// corresponding Javascript module.

import 'dart:io';
import 'package:dev_compiler/src/kernel/command.dart';

void main(List<String> args) async {
  var result = await compileSdkFromDill(args);
  exitCode = result.exitCode;
}

Migrate compile sdk script to null safety

#!/usr/bin/env dart
// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/// Tool that consumes the .dill file of an entire dart-sdk and produces the
/// corresponding Javascript module.

import 'dart:io';
import 'package:dev_compiler/src/kernel/command.dart';

void main(List<String> args) async {
  var result = await compileSdkFromDill(args);
  exitCode = result.exitCode;
}


/// XML pretty printer.
library xml.example.xml_pp;

import 'dart:io';

import 'package:args/args.dart' as args;
import 'package:xml/xml.dart' as xml;

final args.ArgParser argumentParser = args.ArgParser()
  ..addOption('indent',
      abbr: 'i',
      help: 'Customizes the indention when pretty printing.',
      defaultsTo: '  ');

void printUsage() {
  stdout.writeln('Usage: xml_pp [options] {files}');
  stdout.writeln();
  stdout.writeln(argumentParser.usage);
  exit(1);
}

void main(List<String> arguments) {
  final files = <File>[];
  final results = argumentParser.parse(arguments);
  final indent = results['indent'];

  for (final argument in results.rest) {
    final file = File(argument);
    if (file.existsSync()) {
      files.add(file);
    } else {
      stderr.writeln('File not found: $file');
      exit(2);
    }
  }
  if (files.isEmpty) {
    printUsage();
  }

  for (final file in files) {
    final document = xml.parse(file.readAsStringSync());
    stdout.writeln(document.toXmlString(pretty: true, indent: indent));
  }
}

Add a pretty option to the formatter example.

/// XML pretty printer.
library xml.example.xml_pp;

import 'dart:io';

import 'package:args/args.dart' as args;
import 'package:xml/xml.dart' as xml;

final args.ArgParser argumentParser = args.ArgParser()
  ..addOption('indent',
      abbr: 'i',
      help: 'Customizes the indention when pretty printing.',
      defaultsTo: '  ')
  ..addFlag('pretty',
      abbr: 'p',
      help: 'Reformats the output to be pretty.',
      defaultsTo: true);

void printUsage() {
  stdout.writeln('Usage: xml_pp [options] {files}');
  stdout.writeln();
  stdout.writeln(argumentParser.usage);
  exit(1);
}

void main(List<String> arguments) {
  final files = <File>[];
  final results = argumentParser.parse(arguments);
  final indent = results['indent'];
  final pretty = results['pretty'];

  for (final argument in results.rest) {
    final file = File(argument);
    if (file.existsSync()) {
      files.add(file);
    } else {
      stderr.writeln('File not found: $file');
      exit(2);
    }
  }
  if (files.isEmpty) {
    printUsage();
  }

  for (final file in files) {
    final document = xml.parse(file.readAsStringSync());
    stdout.writeln(document.toXmlString(pretty: pretty, indent: indent));
  }
}


// Copyright (c) 2013, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

library git.utils;

import 'dart:core';

/**
 * Convertes [sha] string to sha bytes.
 */
List<int> shaToBytes(String sha) {
  List<int> bytes = [];

  for (var i = 0; i < sha.length; i+=2) {
    bytes.add(int.parse('0x' + sha[i] + sha[i+1]));
  }
  return bytes;
}

/**
 * Converts [shaBytes] to HEX string.
 */
String shaBytesToString(List<int> shaBytes) {
  String sha = "";
  shaBytes.forEach((int byte) {
    sha += byte.toRadixString(16);
  });
  return sha;
}

/**
 * An empty function.
 */
void nopFunction() => null;

Fix bug in sha / bytes conversion.

// Copyright (c) 2013, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

library git.utils;

import 'dart:core';

/**
 * Convertes [sha] string to sha bytes.
 */
List<int> shaToBytes(String sha) {
  List<int> bytes = [];

  for (var i = 0; i < sha.length; i+=2) {
    bytes.add(int.parse('0x' + sha[i] + sha[i+1]));
  }
  return bytes;
}

/**
 * Converts [shaBytes] to HEX string.
 */
String shaBytesToString(List<int> shaBytes) {
  String sha = "";
  shaBytes.forEach((int byte) {
    String shaPart = byte.toRadixString(16);
    if (shaPart.length == 1) shaPart = '0' + shaPart;
    sha += shaPart;
  });
  return sha;
}

/**
 * An empty function.
 */
void nopFunction() => null;


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. 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:expect/expect.dart";

class A<T> {
  @NoInlining()
  A();

  @NoInlining()
  foo() => new B<T>();
}

class B<T> {
  T bar() => null;
}

typedef F();
typedef F2(x);

// Dart2js realized that the generic type for A was not needed, but then used
// it nevertheless when it constructed the closure.
main() {
  var f = new A<int>().foo().bar;
  Expect.isTrue(f is F);
  Expect.isFalse(f is F2);
}

Update no-inline annotation in test.

// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. 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:expect/expect.dart";

class A<T> {
  @NoInline()
  A();

  @NoInline()
  foo() => new B<T>();
}

class B<T> {
  T bar() => null;
}

typedef F();
typedef F2(x);

// Dart2js realized that the generic type for A was not needed, but then used
// it nevertheless when it constructed the closure.
main() {
  var f = new A<int>().foo().bar;
  Expect.isTrue(f is F);
  Expect.isFalse(f is F2);
}


part of quiz;

class StaticFilesController extends HTTPController {
  final String basePath;
  final String defaultFile;

  StaticFilesController({this.basePath: "build/web", this.defaultFile: "index.html"});

  // Initially based on https://github.com/stablekernel/aqueduct/issues/157
  @httpGet getFile() async {
    String realPath = request.path.remainingPath;
    if (realPath.length == 0) {
      realPath = defaultFile;
    }
    String filePath = path.join(basePath, realPath);
    io.File file = new io.File(filePath);
    var fileContents = file.readAsBytesSync();

    String contentType = mime.lookupMimeType(filePath);

    return new Response.ok(fileContents)
      ..contentType = io.ContentType.parse(contentType);
  }
}

Add type for the file contents.

part of quiz;

class StaticFilesController extends HTTPController {
  final String basePath;
  final String defaultFile;

  StaticFilesController({this.basePath: "build/web", this.defaultFile: "index.html"});

  // Initially based on https://github.com/stablekernel/aqueduct/issues/157
  @httpGet getFile() async {
    String realPath = request.path.remainingPath;
    if (realPath.length == 0) {
      realPath = defaultFile;
    }
    String filePath = path.join(basePath, realPath);
    io.File file = new io.File(filePath);
    List<int> fileContents = file.readAsBytesSync();

    String contentType = mime.lookupMimeType(filePath);

    return new Response.ok(fileContents)
      ..contentType = io.ContentType.parse(contentType);
  }
}


import 'package:flutter/material.dart';

class ServerSetupInstructions extends StatelessWidget {
  const ServerSetupInstructions({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(bottom: 10),
          child: Text(
            'This app is not registered to a Tautulli server.',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
        Text('To register this app do the following:'),
        BulletItem('Open the Tautulli web interface on another device'),
        BulletItem('Navigate to Settings > Tautulli Remote App'),
        BulletItem('Select \'Register a new device\''),
        BulletItem('Use the button below to add a new server'),
      ],
    );
  }
}

class BulletItem extends StatelessWidget {
  final String text;

  const BulletItem(this.text, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(
        left: 10,
      ),
      child: Text('• $text'),
    );
  }
}

Tweak wording for server setup instructions.

import 'package:flutter/material.dart';

class ServerSetupInstructions extends StatelessWidget {
  const ServerSetupInstructions({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(bottom: 10),
          child: Text(
            'This app is not registered to a Tautulli server.',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
        Text('To register with a Tautulli server:'),
        BulletItem('Open the Tautulli web interface on another device'),
        BulletItem('Navigate to Settings > Tautulli Remote App'),
        BulletItem('Select \'Register a new device\''),
        BulletItem('Use the button below to add a new server'),
      ],
    );
  }
}

class BulletItem extends StatelessWidget {
  final String text;

  const BulletItem(this.text, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(
        left: 10,
      ),
      child: Text('• $text'),
    );
  }
}


// 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.

library playfair;

import 'dart:sky' as sky;
import 'dart:math' as math;

import 'package:sky/material.dart';
import 'package:sky/rendering.dart';
import 'package:sky/widgets_next.dart';

part 'src/base.dart';

Switch to the production name for fn3

// 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.

library playfair;

import 'dart:sky' as sky;
import 'dart:math' as math;

import 'package:sky/material.dart';
import 'package:sky/rendering.dart';
import 'package:sky/widgets.dart';

part 'src/base.dart';


// Copyright (c) 2020, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// ignore_for_file: directives_ordering

/// Support for programming against the Win32 Windows Socket 2 library on
/// Windows operating systems.
///
/// This library extends the core `win32` library with Windows Socket functions.
/// Since this library is somewhat specialist and many of its function names are
/// likely to conflict with other libraries or programs, it is separately
/// exported.
///
/// The `winsock2` library will normally be used in conjunction with the main
/// `win32` library, and the latter will be required for constants and structs
/// used here.
library winsock2;

// Core Win32 APIs, constants and macros
export 'src/structs.g.dart'
    show addrinfo, fd_set, SOCKADDR, timeval, hostent, protoent, servent;
export 'src/structs.dart' show IN_ADDR;
export 'src/constants_winsock.dart';

// Traditional C-style Windows APIs
export 'src/ws2_32.dart';

Add more explanation for importing winsock

// Copyright (c) 2020, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// ignore_for_file: directives_ordering

/// Support for programming against the Win32 Windows Socket 2 library on
/// Windows operating systems.
///
/// This library extends the core `win32` library with Windows Socket functions.
/// Since this library is somewhat specialist and many of its function names
/// (e.g. `send`, `connect`) are likely to conflict with other libraries or
/// programs, it is separately exported.
///
/// To add Winsock2 support to your app, use the additional line below:
///
/// ```dart
/// import 'package:win32/win32.dart';
/// import 'package:win32/winsock2.dart' as winsock2;
/// ```
///
/// Now you can call, for instance, `winsock2.connect()` or `winsock2.send()`.
///
/// The `winsock2` library will normally be used in conjunction with the main
/// `win32` library, and the latter will be required for constants and structs
/// used here.
library winsock2;

// Core Win32 APIs, constants and macros
export 'src/structs.g.dart'
    show addrinfo, fd_set, SOCKADDR, timeval, hostent, protoent, servent;
export 'src/structs.dart' show IN_ADDR;
export 'src/constants_winsock.dart';

// Traditional C-style Windows APIs
export 'src/ws2_32.dart';


import 'package:unittest/unittest.dart';
import 'package:workmantrainer/textmarker.dart';

void main() {
  test('check initialisation of TextMarker Class works.', () {
    var tm = new TextMarker('some text',0,2,"CORRECT");
    expect(tm.targettext, 'some text');
    expect(tm.startposition,0);
    expect(tm.endposition,2);
    expect(tm.textState, 'CORRECT');
  });
  test('typedCorrectly returns correct span element.', () {
    var tm = new TextMarker('some text', 0, 2, "Correct");
    var span = tm.typedCorrectly();
    expect(span.text, 'so');
  });
}

Check Correct ClassName is set.

import 'package:unittest/unittest.dart';
import 'package:workmantrainer/textmarker.dart';

void main() {
  test('check initialisation of TextMarker Class works.', () {
    var tm = new TextMarker('some text',0,2,"CORRECT");
    expect(tm.targettext, 'some text');
    expect(tm.startposition,0);
    expect(tm.endposition,2);
    expect(tm.textState, 'CORRECT');
  });
  test('typedCorrectly returns correct span element.', () {
    var tm = new TextMarker('some text', 0, 2, "CORRECT");
    var span = tm.typedCorrectly();
    expect(span.text, 'so');
    expect(span.className, 'typedcorrect');
  });
}


import 'dart:convert';

import 'package:drift/drift.dart';
import 'package:test/test.dart';

void main() {
  test('maps without transormation', () {
    const type = BlobType();
    final data = Uint8List.fromList(List.generate(256, (i) => i));

    expect(type.mapToSqlVariable(data), data);
    expect(type.mapFromDatabaseResponse(data), data);
  });

  test('writes blob literals', () {
    const type = BlobType();
    const hex = '67656E6572616C206B656E6F626921';
    final data = Uint8List.fromList(utf8.encode('general kenobi!'));

    expect(type.mapToSqlConstant(data), equalsIgnoringCase("x'$hex'"));
  });
}

Test for blob by string

import 'dart:convert';

import 'package:drift/drift.dart';
import 'package:test/test.dart';

void main() {
  test('maps without transformation', () {
    const type = BlobType();
    final data = Uint8List.fromList(List.generate(256, (i) => i));

    expect(type.mapToSqlVariable(data), data);
    expect(type.mapFromDatabaseResponse(data), data);
  });

  test('writes blob literals', () {
    const type = BlobType();
    const hex = '67656E6572616C206B656E6F626921';
    final data = Uint8List.fromList(utf8.encode('general kenobi!'));

    expect(type.mapToSqlConstant(data), equalsIgnoringCase("x'$hex'"));
  });

  test('maps of string', () {
    const chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
    const type = BlobType();
    final data = List.generate(256, (i) => chars[i % chars.length]);
    final dataString = data.join();
    final dataInt = data.map((e) => e.codeUnits[0]).toList();
    final dataUint8 = Uint8List.fromList(dataInt);
    expect(type.mapFromDatabaseResponse(dataString), dataUint8);
  });
}


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// This file is separate from has_renderer so it doesn't add in the angular
// dependency and so 'dart:html' which stops tests from running as a simple
// dart_test.
import 'package:angular/angular.dart' show ComponentFactory;

import 'has_renderer.dart';

export 'has_renderer.dart';

/// Defines a method that returns a factory to render the Item.  The
/// component created must implement [RendersValue].
typedef ComponentFactory FactoryRenderer<T extends RendersValue, I>(I item);

/// HasFactoryRenderer defines a method that takes in an item and returns the
/// factory to use to render the item.
abstract class HasFactoryRenderer<T extends RendersValue, I> {
  FactoryRenderer<T, I> factoryRenderer;
}

Clarify file comment about angular dependency.

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// This file is separate from has_renderer.dart so it doesn't add the angular
// dependency and transitively 'dart:html', which doesn't work in a simple
// dart_test.
import 'package:angular/angular.dart' show ComponentFactory;

import 'has_renderer.dart';

export 'has_renderer.dart';

/// Defines a method that returns a factory to render the Item.  The component
/// created must implement [RendersValue].
typedef ComponentFactory FactoryRenderer<T extends RendersValue, I>(I item);

/// HasFactoryRenderer defines a method that takes in an item and returns the
/// factory to use to render the item.
abstract class HasFactoryRenderer<T extends RendersValue, I> {
  FactoryRenderer<T, I> factoryRenderer;
}


part of nest_ui;

class BaseComponentBehaviors {

  Component component;

  BaseComponentBehaviors(this.component) {}

  // Show-hide behaviors
  //
  hide() => this.dom_element.style.display="none";
  show() => this.dom_element.style.display="";
  toggleDisplay() => _toggle(
    [show, hide],
    this.dom_element.style.display == 'none'
  );

  // Lock-unlock behaviors
  //
  lock()       => this.dom_element.classes.add("locked");
  unlock()     => this.dom_element.classes.remove("locked");
  toggleLock() => this.dom_element.classes.toggle("locked");

  // Enable-disable behaviors
  //
  disable() => {
    this.dom_element.classes.add('disabled');
    this.dom_element.setAttribute('disabled', 'disabled');
  }
  enable() => {
    this.dom_element.classes.add('disabled');
    this.dom_element.attributes.remove('disabled');
  }
  toggleDisable() => _toggle([enable, disable], this.dom_element.classes.contains('disabled'));

  _toggle(behaviors, condition) {
    if(condition)
      behaviors[0]();
    else
      behaviors[1]();
  }

  get dom_element => this.component.dom_element;

}

Add disabling/enabling behavior into BaseComponentBehavior class

part of nest_ui;

class BaseComponentBehaviors {

  Component component;

  BaseComponentBehaviors(this.component) {}

  // Show-hide behaviors
  //
  hide() => this.dom_element.style.display="none";
  show() => this.dom_element.style.display="";
  toggleDisplay() => _toggle(
    [show, hide],
    this.dom_element.style.display == 'none'
  );

  // Lock-unlock behaviors
  //
  lock()       => this.dom_element.classes.add("locked");
  unlock()     => this.dom_element.classes.remove("locked");
  toggleLock() => this.dom_element.classes.toggle("locked");

  // Enable-disable behaviors
  //
  disable() {
    this.dom_element.classes.add('disabled');
    this.dom_element.setAttribute('disabled', 'disabled');
  }
  enable() {
    this.dom_element.classes.remove('disabled');
    this.dom_element.attributes.remove('disabled');
  }
  toggleDisable() => _toggle([enable, disable], this.dom_element.classes.contains('disabled'));

  _toggle(behaviors, condition) {
    if(condition)
      behaviors[0]();
    else
      behaviors[1]();
  }

  get dom_element => this.component.dom_element;

}


// Copyright (c) 2013, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

library spark_widgets;

import 'dart:html';

import 'package:polymer/polymer.dart';

bool IS_DART2JS = identical(1, 1.0);

// NOTE: This SparkWidget element is not intended to use directly.
@CustomTag('spark-widget')
class SparkWidget extends PolymerElement {
  static const CSS_ENABLED = "enabled";
  static const CSS_DISABLED = "disabled";

  // Popular key codes
  static const DOWN_KEY = 40;
  static const UP_KEY = 38;
  static const ENTER_KEY = 13;
  static const ESCAPE_KEY = 27;

  SparkWidget.created() : super.created();

  @override
  bool get applyAuthorStyles => true;

  String joinClasses(List<String> cls) => cls.join(" ");

  Element getShadowDomElement(String selectors) =>
      shadowRoot.querySelector(selectors);

  void focus() {
    // Only the first found element that has 'focused' attribute on it will be
    // actually focused; if there are more than one, the rest will be ignored.
    Element elementToFocus = this.getShadowDomElement('[focused]');
    if (elementToFocus != null) {
      elementToFocus.focus();
    }
  }
}

Remove overridden applyAuthorStyles (obsoleted in Chrome M34)

// Copyright (c) 2013, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

library spark_widgets;

import 'dart:html';

import 'package:polymer/polymer.dart';

bool IS_DART2JS = identical(1, 1.0);

// NOTE: This SparkWidget element is not intended to use directly.
@CustomTag('spark-widget')
class SparkWidget extends PolymerElement {
  static const CSS_ENABLED = "enabled";
  static const CSS_DISABLED = "disabled";

  // Popular key codes
  static const DOWN_KEY = 40;
  static const UP_KEY = 38;
  static const ENTER_KEY = 13;
  static const ESCAPE_KEY = 27;

  SparkWidget.created() : super.created();

  String joinClasses(List<String> cls) => cls.join(" ");

  Element getShadowDomElement(String selectors) =>
      shadowRoot.querySelector(selectors);

  void focus() {
    // Only the first found element that has 'focused' attribute on it will be
    // actually focused; if there are more than one, the rest will be ignored.
    Element elementToFocus = this.getShadowDomElement('[focused]');
    if (elementToFocus != null) {
      elementToFocus.focus();
    }
  }
}


class Position {

  Position._({
    this.longitude,
    this.latitude,
    this.accuracy,
    this.altitude,
    this.altitudeAccuracy,
    this.heading,
    this.speed,
    this.speedAccuracy
  });

  final double latitude;
  final double longitude;
  final double altitude;
  final double accuracy;
  final double altitudeAccuracy;
  final double heading;
  final double speed;
  final double speedAccuracy;

  static Position fromMap(dynamic message) {
    final Map<dynamic, dynamic> map = message;

    return new Position._(
        latitude: map['latitude'],
        longitude: map['longitude'],
        altitude: map.containsKey('altitude') ? map['altitude'] : 0.0,
        accuracy: map.containsKey('accuracy') ? map['accuracy'] : 0.0,
        heading: map.containsKey('heading') ? map['heading'] : 0.0,
        speed: map.containsKey('speed') ? map['speed'] : 0.0,
        speedAccuracy: map.containsKey('speed_accuracy') ? map['speed_accuracy'] : 0.0,
    );
  }
}

Add documentation to the Position class

/// Contains detail location information.
class Position {

  Position._({
    this.longitude,
    this.latitude,
    this.accuracy,
    this.altitude,
    this.heading,
    this.speed,
    this.speedAccuracy
  });

  /// Gets or sets the location latitude.
  final double latitude;
  /// Gets or sets the location longitude.
  final double longitude;
  /// Gets or sets the altitude of the device.
  ///
  /// The altitude is not available on all devices. In these cases the value is 0.0.
  final double altitude;
  /// Gets or sets the accuracy of the device.
  ///
  /// The accuracy is not available on all devices. In these cases the value is 0.0.
  final double accuracy;
  /// Gets or sets the heading of the device.
  ///
  /// The heading is not available on all devices. In these cases the value is 0.0.
  final double heading;
  /// Gets or sets the speed at which the device is travelling
  ///
  /// The speed is not available on all devices. In these cases the value is 0.0.
  final double speed;
  /// Gets or sets the accuracy at which the traveling speed of the device was determined.
  ///
  /// The speedAccuracy is not available on all devices. In these cases the value is 0.0.
  final double speedAccuracy;

  /// Converts the supplied [Map] to an instance of the [Position] class.
  static Position fromMap(dynamic message) {
    final Map<dynamic, dynamic> map = message;

    return new Position._(
        latitude: map['latitude'],
        longitude: map['longitude'],
        altitude: map.containsKey('altitude') ? map['altitude'] : 0.0,
        accuracy: map.containsKey('accuracy') ? map['accuracy'] : 0.0,
        heading: map.containsKey('heading') ? map['heading'] : 0.0,
        speed: map.containsKey('speed') ? map['speed'] : 0.0,
        speedAccuracy: map.containsKey('speed_accuracy') ? map['speed_accuracy'] : 0.0,
    );
  }
}


library textmarker;

import 'dart:html';

class TextMarker {
  String targettext;
  int startposition;
  int endposition;
  String textState; // were characters from start to end position typed correctly.

  TextMarker(this.targettext,this.startposition, this.endposition,this.textState);

  SpanElement textSpan(int start,end, String classname) {
    var span = new SpanElement()
      ..classes.add(classname)
      ..text = targettext.substring(start,end);
    return span;
  }
}

Add span functions for different textstates.

library textmarker;

import 'dart:html';

class TextMarker {
  String targettext;
  int startposition;
  int endposition;
  String textState; // were characters from start to end position typed correctly.

  TextMarker(this.targettext,this.startposition, this.endposition,this.textState);

  SpanElement textSpan(int start,end, String classname) {
    var span = new SpanElement()
      ..classes.add(classname)
      ..text = targettext.substring(start,end);
    return span;
  }
  SpanElement typedCorrectly(int start,end) {
    return textSpan(start,end, 'typedcorrect');
  }
  SpanElement typedIncorrectly(int start,end) {
    return textSpan(start,end, 'typedincorrect');
  }
  SpanElement yetToBeTyped(int start,end) {
    return textSpan(start,end, 'nottyped');
  }
}


part of streamy.testing;

class DynamicEntity extends RawEntity {

  DynamicEntity() : super();

  DynamicEntity.fromMap(Map data) {
    data.forEach((key, value) {
      this[key] = toObservable(value);
    });
  }

  noSuchMethod(Invocation invocation) {
    var memberName = MirrorSystem.getName(invocation.memberName);
    if (invocation.isGetter) {
      return this[memberName];
    } else if (invocation.isSetter) {
      // Setter member names have an '=' at the end, strip it.
      var key = memberName.substring(0, memberName.length - 1);
      this[key] = invocation.positionalArguments[0];
    } else {
      // Perhaps the called was trying to call a nonexistent method,
      // or perhaps the caller was trying to invoke a data member as a
      // completion. Throw an appropriate error.
      if (containsKey(memberName)) {
        throw new ClosureInvocationException(memberName);
      } else {
        // The Invocation class and NoSuchMethodError have different ideas
        // about the type of the named arguments map.
        Map<String, dynamic> namedArgs = {};
        for (key in invocation.namedArguments.keys) {
          namedArgs[MirrorSystem.getName(key)] = invocation.namedArguments[key];
        }
        throw new NoSuchMethodError(this, memberName,
            invocation.positionalArguments, namedArgs);
      }
    }
  }

  Type get streamyType => DynamicEntity;
}

class ClosureInvocationException extends StreamyException {

  final String memberName;

  ClosureInvocationException(this.memberName);

  String toString() => "Fields of DynamicEntity objects can't be invoked, as " +
      'they cannot contain closures. Field: $memberName';
}

Remove obsolete namedArguments workaround in DynamicEntity

part of streamy.testing;

class DynamicEntity extends RawEntity {

  DynamicEntity() : super();

  DynamicEntity.fromMap(Map data) {
    data.forEach((key, value) {
      this[key] = toObservable(value);
    });
  }

  noSuchMethod(Invocation invocation) {
    var memberName = MirrorSystem.getName(invocation.memberName);
    if (invocation.isGetter) {
      return this[memberName];
    } else if (invocation.isSetter) {
      // Setter member names have an '=' at the end, strip it.
      var key = memberName.substring(0, memberName.length - 1);
      this[key] = invocation.positionalArguments[0];
    } else {
      // Perhaps the called was trying to call a nonexistent method,
      // or perhaps the caller was trying to invoke a data member as a
      // completion. Throw an appropriate error.
      if (containsKey(memberName)) {
        throw new ClosureInvocationException(memberName);
      } else {
        throw new NoSuchMethodError(this, memberName,
            invocation.positionalArguments, invocation.namedArguments);
      }
    }
  }

  Type get streamyType => DynamicEntity;
}

class ClosureInvocationException extends StreamyException {

  final String memberName;

  ClosureInvocationException(this.memberName);

  String toString() => "Fields of DynamicEntity objects can't be invoked, as " +
      'they cannot contain closures. Field: $memberName';
}