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

class DOMWrapperBase extends NativeFieldWrapperClass2 implements DOMType {
  var dartObjectLocalStorage;
}

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

class DOMWrapperBase extends NativeFieldWrapperClass1 implements DOMType {
  var dartObjectLocalStorage;
}

Adjust native field wrapper field count.

See corresponding change in WebKit: http://codereview.chromium.org/9837116/.

R=antonm@chromium.org

Review URL: https://chromiumcodereview.appspot.com//9968004

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@6034 260f80e4-7a28-3924-810f-c04153c831b5


import 'package:flutter/foundation.dart' show BindingBase;
import 'package:flutter/widgets.dart' show Element;

/// If you need your provider to be notified when 'Hot Reload' occurs,
/// use this class
///
/// '''dart
/// class MyChangeNotifier extends ChangeNotifier with ReassembleHandler {}
/// '''
abstract class ReassembleHandler {
  /// Called when 'Hot Reload' occurs
  ///
  /// See also:
  ///
  ///  * [Element.reassemble]
  ///  * [BindingBase.reassembleApplication]
  void reassemble();
}

import 'package:flutter/foundation.dart' show BindingBase;
import 'package:flutter/widgets.dart' show Element;

/// If you need your provider to be notified when 'Hot Reload' occurs,
/// use this class
///
/// ```dart
/// class MyChangeNotifier extends ChangeNotifier with ReassembleHandler {}
/// ```
abstract class ReassembleHandler {
  /// Called when 'Hot Reload' occurs
  ///
  /// See also:
  ///
  ///  * [Element.reassemble]
  ///  * [BindingBase.reassembleApplication]
  void reassemble();
}

Fix ReassembleHandler example in class docs


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

import '../state.dart';
import 'device_avatar.dart';
import 'device_picker_dialog.dart';

class DeviceButton extends ConsumerWidget {
  final double radius;
  const DeviceButton({super.key, this.radius = 16});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final deviceNode = ref.watch(currentDeviceProvider);
    final deviceData = ref.watch(currentDeviceDataProvider);
    Widget deviceWidget;
    if (deviceNode != null) {
      if (deviceData != null) {
        deviceWidget = DeviceAvatar.yubiKeyData(
          deviceData,
          selected: true,
          radius: radius,
        );
      } else {
        deviceWidget = DeviceAvatar.deviceNode(
          deviceNode,
          selected: true,
          radius: radius,
        );
      }
    } else {
      deviceWidget = DeviceAvatar(
        radius: radius,
        child: const Icon(Icons.more_horiz),
      );
    }
    return Padding(
      padding: const EdgeInsets.only(right: 8.0),
      child: IconButton(
        tooltip: 'Select YubiKey or device',
        icon: OverflowBox(
          maxHeight: 44,
          maxWidth: 44,
          child: deviceWidget,
        ),
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) => const DevicePickerDialog(),
          );
        },
      ),
    );
  }
}

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

import '../state.dart';
import 'device_avatar.dart';
import 'device_picker_dialog.dart';

class DeviceButton extends ConsumerWidget {
  final double radius;
  const DeviceButton({super.key, this.radius = 16});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final deviceNode = ref.watch(currentDeviceProvider);
    final deviceData = ref.watch(currentDeviceDataProvider);
    Widget deviceWidget;
    if (deviceNode != null) {
      if (deviceData != null) {
        deviceWidget = DeviceAvatar.yubiKeyData(
          deviceData,
          selected: true,
          radius: radius,
        );
      } else {
        deviceWidget = DeviceAvatar.deviceNode(
          deviceNode,
          selected: true,
          radius: radius,
        );
      }
    } else {
      deviceWidget = DeviceAvatar(
        radius: radius,
        selected: true,
        child: const Icon(Icons.usb),
      );
    }
    return Padding(
      padding: const EdgeInsets.only(right: 8.0),
      child: IconButton(
        tooltip: 'Select YubiKey or device',
        icon: OverflowBox(
          maxHeight: 44,
          maxWidth: 44,
          child: deviceWidget,
        ),
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) => const DevicePickerDialog(),
          );
        },
      ),
    );
  }
}

Use USB icon for no device when in USB mode.


library dartdoc_runner.cleaners.package_cleaner;

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

import 'package:dartdoc_runner/config.dart';
import 'package:dartdoc_runner/package.dart';
import 'package:logging/logging.dart';

var _logger = new Logger("package_cleaner");

class PackageCleaner {
  final Config config;
  PackageCleaner(this.config);

  Future<Null> delete(Iterable packages) async {
    var futures = packages.map((Package package) async {
      _logger.info("Deleting pubcache and output directory for the package $package");
      await new Directory(package.pubCacheDir(config)).delete(recursive: true);
      await new Directory(package.outputDir(config)).delete(recursive: true);
    });
    await Future.wait(futures);
  }
}

library dartdoc_runner.cleaners.package_cleaner;

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

import 'package:dartdoc_runner/config.dart';
import 'package:dartdoc_runner/package.dart';
import 'package:logging/logging.dart';
import 'package:yaml/yaml.dart' as yaml;
import 'package:dartdoc_runner/version.dart';

var _logger = new Logger("package_cleaner");

class PackageCleaner {
  final Config config;
  PackageCleaner(this.config);

  Future<Null> delete(Iterable packages) async {
    var futures = packages.map((Package package) async {
      _logger.info("Deleting output directory for the package $package");
      await new Directory(package.outputDir(config)).delete(recursive: true);
      if (!_usedByDartDocGeneratorPackages.contains(package)) {
        _logger.info("Deleting pubcache directory for the package $package");
        await new Directory(package.pubCacheDir(config)).delete(recursive: true);
      }
    });
    await Future.wait(futures);
  }

  Set<Package> _usedByDartDocGeneratorPackagesMemoizer;
  Set<Package> get _usedByDartDocGeneratorPackages {
    if (_usedByDartDocGeneratorPackagesMemoizer == null) {
      Map<String, Map<String, String>> lockfile = yaml.loadYaml(new File("pubspec.lock").readAsStringSync())["packages"];
      var packages = new Set();
      lockfile.forEach((String key, Map<String, String> values) {
        packages.add(new Package(key, new Version(values["version"])));
      });
      _usedByDartDocGeneratorPackagesMemoizer = packages;
    }
    return _usedByDartDocGeneratorPackagesMemoizer;
  }
}

Make sure we don't delete the packages dartdocs-generator depends on


// 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';

double timeBase = null;

Image image;

void beginFrame(double timeStamp) {
  if (timeBase == null) timeBase = timeStamp;
  double delta = timeStamp - timeBase;
  PictureRecorder canvas = new PictureRecorder(view.width, view.height);
  canvas.translate(view.width / 2.0, view.height / 2.0);
  canvas.rotateDegrees(delta / 10);
  canvas.scale(0.2, 0.2);
  Paint paint = new Paint()..setARGB(255, 0, 255, 0);
  canvas.drawImage(image, -image.width / 2.0, -image.height / 2.0, paint);
  view.picture = canvas.endRecording();
  view.scheduleFrame();
}

void main() {
  image = new Image();
  image.src = "https://www.dartlang.org/logos/dart-logo.png";
  view.setBeginFrameCallback(beginFrame);
  view.scheduleFrame();
}

// 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';

double timeBase = null;

Image image = null;

void beginFrame(double timeStamp) {
  if (timeBase == null) timeBase = timeStamp;
  double delta = timeStamp - timeBase;
  PictureRecorder canvas = new PictureRecorder(view.width, view.height);
  canvas.translate(view.width / 2.0, view.height / 2.0);
  canvas.rotateDegrees(delta / 10);
  canvas.scale(0.2, 0.2);
  Paint paint = new Paint()..setARGB(255, 0, 255, 0);
  if (image != null)
    canvas.drawImage(image, -image.width / 2.0, -image.height / 2.0, paint);
  view.picture = canvas.endRecording();
  view.scheduleFrame();
}

void main() {
  new ImageLoader("https://www.dartlang.org/logos/dart-logo.png", (result) {
    if (result != null) {
      print("${result.width}x${result.width} image loaded!");
      image = result;
      view.scheduleFrame();
    } else {
      print("Image failed to load");
    }
  }).load();
  view.setBeginFrameCallback(beginFrame);
}

Refactor image handling in Sky to expose the loader and image as separate classes to Dart code. This makes it possible to avoid unnecessary paints, by only painting once when the image has loaded. Now that we've separated the loader and image classes, we can implement an image cache in Dart.

R=abarth@chromium.org, abarth

Review URL: https://codereview.chromium.org/1156003007


import 'block_parser.dart';
import 'inline_parser.dart';

class ExtensionSet {
  static ExtensionSet none = new ExtensionSet._([], []);

  static ExtensionSet commonMark = new ExtensionSet._(
      [const FencedCodeBlockSyntax()], [new InlineHtmlSyntax()]);

  static ExtensionSet gitHub = new ExtensionSet._(
      [const FencedCodeBlockSyntax(), const TableSyntax()],
      [new InlineHtmlSyntax()]);

  final List<BlockSyntax> blockSyntaxes;
  final List<InlineSyntax> inlineSyntaxes;

  ExtensionSet._(this.blockSyntaxes, this.inlineSyntaxes);
}

import 'block_parser.dart';
import 'inline_parser.dart';

class ExtensionSet {
  static final ExtensionSet none = new ExtensionSet._([], []);

  static final ExtensionSet commonMark = new ExtensionSet._(
      [const FencedCodeBlockSyntax()], [new InlineHtmlSyntax()]);

  static final ExtensionSet gitHub = new ExtensionSet._(
      [const FencedCodeBlockSyntax(), const TableSyntax()],
      [new InlineHtmlSyntax()]);

  final List<BlockSyntax> blockSyntaxes;
  final List<InlineSyntax> inlineSyntaxes;

  ExtensionSet._(this.blockSyntaxes, this.inlineSyntaxes);
}

Make ExtensionSet static fields final

Make ExtensionSet static fields final


part of main;

/// This controller is completely arbitrary. You can choose to set up
/// your environment however you like!
class ErrorController {
  Future<Response> general(
      Object exception,
      StackTrace stack) {
    print('<red>Uncaught error!\n$exception</red>');
    return _errorTemplate(exception, stack);
  }

  Future<Response> notFound(
      HttpNotFoundException exception,
      StackTrace stack) {
    return _errorTemplate(exception, stack, 404, {
      'message': "Oops! That page wasn't found!"
    });
  }

  Future<Response> _errorTemplate(
      Object exception,
      StackTrace stack,
      [int code = 500,
      Map<String, dynamic> variables = const {}]) async {

    // Create a template with the specified parameters
    final errorTemplate = await (template('error', withData: variables)
      ..exception = exception
      ..stackTrace = stack
      ..code = code);

    // Return a shelf Response from the template and the params
    return new Response(
        code,
        body: errorTemplate.encoded,
        headers: {
          'Content-Type': ContentType.HTML.toString()
        });
  }
}

part of main;

/// This controller is completely arbitrary. You can choose to set up
/// your environment however you like!
class ErrorController {
  // lib/templates/error.chalk.html
  static const errorTemplate = 'error';

  Future<Response> general(
      Object exception,
      StackTrace stack) {
    print('<red>Uncaught error!\n$exception</red>');
    return _errorTemplate(exception, stack);
  }

  Future<Response> notFound(
      HttpNotFoundException exception,
      StackTrace stack) {
    return _errorTemplate(exception, stack, 404, {
      'message': "Oops! That page wasn't found!"
    });
  }

  Future<Response> _errorTemplate(
      Object exception,
      StackTrace stack,
      [int code = 500,
      Map<String, dynamic> variables = const {}]) async {

    // Create a template with the specified parameters
    final errorTemplate = await (template(errorTemplate, withData: variables)
      ..exception = exception
      ..stackTrace = stack
      ..code = code);

    // Return a shelf Response from the template and the params
    return new Response(
        code,
        body: errorTemplate.encoded,
        headers: {
          'Content-Type': ContentType.HTML.toString()
        });
  }
}

Set a constant for the error template to use in ErrorController


#!/usr/bin/env dart

import 'dart:io';

import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/scanner.dart';

import 'package:async_await/src/error_collector.dart';
import 'package:async_await/src/xform.dart';

main(List<String> args) {
  if (args.length != 1) {
    print('Usage: async_await.dart [file]');
    exit(0);
  }

  var errorListener = new _ErrorCollector();
  var unit = _parse(new File(args.first), errorListener);
  var analysis = new AnalysisVisitor();
  analysis.visit(unit);
  var transform = new AsyncTransformer(analysis.awaits);
  print(transform.visit(unit));

  for (var error in errorListener.errors) {
    print(error);
  }
}

_parse(File file, AnalysisErrorListener errorListener) {
  var src = file.readAsStringSync();
  var reader = new CharSequenceReader(src);
  var scanner = new Scanner(null, reader, errorListener);
  var token = scanner.tokenize();
  var parser = new Parser(null, errorListener);
  parser.parseAsync = true;
  return parser.parseCompilationUnit(token);
}

#!/usr/bin/env dart

import 'dart:io';

import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/scanner.dart';

import 'package:async_await/src/error_collector.dart';
import 'package:async_await/src/xform.dart';

main(List<String> args) {
  if (args.length != 1) {
    print('Usage: async_await.dart [file]');
    exit(0);
  }

  var errorListener = new ErrorCollector();
  var unit = _parse(new File(args.first), errorListener);
  var analysis = new AnalysisVisitor();
  analysis.visit(unit);
  var transform = new AsyncTransformer(analysis.awaits);
  print(transform.visit(unit));

  for (var error in errorListener.errors) {
    print(error);
  }
}

_parse(File file, AnalysisErrorListener errorListener) {
  var src = file.readAsStringSync();
  var reader = new CharSequenceReader(src);
  var scanner = new Scanner(null, reader, errorListener);
  var token = scanner.tokenize();
  var parser = new Parser(null, errorListener);
  parser.parseAsync = true;
  return parser.parseCompilationUnit(token);
}

Fix typo in class name.

Fix typo in class name.


import 'package:angular2/core.dart';
import 'package:np8080/document/textdocument.dart';
import 'package:np8080/services/textprocessingservice.dart';

@Component(
    selector: 'generate-dialog',
    templateUrl: 'generate_component.html',
    providers: const [TextProcessingService])
class GenerateDialogComponent {
  @Input()
  bool showDialog = false;

  @Input()
  TextDocument note;

  @Output()
  EventEmitter<bool> showDialogChange = new EventEmitter<bool>();

  String textToRepeat;
  num repeatCount = 10;

  final TextProcessingService _textProcessingService;

  GenerateDialogComponent(this._textProcessingService);

  void closeTheDialog() {
    showDialog = false;
    showDialogChange.emit(showDialog);
  }

  void onSubmit() {
    note.text +=
        _textProcessingService.getRepeatedString(textToRepeat, repeatCount);
  }
}

import 'package:angular2/core.dart';
import 'package:np8080/document/textdocument.dart';
import 'package:np8080/services/textprocessingservice.dart';

@Component(
    selector: 'generate-dialog',
    templateUrl: 'generate_component.html',
    providers: const [TextProcessingService])
class GenerateDialogComponent {
  @Input()
  bool showDialog = false;

  @Input()
  TextDocument note;

  @Output()
  EventEmitter<bool> showDialogChange = new EventEmitter<bool>();

  String textToRepeat;
  num repeatCount = 10;

  final TextProcessingService _textProcessingService;

  GenerateDialogComponent(this._textProcessingService);

  void closeTheDialog() {
    textToRepeat = "";
    showDialog = false;
    showDialogChange.emit(showDialog);
  }

  void onSubmit() {
    note.text +=
        _textProcessingService.getRepeatedString(textToRepeat, repeatCount);
    note.save();
  }
}

Reset dialog contents and save changes.

Reset dialog contents and save changes.


// 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.
// Check const classes.

class AConst {
  const AConst() : b_ = 3 ;
  final int b_;
}

class ConstTest {
  static testMain() {
    var o = const AConst();
    Expect.equals(3, o.b_);
  }
}

main() {
  ConstTest.testMain();
}

// 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.
// Check const classes.

class AConst {
  const AConst() : b_ = 3 ;
  final int b_;
}

class BConst {
  const BConst();
  set foo(value) {}
  get foo() { return 5; }

  operator [](ix) { return ix; }
  operator []=(ix, value) {}
}

testMain() {
  var o = const AConst();
  Expect.equals(3, o.b_);

  var x = (const BConst()).foo++;
  Expect.equals(5, x);

  var y = (const BConst())[5]++;
  Expect.equals(5, y);
}

main() {
  for (int i = 0; i < 1000; i++) {
    testMain();
  }
}

Add more const tests.
Review URL: https://chromiumcodereview.appspot.com//9608008

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@5129 260f80e4-7a28-3924-810f-c04153c831b5


#library('NativeGCTest');
#import('../../lib/unittest/unittest.dart');
#import('../../lib/unittest/html_config.dart');
#import('dart:html');

main() {
  useHtmlConfiguration();

  test('EventListener', () {
      final int N = 1000000;
      final int M = 1000;

      var div;
      for (int i = 0; i < M; ++i) {
        // This memory should be freed when the listener below is
        // collected.
        List l = new List(N);

        // Record the iteration number.
        l[N - 1] = i;

        div = new Element.tag('div');
        div.on['test'].add((_) {
            // Only the final iteration's listener should be invoked.
            // Note: the reference to l keeps the entire list alive.
            Expect.equals(M - 1, l[N - 1]);
          }, false);
      }

      final event = new Event('test');
      div.on['test'].dispatch(event);
  });
}

#library('NativeGCTest');
#import('../../lib/unittest/unittest.dart');
#import('../../lib/unittest/html_config.dart');
#import('dart:html');

main() {
  useHtmlConfiguration();

  test('EventListener', () {
      final int N = 1000000;
      final int M = 1000;

      var div;
      for (int i = 0; i < M; ++i) {
        // This memory should be freed when the listener below is
        // collected.
        List l = new List(N);

        // Record the iteration number.
        l[N - 1] = i;

        div = new Element.tag('div');
        div.on['test'].add((_) {
            // Only the final iteration's listener should be invoked.
            // Note: the reference to l keeps the entire list alive.
            Expect.equals(M - 1, l[N - 1]);
          }, false);
      }

      final event = new Event('test');
      div.on['test'].dispatch(event);
  });

  test('WindowEventListener', () {
    Element testDiv = new DivElement();
    testDiv.id = '#TestDiv';
    document.body.nodes.add(testDiv);
    window.on.message.add((e) => testDiv.click());

    for (int i = 0; i < 100; ++i) {
      triggerMajorGC();
    }

    testDiv.on.click.add(expectAsync1((e) {}));
    window.postMessage('test', '*');
  });
}

void triggerMajorGC() {
  List list = new List(1000000);
  Element div = new DivElement();
  div.on.click.add((e) => print(list[0]));
}

Add test for garbage collected window event listeners issue.

R=antonm@google.com

Review URL: https://chromiumcodereview.appspot.com//10689120

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@9497 260f80e4-7a28-3924-810f-c04153c831b5


library dart_coveralls.coveralls_endpoint;

import 'dart:async' show Future;
import 'dart:convert' show JSON;

import 'package:http/http.dart' show MultipartRequest, MultipartFile, Response;

import 'coveralls_entities.dart';
import 'log.dart';

class CoverallsEndpoint {
  static const String COVERALLS_ADDRESS = "https://coveralls.io/api/v1/jobs";

  final Uri coverallsAddress;

  CoverallsEndpoint([coverallsAddress = COVERALLS_ADDRESS])
      : coverallsAddress = coverallsAddress is Uri
            ? coverallsAddress
            : Uri.parse(COVERALLS_ADDRESS);

  MultipartRequest _getCoverallsRequest(String json) {
    var req = new MultipartRequest("POST", coverallsAddress);
    req.files.add(
        new MultipartFile.fromString("json_file", json, filename: "json_file"));
    return req;
  }

  Future<CoverallsResult> sendToCoveralls(String json) async {
    var req = _getCoverallsRequest(json);
    log.info('Sending coverage information. JSON length: ${json.length}');
    var streamedResponse = await req.send();
    Response response = await Response.fromStream(streamedResponse);
    log.info('Coverage information sent.');

    var msg = response.body;

    if (response.statusCode != 200) {
      throw new Exception("${response.reasonPhrase}\n$msg");
    }
    log.info("200 OK");
    log.info("Response:\n$msg");

    var resultJson = JSON.decode(msg);
    return new CoverallsResult.fromJson(resultJson);
  }
}

library dart_coveralls.coveralls_endpoint;

import 'dart:async' show Future;
import 'dart:convert' show JSON;

import 'package:http/http.dart' show MultipartRequest, MultipartFile, Response;

import 'coveralls_entities.dart';
import 'log.dart';

class CoverallsEndpoint {
  static const String COVERALLS_ADDRESS = "https://coveralls.io/api/v1/jobs";

  final Uri coverallsAddress;

  CoverallsEndpoint([coverallsAddress = COVERALLS_ADDRESS])
      : coverallsAddress = coverallsAddress is Uri
            ? coverallsAddress
            : Uri.parse(COVERALLS_ADDRESS);

  MultipartRequest _getCoverallsRequest(String json) {
    var req = new MultipartRequest("POST", coverallsAddress);
    req.files.add(
        new MultipartFile.fromString("json_file", json, filename: "json_file"));
    return req;
  }

  Future<CoverallsResult> sendToCoveralls(String json) async {
    var req = _getCoverallsRequest(json);
    log.info('Sending coverage information. JSON length: ${json.length}');
    var streamedResponse = await req.send();
    Response response = await Response.fromStream(streamedResponse);
    log.info('Coverage information sent.');

    var msg = response.body;

    if (response.statusCode != 200) {
      throw new Exception("${response.reasonPhrase}");
    }
    log.info("200 OK");
    log.info("Response:\n$msg");

    var resultJson = JSON.decode(msg);
    return new CoverallsResult.fromJson(resultJson);
  }
}

Stop logging of HTML if status!=200

Stop logging of HTML if status!=200


// 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.
library kernel.target.flutter;

import 'targets.dart';
import 'vm.dart' show VmTarget;

class FlutterTarget extends VmTarget {
  FlutterTarget(TargetFlags flags) : super(flags);

  @override
  String get name => 'flutter';

  // This is the order that bootstrap libraries are loaded according to
  // `runtime/vm/object_store.h`.
  @override
  List<String> get extraRequiredLibraries => const <String>[
        'dart:async',
        'dart:collection',
        'dart:convert',
        'dart:developer',
        'dart:_internal',
        'dart:isolate',
        'dart:math',

        // The library dart:mirrors may be ignored by the VM, e.g. when built in
        // PRODUCT mode.
        'dart:mirrors',

        'dart:profiler',
        'dart:typed_data',
        'dart:nativewrappers',
        'dart:io',

        // Required for flutter.
        'dart:ui',
      ];
}

// 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.
library kernel.target.flutter;

import 'targets.dart';
import 'vm.dart' show VmTarget;

class FlutterTarget extends VmTarget {
  FlutterTarget(TargetFlags flags) : super(flags);

  @override
  String get name => 'flutter';

  // This is the order that bootstrap libraries are loaded according to
  // `runtime/vm/object_store.h`.
  @override
  List<String> get extraRequiredLibraries => const <String>[
        'dart:async',
        'dart:collection',
        'dart:convert',
        'dart:developer',
        'dart:_internal',
        'dart:isolate',
        'dart:math',

        // The library dart:mirrors may be ignored by the VM, e.g. when built in
        // PRODUCT mode.
        'dart:mirrors',

        'dart:profiler',
        'dart:typed_data',
        'dart:nativewrappers',
        'dart:io',

        // Required for flutter.
        'dart:ui',
        'dart:vmservice_sky',
      ];
}

Add vmservice_sdk to target as it is needed in platform.dill to be included into app dill file for Flutter release gen_snapshot

Bug:
Change-Id: I699768ef6f3a315d497bc65c7d713d0c538313ca
Reviewed-on: https://dart-review.googlesource.com/12783
Reviewed-by: Zach Anderson <9f8b31e960a68dade71618f1ff6da6e23a1edfc9@google.com>
Commit-Queue: Alexander Aprelev <dfb74c35a357c2059971a4bf7fe26b6a7c18085d@google.com>


library app_initializer;

import 'package:angular/angular.dart';
import 'package:di/di.dart';
import 'package:di/static_injector.dart';

// Generated Files!
import 'di_factories_gen.dart' as di_factories_gen;
import 'ng_parser_gen.dart' as ng_parser_gen;

createInjector(List<Module> modules) {
  di_factories_gen.main();
  return new StaticInjector(modules: modules,
      typeFactories: di_factories_gen.typeFactories);
}

createParser(Module module) {
  module.type(Parser, implementedBy: StaticParser);
  module.factory(StaticParserFunctions,
      (i) => ng_parser_gen.functions(i.get(FilterMap)));
}

library app_initializer;

import 'package:angular/angular.dart';
import 'package:di/di.dart';
import 'package:di/static_injector.dart';

// Generated Files!
import 'di_factories_gen.dart' as di_factories_gen;
import 'ng_parser_gen.dart' as ng_parser_gen;

createInjector(List<Module> modules) {
  di_factories_gen.main();
  return new StaticInjector(modules: modules,
      typeFactories: di_factories_gen.typeFactories);
}

createParser(Module module) {
  module.factory(Parser, (i) {
    StaticParserFunctions fns = ng_parser_gen.functions(i.get(FilterMap));
    return new StaticParser(fns, null);
  });
}

Update to the latest StaticParser

fix(static-injector): Update to the latest StaticParser


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

class CopyIntent extends Intent {
  const CopyIntent();
}

class SearchIntent extends Intent {
  const SearchIntent();
}

final globalShortcuts = {
  LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyC):
      const CopyIntent(),
  LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyF):
      const SearchIntent(),
};

import 'dart:io';

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

class CopyIntent extends Intent {
  const CopyIntent();
}

class SearchIntent extends Intent {
  const SearchIntent();
}

final ctrlOrCmd =
    Platform.isMacOS ? LogicalKeyboardKey.meta : LogicalKeyboardKey.control;

final globalShortcuts = {
  LogicalKeySet(ctrlOrCmd, LogicalKeyboardKey.keyC): const CopyIntent(),
  LogicalKeySet(ctrlOrCmd, LogicalKeyboardKey.keyF): const SearchIntent(),
};

Use CMD on Mac, Ctrl on rest.

Use CMD on Mac, Ctrl on rest.


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

part of flutter_sprites;

class ImageMap {
  ImageMap(AssetBundle bundle) : _bundle = bundle;

  final AssetBundle _bundle;
  final Map<String, ui.Image> _images = new Map<String, ui.Image>();

  Future<List<ui.Image>> load(List<String> urls) {
    return Future.wait(urls.map(_loadImage));
  }

  Future<ui.Image> _loadImage(String url) async {
    ui.Image image = await _bundle.loadImage(url).first;
    _images[url] = image;
    return image;
  }

  ui.Image getImage(String url) => _images[url];
  ui.Image operator [](String url) => _images[url];
}

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

part of flutter_sprites;

class ImageMap {
  ImageMap(AssetBundle bundle) : _bundle = bundle;

  final AssetBundle _bundle;
  final Map<String, ui.Image> _images = new Map<String, ui.Image>();

  Future<List<ui.Image>> load(List<String> urls) {
    return Future.wait(urls.map(_loadImage));
  }

  Future<ui.Image> _loadImage(String url) async {
    ui.Image image = (await _bundle.loadImage(url).first).image;
    _images[url] = image;
    return image;
  }

  ui.Image getImage(String url) => _images[url];
  ui.Image operator [](String url) => _images[url];
}

Update flutter_sprites now that ImageResource.first returns an ImageInfo


// Copyright (c) 2014, 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 source_span.span_exception;

import 'span.dart';

/// A class for exceptions that have source span information attached.
class SourceSpanException implements Exception {
  /// A message describing the exception.
  final String message;

  /// The span associated with this exception.
  ///
  /// This may be `null` if the source location can't be determined.
  final SourceSpan span;

  SourceSpanException(this.message, this.span);

  /// Returns a string representation of [this].
  ///
  /// [color] may either be a [String], a [bool], or `null`. If it's a string,
  /// it indicates an ANSII terminal color escape that should be used to
  /// highlight the span's text. If it's `true`, it indicates that the text
  /// should be highlighted using the default color. If it's `false` or `null`,
  /// it indicates that the text shouldn't be highlighted.
  String toString({color}) {
    if (span == null) return message;
    return "Error on " + span.message(message, color: color);
  }
}

/// A [SourceSpanException] that's also a [FormatException].
class SourceSpanFormatException extends SourceSpanException
    implements FormatException {
  final source;

  int get position => span == null ? null : span.start.offset;

  SourceSpanFormatException(String message, SourceSpan span, [this.source])
      : super(message, span);
}

// Copyright (c) 2014, 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 source_span.span_exception;

import 'span.dart';

/// A class for exceptions that have source span information attached.
class SourceSpanException implements Exception {
  /// A message describing the exception.
  final String message;

  /// The span associated with this exception.
  ///
  /// This may be `null` if the source location can't be determined.
  final SourceSpan span;

  SourceSpanException(this.message, this.span);

  /// Returns a string representation of [this].
  ///
  /// [color] may either be a [String], a [bool], or `null`. If it's a string,
  /// it indicates an ANSII terminal color escape that should be used to
  /// highlight the span's text. If it's `true`, it indicates that the text
  /// should be highlighted using the default color. If it's `false` or `null`,
  /// it indicates that the text shouldn't be highlighted.
  String toString({color}) {
    if (span == null) return message;
    return "Error on " + span.message(message, color: color);
  }
}

/// A [SourceSpanException] that's also a [FormatException].
class SourceSpanFormatException extends SourceSpanException
    implements FormatException {
  final source;

  int get offset => span == null ? null : span.start.offset;

  SourceSpanFormatException(String message, SourceSpan span, [this.source])
      : super(message, span);
}

Change "FormatException.position" to be named "offset".

Address comments on SpanFormatException changes.

R=nweiz@google.com

Committed: https://code.google.com/p/dart/source/detail?r=38373

Committed: https://code.google.com/p/dart/source/detail?r=38378

Review URL: https://codereview.chromium.org//396603003

git-svn-id: e5ef7ab7c496cb8c642f2ecaf89951a3f60a5859@38379 260f80e4-7a28-3924-810f-c04153c831b5


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

import 'package:sky/widgets/checkbox.dart';
import 'package:sky/widgets/toggleable.dart';
import 'package:sky/widgets/popup_menu.dart';
import 'package:sky/widgets/basic.dart';
import 'package:sky/framework/theme/view_configuration.dart';

class StockMenu extends Component {

  StockMenu({
    Object key,
    this.controller,
    this.autorefresh: false,
    this.onAutorefreshChanged
  }) : super(key: key);

  final PopupMenuController controller;
  final bool autorefresh;
  final ValueChanged onAutorefreshChanged;

  UINode build() {
    var checkbox = new Checkbox(
      value: this.autorefresh,
      onChanged: this.onAutorefreshChanged
    );

    return new StackPositionedChild(
      new PopupMenu(
        controller: controller,
        items: [
          [new Text('Add stock')],
          [new Text('Remove stock')],
          [new FlexExpandingChild(new Text('Autorefresh')), checkbox],
        ],
        level: 4
      ),
      right: 8.0,
      top: 8.0 + kStatusBarHeight
    );
  }
}

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

import 'package:sky/widgets/checkbox.dart';
import 'package:sky/widgets/popup_menu.dart';
import 'package:sky/widgets/basic.dart';
import 'package:sky/framework/theme/view_configuration.dart';

class StockMenu extends Component {

  StockMenu({
    Object key,
    this.controller,
    this.autorefresh: false,
    this.onAutorefreshChanged
  }) : super(key: key);

  final PopupMenuController controller;
  final bool autorefresh;
  final ValueChanged onAutorefreshChanged;

  UINode build() {
    var checkbox = new Checkbox(
      value: this.autorefresh,
      onChanged: this.onAutorefreshChanged
    );

    return new StackPositionedChild(
      new PopupMenu(
        controller: controller,
        items: [
          [new Text('Add stock')],
          [new Text('Remove stock')],
          [new FlexExpandingChild(new Text('Autorefresh')), checkbox],
        ],
        level: 4
      ),
      right: 8.0,
      top: 8.0 + kStatusBarHeight
    );
  }
}

Remove unneeded import and fix analyzer warnings

R=ianh@google.com, hixie

Review URL: https://codereview.chromium.org/1190573002.


// 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:expect/expect.dart';

void main() {
  print(const Symbol(null));                                //# 01: compile-time error
  print(const Symbol(r''));                                 //# 02: ok
  Expect.isTrue(identical(const Symbol(r'foo'), #foo));     //# 03: ok
  Expect.isTrue(identical(const Symbol(r'$foo'), #$foo));   //# 03: ok
  Expect.isTrue(identical(const Symbol(r'$_'), #$_));       //# 03: ok
  Expect.isTrue(identical(const Symbol(r'+'), #+));         //# 03: ok
  Expect.isTrue(identical(const Symbol(r'[]='), #[]=));     //# 03: ok
  Expect.isTrue(identical(const Symbol(r'_foo'), #_foo));   //# 03: compile-time error
  Expect.isTrue(identical(const Symbol(r'_$'), #_$));       //# 03: compile-time error
  Expect.isTrue(identical(const Symbol(r'_foo$'), #_foo$)); //# 03: compile-time error
  print(const Symbol(r'_+'));                               //# 03: compile-time error
}

// 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:expect/expect.dart';

void main() {
  print(const Symbol(null)); //# 01: compile-time error
  print(const Symbol(r''));
  Expect.isTrue(identical(const Symbol(r'foo'), #foo));
  Expect.isTrue(identical(const Symbol(r'$foo'), #$foo));
  Expect.isTrue(identical(const Symbol(r'$_'), #$_));
  Expect.isTrue(identical(const Symbol(r'+'), #+));
  Expect.isTrue(identical(const Symbol(r'[]='), #[]=));
  Expect.isFalse(identical(const Symbol(r'_foo'), #_foo));
  Expect.isFalse(identical(const Symbol(r'_$'), #_$));
  Expect.isFalse(identical(const Symbol(r'_foo$'), #_foo$));
  print(const Symbol(r'_+'));
}

Adjust vm test about the Symbol constructor

The `Symbol` constructor has been changed to accept any string as the
actual argument (it used to require strings similar to the ones that we
can use with `#` to create a symbol literal). This CL change a vm test
such that it has the updated expectations.

Cf. https://github.com/dart-lang/sdk/issues/46207.

Change-Id: I25fa5a145b7d476372b4c2f8502eabb36ec82fec
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/205781
Commit-Queue: Erik Ernst <251bb01623bfda2cd9151e339a6e783ca432874c@google.com>
Reviewed-by: Martin Kustermann <a35dd5b79fac84b2bb3b026a16b8becc55af5961@google.com>


/*
 * 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 It is a static type warning if a type variable is supertype of
 * its upper bound.
 * @description Checks that warning is produced.
 * @static-warning
 * @author pagolubev
 * @reviewer kaigorodov
 * @needsreview issue 905
 */

class A {}
class B extends A {}

class G<T extends B> {}

main() {
  new G<A>();
}

/*
 * 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 It is a static type warning if a type variable is supertype of
 * its upper bound.
 * @description Checks that a warning is produced.
 * @static-warning
 * @author pagolubev
 * @reviewer kaigorodov
 * @needsreview issue 905
 */

#import("../../Utils/dynamic_check.dart");

class A {}
class B extends A {}

class G<T extends B> {}

main() {
  checkTypeError(() {
    new G<A>();
  });
}

Test fix: handling a type error in checked mode (issue 95)

git-svn-id: 38feb1729fd842af57e1a6ea8a5dccce4272ed9b@154 2ecb45c1-dfb3-dc95-330a-13f216d23a04


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

// Test that inlining in the compiler works with privacy.

import 'other_library.dart';

main() {
  Expect.equals(42, foo(new A()));
  Expect.throws(() => foo(new B()), (e) => e is NoSuchMethodError);
}

class B {
  _bar() => 42;
}

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

// Test that inlining in the compiler works with privacy.

library private4_test;

import 'other_library.dart';

main() {
  Expect.equals(42, foo(new A()));
  Expect.throws(() => foo(new B()), (e) => e is NoSuchMethodError);
}

class B {
  _bar() => 42;
}

Add a library tag to allow running on DRT.

R=ngeoffray@google.com

Review URL: https://codereview.chromium.org//11859031

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@17280 260f80e4-7a28-3924-810f-c04153c831b5


part of irc.parser;

/**
 * Base class for IRC Parsers
 *
 * ```
 * var parser = new SomeIrcParser();
 * var message = parser.convert(":some.server PRIVMSG #SomeChannel :Some Message");
 * // Use Message Instance
 * ```
 */
abstract class IrcParser extends Converter<String, Message> {

  /**
   * Creates the default IrcParser, which is [RegexIrcParser].
   */
  static IrcParser create() => new RegexIrcParser();

  /**
   * Parses [line] as an IRC line and outputs a [Message].
   */
  @override
  Message convert(String line);
}

part of irc.parser;

/**
 * Base class for IRC Parsers
 *
 *      var parser = new SomeIrcParser();
 *      var message = parser.convert(":some.server PRIVMSG #SomeChannel :Some Message");
 *      // Use Message Instance
 */
abstract class IrcParser extends Converter<String, Message> {

  /**
   * Creates the default IrcParser, which is [RegexIrcParser].
   */
  static IrcParser create() => new RegexIrcParser();

  /**
   * Parses [line] as an IRC line and outputs a [Message].
   */
  @override
  Message convert(String line);
}

Tweak Documentation to use spaces for the code highlighting


import 'package:meta/meta.dart';

import '../../../features/settings/presentation/bloc/settings_bloc.dart';
import 'connection_handler.dart';

abstract class GetUser {
  Future<Map<String, dynamic>> call({
    @required String tautulliId,
    @required int userId,
    @required SettingsBloc settingsBloc,
  });
}

class GetUserImpl implements GetUser {
  final ConnectionHandler connectionHandler;

  GetUserImpl({@required this.connectionHandler});

  @override
  Future<Map<String, dynamic>> call({
    @required String tautulliId,
    @required int userId,
    @required SettingsBloc settingsBloc,
  }) async {
    final responseJson = await connectionHandler(
      tautulliId: tautulliId,
      cmd: 'get_user',
      params: {
        'user_id': userId.toString(),
      },
      settingsBloc: settingsBloc,
    );

    return responseJson;
  }
}

import 'package:meta/meta.dart';

import '../../../features/settings/presentation/bloc/settings_bloc.dart';
import 'connection_handler.dart';

abstract class GetUser {
  Future<Map<String, dynamic>> call({
    @required String tautulliId,
    @required int userId,
    @required SettingsBloc settingsBloc,
  });
}

class GetUserImpl implements GetUser {
  final ConnectionHandler connectionHandler;

  GetUserImpl({@required this.connectionHandler});

  @override
  Future<Map<String, dynamic>> call({
    @required String tautulliId,
    @required int userId,
    @required SettingsBloc settingsBloc,
  }) async {
    final responseJson = await connectionHandler(
      tautulliId: tautulliId,
      cmd: 'get_user',
      params: {
        'user_id': userId.toString(),
        'include_last_seen': 'true',
      },
      settingsBloc: settingsBloc,
    );

    return responseJson;
  }
}

Set include last seen to true for get user.


part of irc.bot;

/**
 * Base Class for Bots
 */
abstract class Bot {
  Client client();

  void connect() => client().connect();

  void disconnect() => client().disconnect();

  Channel channel(String name) => client().channel(name);

  void register(handler) => client().register(handler);

  void join(String channel) => client().join(channel);

  void part(String channel) => client().part(channel);

  void message(String target, String message) => client().message(target, message);
}

part of irc.bot;

/**
 * Base Class for Bots
 */
abstract class Bot {
  Client client();

  void connect() => client().connect();

  void disconnect() => client().disconnect();

  Channel channel(String name) => client().channel(name);

  bool register(handler) => client().register(handler);

  void join(String channel) => client().join(channel);

  void part(String channel) => client().part(channel);

  void message(String target, String message) => client().message(target, message);
}

Fix Return Type for Bot.register(handler)


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

library barback.transform_logger;

import 'package:source_maps/span.dart';

/// Object used to report warnings and errors encountered while running a
/// transformer.
class TransformLogger {

  bool _shouldPrint;

  TransformLogger(this._shouldPrint);

  /// Logs a warning message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the warning.
  void warning(String message, [Span span]) {
    _printMessage('warning', message, span);
  }

  /// Logs an error message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the error.
  // TODO(sigmund,nweiz): clarify when an error should be logged or thrown.
  void error(String message, [Span span]) {
    _printMessage('error', message, span);
  }

  // TODO(sigmund,rnystrom): do something better than printing.
  _printMessage(String prefix, String message, Span span) {
    if (!_shouldPrint) return;
    print(span == null ? '$prefix $message'
        : '$prefix ${span.getLocationMessage(message)}');
  }
}

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

library barback.transform_logger;

import 'package:source_maps/span.dart';

/// Object used to report warnings and errors encountered while running a
/// transformer.
class TransformLogger {

  bool _shouldPrint;

  TransformLogger(this._shouldPrint);

  /// Logs an informative message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the message.
  void info(String message, [Span span]) {
    _printMessage('info', message, span);
  }

  /// Logs a warning message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the warning.
  void warning(String message, [Span span]) {
    _printMessage('warning', message, span);
  }

  /// Logs an error message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the error.
  // TODO(sigmund,nweiz): clarify when an error should be logged or thrown.
  void error(String message, [Span span]) {
    _printMessage('error', message, span);
  }

  // TODO(sigmund,rnystrom): do something better than printing.
  _printMessage(String prefix, String message, Span span) {
    if (!_shouldPrint) return;
    print(span == null ? '$prefix $message'
        : '$prefix ${span.getLocationMessage(message)}');
  }
}

Support dart2js in pub serve.

Support dart2js in pub serve.

R=nweiz@google.com

Review URL: https://codereview.chromium.org//24886002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@28231 260f80e4-7a28-3924-810f-c04153c831b5


import 'dart:io';

class IpAddressHelper {
  /// Returns true if IP address is not a loopback, link local, or private IP
  ///
  /// Throws a generic exception if [ipAddress] cannot be parsed
  static bool isPublic(String ipAddress) {
    final parsedAddress = InternetAddress.tryParse(ipAddress);

    if (parsedAddress == null) {
      throw Exception();
    }

    if (parsedAddress.isLinkLocal || parsedAddress.isLoopback) {
      return false;
    }

    if (parsedAddress.type == InternetAddressType.IPv4) {
      List<int> octets =
          parsedAddress.address.split('.').map((e) => int.parse(e)).toList();

      if ((octets[0] == 10) ||
          (octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31) ||
          (octets[0] == 192 && octets[1] == 168)) {
        return false;
      }
    }

    if (parsedAddress.type == InternetAddressType.IPv6) {
      if (parsedAddress.address.startsWith('fe80')) {
        return false;
      }
    }

    return true;
  }
}

import 'dart:io';

class IpAddressHelper {
  /// Returns true if IP address is not a loopback, link local, or private IP
  ///
  /// Throws a generic exception if [ipAddress] cannot be parsed
  static bool isPublic(String ipAddress) {
    final parsedAddress = InternetAddress.tryParse(ipAddress);

    if (parsedAddress == null) {
      throw Exception();
    }

    if (parsedAddress.isLinkLocal || parsedAddress.isLoopback) {
      return false;
    }

    if (parsedAddress.type == InternetAddressType.IPv4) {
      List<int> octets =
          parsedAddress.address.split('.').map((e) => int.parse(e)).toList();

      if ((octets[0] == 10) ||
          (octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31) ||
          (octets[0] == 192 && octets[1] == 168)) {
        return false;
      }
    }

    if (parsedAddress.type == InternetAddressType.IPv6) {
      if (parsedAddress.address.startsWith('fe80')) {
        return false;
      }
    }

    return true;
  }

  static String parseIpFromUrl(String url) {
    String parsedIp = '';

    RegExp ipv4Exp = RegExp(r"http[s]?:\/\/([0-9,.]+)[\S]*");
    RegExp ipv6Exp = RegExp(r"http[s]?:\/\/([[a-f,0-9,:]+])[\S]*");

    if (ipv4Exp.hasMatch(url)) {
      Iterable<Match> ipv4Matches = ipv4Exp.allMatches(url);
      ipv4Matches.forEach((m) {
        parsedIp = m.group(1);
      });
    } else if (ipv6Exp.hasMatch(url)) {
      Iterable<Match> ipv6Matches = ipv6Exp.allMatches(url);
      ipv6Matches.forEach((m) {
        parsedIp = m.group(1);
      });
    }

    return parsedIp;
  }
}

Add helper function to parse IP from URL string.


// Copyright (c) 2017, 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 type tests are not misoptimized.
// VMOptions=--optimization-counter-threshold=1000 --optimization-filter=IsAnInt

main() {
  train();
  if (IsAnInt("This is not an int")) throw "oops";
}

// Prime the IC with things that are and are not ints.
void train() {
  int sum = 0;
  for (int i = 0; i < 10000; i++) {
    IsAnInt(42); // Smi - always goes first in the generated code.
    IsAnInt(1 << 62); // Mint on 64 bit platforms.
    IsAnInt(1 << 62);
    IsAnInt(4200000000000000000000000000000000000); // BigInt
    IsAnInt(4200000000000000000000000000000000000);
    // This one that is not an int goes last in the IC because it is called
    // less frequently.
    IsAnInt(4.2);
  }
}

int IsAnInt(Foo f) => f is int;

// Copyright (c) 2017, 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 type tests are not misoptimized.
// VMOptions=--optimization-counter-threshold=1000 --optimization-filter=IsAnInt

main() {
  train();
  if (IsAnInt("This is not an int")) throw "oops";
}

// Prime the IC with things that are and are not ints.
void train() {
  for (int i = 0; i < 10000; i++) {
    IsAnInt(42); // Smi - always goes first in the generated code.
    IsAnInt(1 << 62); // Mint on 64 bit platforms.
    IsAnInt(1 << 62);
    IsAnInt(4200000000000000000000000000000000000); // BigInt
    IsAnInt(4200000000000000000000000000000000000);
    // This one that is not an int goes last in the IC because it is called
    // less frequently.
    IsAnInt(4.2);
  }
}

bool IsAnInt(f) => f is int;

Fix new test in checked mode

Fix new test in checked mode

It's also analyzer clean now.
R=vegorov@google.com
BUG=

Review-Url: https://codereview.chromium.org/2909883002 .


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

// Dart test program for testing that exceptions in other isolates bring down
// the program.

#library('Isolate2NegativeTest');
#import('dart:isolate');
#import('../../lib/unittest/unittest.dart');

void entry() {
  throw "foo";
}

main() {
  test("catch exception from other isolate", () {
    spawnFunction(entry);
  });
}

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

// Dart test program for testing that exceptions in other isolates bring down
// the program.

#library('Isolate2NegativeTest');
#import('dart:isolate');

void entry() {
  throw "foo";
}

main() {
  SendPort port = spawnFunction(entry);
}

Fix negative test by not complicating it by using the unit test framework.

R=kasperl@google.com
BUG=

Review URL: https://chromiumcodereview.appspot.com//10828145

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@10215 260f80e4-7a28-3924-810f-c04153c831b5


library webdriver_test.window;

import 'package:unittest/unittest.dart';
import 'package:webdriver/webdriver.dart';

void main() {
  group('Window', () {
    WebDriver driver;

    setUp(() async {
      driver = await WebDriver.createDriver(
          desiredCapabilities: Capabilities.chrome);
    });

    tearDown(() => driver.quit());

    test('size', () async {
      var window = await driver.window;
      var size = const Size(400, 600);
      await window.setSize(size);
      expect(await window.size, size);
    });

    test('location', () async {
      var window = await driver.window;
      var position = const Point(100, 200);
      await window.setLocation(position);
      expect(await window.location, position);
    });

    test('maximize', () async {
      var window = await driver.window;
      await window.setSize(const Size(200, 300));
      await window.setLocation(const Point(100, 200));
      await window.maximize();
      var location = await window.location;
      var size = await window.size;
      expect(location.x, lessThan(100));
      expect(location.y, lessThan(200));
      expect(size.height, greaterThan(200));
      expect(size.width, greaterThan(300));
    });
  });
}

library webdriver_test.window;

import 'package:unittest/unittest.dart';
import 'package:webdriver/webdriver.dart';

void main() {
  group('Window', () {
    WebDriver driver;

    setUp(() async {
      driver = await WebDriver.createDriver(
          desiredCapabilities: Capabilities.chrome);
    });

    tearDown(() => driver.quit());

    test('size', () async {
      var window = await driver.window;
      var size = const Size(400, 600);
      await window.setSize(size);
      expect(await window.size, size);
    });

    test('location', () async {
      var window = await driver.window;
      var position = const Point(100, 200);
      await window.setLocation(position);
      expect(await window.location, position);
    });

    // May not work on some OS/browser combinations (notably Mac OS X).
    test('maximize', () async {
      var window = await driver.window;
      await window.setSize(const Size(200, 300));
      await window.setLocation(const Point(100, 200));
      await window.maximize();
      var location = await window.location;
      var size = await window.size;
      expect(location.x, lessThan(100));
      expect(location.y, lessThan(200));
      expect(size.height, greaterThan(200));
      expect(size.width, greaterThan(300));
    });
  });
}

Add comment to maximize test to warn that it may fail in some cases.


library distributed_dart;
import 'dart:io';
import 'dart:async';
import 'dart:isolate';
import 'dart:json';
import 'dart:typeddata';

part 'src/dart_import/util/characters.dart';
//part 'src/dart_import/dart_code.dart';
part 'src/dart_import/scanner.dart';

part 'src/network/network.dart';

// logging mechanism instad of print

/**
 * Set to true for enabling debug output from the distributed_dart library.
 * Default value is false.
 */
bool logging = false;

_log(var msg) => logging ? stdout.writeln("DIST_DART, log: ${msg}") : "";
_err(var msg) => logging ? stderr.writeln("DIST_DART, err: ${msg}") : "";

library distributed_dart;
import 'dart:io';
import 'dart:async';
import 'dart:isolate';
import 'dart:json' as json;
import 'dart:typeddata';

part 'src/dart_import/util/characters.dart';
//part 'src/dart_import/dart_code.dart';
part 'src/dart_import/scanner.dart';

part 'src/network/network.dart';

// logging mechanism instad of print

/**
 * Set to true for enabling debug output from the distributed_dart library.
 * Default value is false.
 */
bool logging = false;

_log(var msg) => logging ? stdout.writeln("DIST_DART, log: ${msg}") : "";
_err(var msg) => logging ? stderr.writeln("DIST_DART, err: ${msg}") : "";

Fix error. import dart:json as json.

Fix error. import dart:json as json.


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

class Map extends StatelessWidget {
  GoogleMapController mapController;
  final LatLng _center = const LatLng(45.521563, -122.677433);
  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _center,
          zoom: 11.0,
        ),
      ),
    );
  }
}

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

class Map extends StatelessWidget {
  GoogleMapController mapController;
  final LatLng _center = const LatLng(32.8801,-117.2340);
  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _center,
          zoom: 11.0,
        ),
      ),
    );
  }
}

Set default coordinates to ucsd

Set default coordinates to ucsd


// 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 explicit import of dart:core in the source code..

#library("ImportCorePrefixTest.dart");
#import("dart:core", prefix:"mycore");

void main() {
  var test = new mycore.Map<mycore.int,mycore.String>();
  mycore.bool boolval = false;
  mycore.int variable = 10;
  mycore.num value = 10;
  mycore.dynamic d = null;
}

// 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 explicit import of dart:core in the source code..

#library("ImportCorePrefixTest.dart");
#import("dart:core", prefix:"mycore");

class Object {
}

void main() {
  var test = new mycore.Map<mycore.int,mycore.String>();
  mycore.bool boolval = false;
  mycore.int variable = 10;
  mycore.num value = 10;
  mycore.dynamic d = null;
  mycore.print(new Object());
}

Fix issue 3638
Review URL: https://codereview.chromium.org//11368157

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@14719 260f80e4-7a28-3924-810f-c04153c831b5


library debiki_admin;

import 'package:angular/angular.dart';
import 'package:perf_api/perf_api.dart';

import 'package:debiki_admin/debiki_admin_controller.dart';
import 'package:debiki_admin/component/view_topics_component.dart';
import 'package:debiki_admin/component/view_comments_component.dart';
import 'package:debiki_admin/routing/debiki_admin_router.dart';
import 'package:debiki_admin/service/query_service.dart';

// Temporary, please follow https://github.com/angular/angular.dart/issues/476
@MirrorsUsed(targets: const['debiki_admin'], override: '*')
import 'dart:mirrors';

class DebikiAdminModule extends Module {
  DebikiAdminModule() {
    type(DebikiAdminController);
    type(DebikiAdminQueryService);
    type(ViewTopicsComponent);
    type(ViewCommentsComponent);
    type(RouteInitializer, implementedBy: DebikiAdminRouteInitializer);
    factory(NgRoutingUsePushState, (_) => new NgRoutingUsePushState.value(false));
    type(Profiler, implementedBy: Profiler); // comment out to enable profiling
  }
}

main() {
  ngBootstrap(module: new DebikiAdminModule());
}

library debiki_admin;

import 'package:angular/angular.dart';
import 'package:perf_api/perf_api.dart';

import 'package:debiki_admin/debiki_admin_controller.dart';
import 'package:debiki_admin/component/view_topics_component.dart';
import 'package:debiki_admin/component/view_comments_component.dart';
import 'package:debiki_admin/routing/debiki_admin_router.dart';
import 'package:debiki_admin/service/query_service.dart';

// Temporary, please follow https://github.com/angular/angular.dart/issues/476
/* @MirrorsUsed(
    targets: const[
      'debiki_admin',
      'debiki_admin_controller',
      'view_topics_component',
      'view_comments_component'],
    override: '*') */
//import 'dart:mirrors';

class DebikiAdminModule extends Module {
  DebikiAdminModule() {
    type(DebikiAdminController);
    type(DebikiAdminQueryService);
    type(ViewTopicsComponent);
    type(ViewCommentsComponent);
    type(RouteInitializer, implementedBy: DebikiAdminRouteInitializer);
    factory(NgRoutingUsePushState, (_) => new NgRoutingUsePushState.value(false));
    type(Profiler, implementedBy: Profiler); // comment out to enable profiling
  }
}

main() {
  ngBootstrap(module: new DebikiAdminModule());
}

Remove @MirrorUsed, it breaks Javascript in Firefox

Apparently I haven't listed in `targets` all classes/things that I need to
list, so this error happens:
  TypeError: Cannot call method 'gMP' of undefined


// Copyright (c) 2022, 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.16

// ignore_for_file: unused_local_variable

import 'dart:ffi';

class MyFinalizable implements Finalizable {
  int _internalValue = 4;

  int Function() capturingThis() {
    return () {
      final result = this._internalValue;
      // Should generate: _reachabilityFence(this)
      return result;
    };
    // Should generate: _reachabilityFence(this)
  }

  int Function() capturingThis2() {
    return () {
      return this._internalValue;
      // Should generate: _reachabilityFence(this)
    };
    // Should generate: _reachabilityFence(this)
  }

  int Function() capturingThis3() {
    return () {
      return _internalValue;
      // Should generate: _reachabilityFence(this)
    };
    // Should generate: _reachabilityFence(this)
  }

  /// Tests that captures later in the body also cause fences earlier in the body.
  int Function() capturingThis4() {
    return () {
      if (DateTime.now().millisecondsSinceEpoch == 42) {
        // Should generate: _reachabilityFence(this)
        return 3;
      }
      return _internalValue;
      // Should generate: _reachabilityFence(this)
    };
    // Should generate: _reachabilityFence(this)
  }
}

void main() {}

// Copyright (c) 2022, 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.16

import 'dart:ffi';

class MyFinalizable implements Finalizable {
  int _internalValue = 4;

  int Function() capturingThis() {
    return () {
      final result = this._internalValue;
      // Should generate: _reachabilityFence(this)
      return result;
    };
    // Should generate: _reachabilityFence(this)
  }

  int Function() capturingThis2() {
    return () {
      return this._internalValue;
      // Should generate: _reachabilityFence(this)
    };
    // Should generate: _reachabilityFence(this)
  }

  int Function() capturingThis3() {
    return () {
      return _internalValue;
      // Should generate: _reachabilityFence(this)
    };
    // Should generate: _reachabilityFence(this)
  }

  /// Tests that captures later in the body also cause fences earlier in the body.
  int Function() capturingThis4() {
    return () {
      if (DateTime.now().millisecondsSinceEpoch == 42) {
        // Should generate: _reachabilityFence(this)
        return 3;
      }
      return _internalValue;
      // Should generate: _reachabilityFence(this)
    };
    // Should generate: _reachabilityFence(this)
  }
}

void main() {}

Remove an unneeded ignore comment in vm package

Change-Id: I3b81e1d66c2100b8ed1834815f318cf39a8da305
Tested: This only impacts the analyzer's reporting of diagnostics, so I ran the analyzer over the code and verified that no new diagnostics were being reported.
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/238983
Reviewed-by: Daco Harkes <930cbae0ca77f1954c53e32620d89cfcca318f00@google.com>
Commit-Queue: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>


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

library lazy_trace;

import 'frame.dart';
import 'trace.dart';

/// A thunk for lazily constructing a [Trace].
typedef Trace TraceThunk();

/// A wrapper around a [TraceThunk]. This works around issue 9579 by avoiding
/// the conversion of native [StackTrace]s to strings until it's absolutely
/// necessary.
class LazyTrace implements Trace {
  final TraceThunk _thunk;
  Trace _inner;

  LazyTrace(this._thunk);

  Trace get _trace {
    if (_inner == null) _inner = _thunk();
    return _inner;
  }

  List<Frame> get frames => _trace.frames;
  StackTrace get vmTrace => _trace.vmTrace;
  Trace get terse => new LazyTrace(() => _trace.terse);
  Trace foldFrames(bool predicate(frame)) =>
    new LazyTrace(() => _trace.foldFrames(predicate));
  String toString() => _trace.toString();
}

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

library lazy_trace;

import 'frame.dart';
import 'trace.dart';

/// A thunk for lazily constructing a [Trace].
typedef Trace TraceThunk();

/// A wrapper around a [TraceThunk]. This works around issue 9579 by avoiding
/// the conversion of native [StackTrace]s to strings until it's absolutely
/// necessary.
class LazyTrace implements Trace {
  final TraceThunk _thunk;
  Trace _inner;

  LazyTrace(this._thunk);

  Trace get _trace {
    if (_inner == null) _inner = _thunk();
    return _inner;
  }

  List<Frame> get frames => _trace.frames;
  StackTrace get vmTrace => _trace.vmTrace;
  Trace get terse => new LazyTrace(() => _trace.terse);
  Trace foldFrames(bool predicate(frame)) =>
    new LazyTrace(() => _trace.foldFrames(predicate));
  String toString() => _trace.toString();

  // Work around issue 14075.
  set frames(_) => throw new UnimplementedError();
}

Work around issue 14125 in stack_trace by adding a dummy setter.

R=rnystrom@google.com
BUG=13945

Review URL: https://codereview.chromium.org//27416002

git-svn-id: 23a8f5f0d54e45b03616c23fdace24df99c52d8d@28811 260f80e4-7a28-3924-810f-c04153c831b5


import 'package:pwa/worker.dart';
import 'package:website/pwa/offline_urls.g.dart' as offline;

/// The Progressive Web Application's entry point.
void main() {
  // The Worker handles the low-level code for initialization, fetch API
  // routing and (later) messaging.
  Worker worker = new Worker();

  // The static assets that need to be in the cache for offline mode.
  // By default it uses the automatically generated list from the output of
  // `pub build`. To refresh this list, run `pub run pwa` after each new build.
  worker.offlineUrls = offline.offlineUrls;

  // The above list can be extended with additional URLs:
  //
  // List<String> offlineUrls = new List.from(offline.offlineUrls);
  // offlineUrls.addAll(['https://www.example.org/custom/resource/']);
  // worker.offlineUrls = offlineUrls;

  // Fine-tune the caching and network fetch with dynamic caches and cache
  // strategies on the url-prefixed network routes:
  //
  // DynamicCache cache = new DynamicCache('images');
  // worker.router.registerGetUrl('https://cdn.example.com/', cache.networkFirst);

  // Start the worker.
  worker.run(version: offline.lastModified);
}

import 'package:pwa/worker.dart';
import 'package:website/pwa/offline_urls.g.dart' as offline;

/// The Progressive Web Application's entry point.
void main() {
  // The Worker handles the low-level code for initialization, fetch API
  // routing and (later) messaging.
  new Worker()

    // The static assets that need to be in the cache for offline mode.
    // By default it uses the automatically generated list from the output of
    // `pub build`. To refresh this list, run `pub run pwa` after each new build.
    ..offlineUrls = offline.offlineUrls

    // The above list can be extended with additional URLs:
    //
    // List<String> offlineUrls = new List.from(offline.offlineUrls);
    // offlineUrls.addAll(['https://www.example.org/custom/resource/']);
    // worker.offlineUrls = offlineUrls;

    // Fine-tune the caching and network fetch with dynamic caches and cache
    // strategies on the url-prefixed network routes:
    //
    // DynamicCache cache = new DynamicCache('images');
    // worker.router.registerGetUrl('https://cdn.example.com/', cache.networkFirst);

    // Start the worker.
    ..run(version: offline.lastModified);
}

Use cascading methods off of first Worker() reference [ci skip]


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

library fasta.scanner.main;

import 'io.dart' show readBytesFromFileSync;

import '../scanner.dart' show scan;

scanAll(Map<Uri, List<int>> files) {
  Stopwatch sw = new Stopwatch()..start();
  int byteCount = 0;
  files.forEach((Uri uri, List<int> bytes) {
    scan(bytes);
    byteCount += bytes.length - 1;
  });
  sw.stop();
  print("Scanning files took: ${sw.elapsed}");
  print("Bytes/ms: ${byteCount/sw.elapsedMilliseconds}");
}

mainEntryPoint(List<String> arguments) {
  Map<Uri, List<int>> files = <Uri, List<int>>{};
  Stopwatch sw = new Stopwatch()..start();
  for (String name in arguments) {
    Uri uri = Uri.base.resolve(name);
    List<int> bytes = readBytesFromFileSync(uri);
    files[uri] = bytes;
  }
  sw.stop();
  print("Reading files took: ${sw.elapsed}");
  scanAll(files);
}

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

library fasta.scanner.main;

import 'io.dart' show readBytesFromFileSync;

import '../scanner.dart' show scan;

scanAll(Map<Uri, List<int>> files) {
  Stopwatch sw = new Stopwatch()..start();
  int byteCount = 0;
  files.forEach((Uri uri, List<int> bytes) {
    var token = scan(bytes).tokens;
    if (const bool.fromEnvironment("printTokens")) {
      while (!token.isEof) {
        print("${token.charOffset}: ${token}");
        token = token.next;
      }
    }
    byteCount += bytes.length - 1;
  });
  sw.stop();
  print("Scanning files took: ${sw.elapsed}");
  print("Bytes/ms: ${byteCount/sw.elapsedMilliseconds}");
}

mainEntryPoint(List<String> arguments) {
  Map<Uri, List<int>> files = <Uri, List<int>>{};
  Stopwatch sw = new Stopwatch()..start();
  for (String name in arguments) {
    Uri uri = Uri.base.resolve(name);
    List<int> bytes = readBytesFromFileSync(uri);
    files[uri] = bytes;
  }
  sw.stop();
  print("Reading files took: ${sw.elapsed}");
  scanAll(files);
}

Add option for printing tokens produced by the scanner.

R=danrubel@google.com

Review-Url: https://codereview.chromium.org/2933533002 .


import '../../ordering.dart';

class NullsLastOrdering<T> extends Ordering<T> {
  final Ordering<T> ordering;

  const NullsLastOrdering(this.ordering);

  @override
  int compare(T a, T b) {
    if (a == null && b == null) {
      return 0;
    } else if (a == null) {
      return 1;
    } else if (identical(b, null)) {
      return -1;
    }
    return ordering.compare(a, b);
  }

  @override
  Ordering<T> get reversed => ordering.reversed.nullsFirst;

  @override
  Ordering<T> get nullsFirst => ordering.nullsFirst;

  @override
  Ordering<T> get nullsLast => this;
}

import '../../ordering.dart';

class NullsLastOrdering<T> extends Ordering<T> {
  final Ordering<T> ordering;

  const NullsLastOrdering(this.ordering);

  @override
  int compare(T a, T b) {
    if (a == null && b == null) {
      return 0;
    } else if (a == null) {
      return 1;
    } else if (b == null) {
      return -1;
    }
    return ordering.compare(a, b);
  }

  @override
  Ordering<T> get reversed => ordering.reversed.nullsFirst;

  @override
  Ordering<T> get nullsFirst => ordering.nullsFirst;

  @override
  Ordering<T> get nullsLast => this;
}

Fix another issue from the cherry-picking.


part of plugins.common;

class RequestManager {

  Map<int, Completer> _requests = {};
  final Random _rand = new Random();

  void complete(int uid, String command, Map<dynamic, dynamic> data) {
    var com = _requests[uid];
    if (com == null)
      throw new Exception("Attempt to complete an invalid request");
    com.complete(data);
  }

  int queue(Completer completer) {
    int uid = _rand.nextInt(10000);
    while (_requests.containsKey(uid))
      uid = _rand.nextInt(10000);
    _requests[uid] = completer;
    return uid;
  }
}

/**
 * Handles data for requests. Replies are expected to ensure the request
 * is completed.
 */
class Request {

  final SendPort _sp;

  /**
   * THe name of the command.
   */
  final String command;

  /**
   * Identifier for the request that will be expected by the requester.
   */
  final int uid;

  /**
   * The received [data] from the plugin or the loader.
   */
  final Map<dynamic, dynamic> data;

  Request(this._sp, this.uid, this.command, this.data);

  /**
   * Replies are expected to ensure data is sent back.
   */
  void reply(Map<dynamic, dynamic> info) {
    var wrapped = <String, dynamic>{
      'type': SendType.NORMAL,
      'uid': uid,
      'command': command,
      'data': info
    };
    _sp.send(wrapped);
  }
}

part of plugins.common;

class RequestManager {

  Map<int, Completer> _requests = {};
  final Random _rand = new Random();

  void complete(int uid, String command, Map<dynamic, dynamic> data) {
    var com = _requests[uid];
    if (com == null)
      throw new Exception("Attempt to complete an invalid request");
    com.complete(data);
    _requests.remove(uid);
  }

  int queue(Completer completer) {
    int uid = _rand.nextInt(10000);
    while (_requests.containsKey(uid))
      uid = _rand.nextInt(10000);
    _requests[uid] = completer;
    return uid;
  }
}

/**
 * Handles data for requests. Replies are expected to ensure the request
 * is completed.
 */
class Request {

  final SendPort _sp;

  /**
   * THe name of the command.
   */
  final String command;

  /**
   * Identifier for the request that will be expected by the requester.
   */
  final int uid;

  /**
   * The received [data] from the plugin or the loader.
   */
  final Map<dynamic, dynamic> data;

  Request(this._sp, this.uid, this.command, this.data);

  /**
   * Replies are expected to ensure data is sent back.
   */
  void reply(Map<dynamic, dynamic> info) {
    var wrapped = <String, dynamic>{
      'type': SendType.NORMAL,
      'uid': uid,
      'command': command,
      'data': info
    };
    _sp.send(wrapped);
  }
}

Remove the completer from the list

Remove the completer from the list


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

import 'package:args/args.dart';
import 'package:lsp_server/src/analysis_server.dart';
import 'package:lsp_server/src/channel.dart';

const _optionCandyDirectory = 'candy-path';

Future<void> main(List<String> arguments) async {
  stderr.write('Starting LSP…');

  final parser = ArgParser()..addOption(_optionCandyDirectory);
  final results = parser.parse(arguments);

  final candyDirectory = Directory(results[_optionCandyDirectory]);
  if (!candyDirectory.existsSync()) {
    exit(HttpStatus.notFound);
  }

  final channel = LspByteStreamServerChannel(stdin, stdout);
  final analysisServer = AnalysisServer(channel, candyDirectory);
  stderr.write('Started LSP.');
  await channel.closed;

  // Only shutdown the server and exit if the server is not already
  // handling the shutdown.
  if (!analysisServer.willExit) {
    await analysisServer.shutdown();
    exit(0);
  }
}

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

import 'package:args/args.dart';
import 'package:lsp_server/src/analysis_server.dart';
import 'package:lsp_server/src/channel.dart';

const _optionCandyDirectory = 'candy-path';

Future<void> main(List<String> arguments) async {
  stderr.write('Starting LSP…');

  final parser = ArgParser()..addOption(_optionCandyDirectory);
  final results = parser.parse(arguments);

  final corePath = results[_optionCandyDirectory];
  final coreDirectory = Directory(corePath);
  if (!coreDirectory.existsSync()) {
    stderr.write('Core library not found at $corePath.');
    exit(HttpStatus.notFound);
  }

  final channel = LspByteStreamServerChannel(stdin, stdout);
  final analysisServer = AnalysisServer(channel, coreDirectory);
  stderr.write('Started LSP.');
  await channel.closed;

  // Only shutdown the server and exit if the server is not already
  // handling the shutdown.
  if (!analysisServer.willExit) {
    await analysisServer.shutdown();
    exit(0);
  }
}

Improve debuggability if core package is not found


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

// Regression test for http://dartbug.com/23432

import 'package:expect/expect.dart';

class N {
  noSuchMethod(i) { print('x'); return 42; }
}

get NEVER => new DateTime.now().millisecondsSinceEpoch < 42;

main() {
  var c = 12345;
  if (NEVER) c = new N();
  var e;
  try {
    c..toString()..add(88);
  } catch (ex) {
    e = ex;
  }
  var s = e.toString();
  Expect.isTrue(s.contains('$c'), 'Text "$s" should contain "$c"');
}

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

// Regression test for http://dartbug.com/23432.  Test that the receiver of a
// NoSuchMethodError is correct on an intercepted method.  The bug (issue 23432)
// is that the interceptor is captured instead of the receiver.

import 'package:expect/expect.dart';

class N {
  noSuchMethod(i) { print('x'); return 42; }
}

@NoInline() @AssumeDynamic()
get NEVER => false;

main() {
  var c = 12345;
  if (NEVER) c = new N();
  var e;
  try {
    c..toString()..add(88);
  } catch (ex) {
    e = ex;
  }
  var s = e.toString();
  Expect.isTrue(s.contains('$c'), 'Text "$s" should contain "$c"');
}

Add test for Issue 23432

Add test for Issue 23432

BUG=
R=sigmund@google.com

Committed: https://code.google.com/p/dart/source/detail?r=45821

Review URL: https://codereview.chromium.org//1136383004

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@45824 260f80e4-7a28-3924-810f-c04153c831b5


import 'package:flutter/material.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:url_launcher/url_launcher.dart';

/*
Widget used to Linkify text and then ensure any invalid URLs are caught and
reported to user. This should be used in place of the Linkify widget.
 */

class LinkifyWithCatch extends StatelessWidget {
  final String text;
  final TextStyle style;
  final TextAlign textAlign;

  const LinkifyWithCatch(
      {Key key, @required this.text, this.style, this.textAlign})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Linkify(
      onOpen: (link) async {
        try {
          if (await canLaunch(link.url)) {
            await launch(link.url);
          } else {
            throw 'Could not launch $link';
          }
        } catch (e) {
          Scaffold.of(context).showSnackBar(SnackBar(
            content: Text('Could not open.'),
          ));
        }
      },
      options: LinkifyOptions(humanize: false),
      text: text,
      textAlign: textAlign,
      style: style,
    );
  }
}

import 'package:flutter/material.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:url_launcher/url_launcher.dart';

/*
Widget used to Linkify text and then ensure any invalid URLs are caught and
reported to user. This should be used in place of the Linkify widget.
 */

class LinkifyWithCatch extends StatelessWidget {
  final String text;
  final TextStyle style;
  final TextAlign textAlign;

  const LinkifyWithCatch(
      {Key key,
      @required this.text,
      this.style,
      this.textAlign = TextAlign.start})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Linkify(
      onOpen: (link) async {
        try {
          if (await canLaunch(link.url)) {
            await launch(link.url);
          } else {
            throw 'Could not launch $link';
          }
        } catch (e) {
          Scaffold.of(context).showSnackBar(SnackBar(
            content: Text('Could not open.'),
          ));
        }
      },
      options: LinkifyOptions(humanize: false),
      text: text,
      textAlign: textAlign,
      style: style,
    );
  }
}

Add default value to textAlign property

Add default value to textAlign property


part of stream_transformers;

/// Similar to `FlatMap`, but instead of including events from all spawned
/// streams, only includes the ones from the latest stream. Think of this
/// as stream switching.
///
/// **Example:**
///
///     var controller = new StreamController();
///     var latest = controller.stream.transform(new FlatMapLatest((value) => new Stream.fromIterable([value + 1]));
///
///     latest.listen(print);
///
///     controller.add(1);
///     controller.add(2); // Prints: 3
class FlatMapLatest<S, T> implements StreamTransformer<S, T> {
  final Mapper<S, Stream<T>> _convert;

  FlatMapLatest(Mapper<S, Stream<T>> convert) : _convert = convert;

  Stream<T> bind(Stream<S> stream) {
    var input = stream.asBroadcastStream(onCancel: (subscription) => subscription.cancel());

    return _bindStream(like: stream, onListen: (EventSink<T> sink) {
      var done = input.handleError((e) => e);
      return input
          .transform(new FlatMap((value) => _convert(value).transform(new TakeUntil(done))))
          .listen((value) => sink.add(value), onError: sink.addError, onDone: () => sink.close());
    });
  }
}

part of stream_transformers;

/// Similar to `FlatMap`, but instead of including events from all spawned
/// streams, only includes the ones from the latest stream. Think of this
/// as stream switching.
///
/// **Example:**
///
///     var controller = new StreamController();
///     var latest = controller.stream.transform(new FlatMapLatest((value) => new Stream.fromIterable([value + 1]));
///
///     latest.listen(print);
///
///     controller.add(1);
///     controller.add(2); // Prints: 3
class FlatMapLatest<S, T> implements StreamTransformer<S, T> {
  final Mapper<S, Stream<T>> _convert;

  FlatMapLatest(Mapper<S, Stream<T>> convert) : _convert = convert;

  Stream<T> bind(Stream<S> stream) {
    var input = stream.asBroadcastStream(onCancel: (subscription) => subscription.cancel());
    StreamSubscription doneSubscription;

    StreamSubscription onListen(EventSink<T> sink) {
      var done = new StreamController.broadcast(sync: true);
      doneSubscription = input.listen((value) => done.add(true), onError: (_) {}, onDone: () => done.close());

      return input
          .transform(new FlatMap((value) => _convert(value).transform(new TakeUntil(done.stream))))
          .listen((value) => sink.add(value), onError: sink.addError, onDone: () => sink.close());
    }

    return _bindStream(like: stream, onListen: onListen, onCancel: () => doneSubscription.cancel());
  }
}

Change how FlatMapLatest cancels previous subscriptions


// 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 'dart:isolate';

main(List<String> args, SendPort sendPort) {
  ReceivePort receivePort = new ReceivePort();
  sendPort.send(receivePort.sendPort);

  receivePort.listen((msg) {
    sendPort.send(_handle(msg));
  });
}

_handle(String msg) {
  return "ECHO: $msg";
}

// 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 'dart:convert';
import 'dart:isolate';

main(List<String> args, SendPort sendPort) {
  ReceivePort receivePort = new ReceivePort();
  sendPort.send(receivePort.sendPort);

  receivePort.listen((msg) {
    sendPort.send(_handle(msg));
  });
}

_handle(String msg) {
  // Unpack arguments

  var inArgs = JSON.decode(msg);

  String key = inArgs["key"];
  String value = inArgs["value"];

  return JSON.encode(map(key, value));
}

Map<String, List<String>> map(String k, String v) {
  return { k : [ v.length ] };
}

Replace compute target with a structure map function


import 'safenames.dart';
import 'utils.dart';
import 'winrt_method.dart';

abstract class WinRTPropertyProjection extends WinRTMethodProjection {
  WinRTPropertyProjection(super.method, super.vtableOffset);

  /// Strip off all underscores, even if double underscores
  String get exposedMethodName =>
      method.name.startsWith('get__') || method.name.startsWith('put__')
          ? safeIdentifierForString(method.name.substring(5).toCamelCase())
          : safeIdentifierForString(method.name.substring(4).toCamelCase());

  // WinRT properties always return an HRESULT
  @override
  String get nativePrototype => 'HRESULT Function($nativeParams)';

  // WinRT properties always return an HRESULT
  @override
  String get dartPrototype => 'int Function($dartParams)';
}

import 'safenames.dart';
import 'utils.dart';
import 'winrt_method.dart';

abstract class WinRTPropertyProjection extends WinRTMethodProjection {
  WinRTPropertyProjection(super.method, super.vtableOffset);

  /// Strip off all underscores, even if double underscores
  String get exposedMethodName =>
      method.name.startsWith('get__') || method.name.startsWith('put__')
          ? safeIdentifierForString(method.name.substring(5)).toCamelCase()
          : safeIdentifierForString(method.name.substring(4)).toCamelCase();

  // WinRT properties always return an HRESULT
  @override
  String get nativePrototype => 'HRESULT Function($nativeParams)';

  // WinRT properties always return an HRESULT
  @override
  String get dartPrototype => 'int Function($dartParams)';
}

Call .toCamelCase() after safeIdentifierForString for consistency


// 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("co19_test_config");

#import('dart:io');
#import('../../tools/testing/dart/test_suite.dart');

class Co19TestSuite extends StandardTestSuite {
  RegExp _testRegExp = new RegExp(r"t[0-9]{2}.dart$");

  Co19TestSuite(Map configuration)
      : super(configuration,
              "co19",
              new Path("tests/co19/src"),
              ["tests/co19/co19-compiler.status",
               "tests/co19/co19-runtime.status",
               "tests/co19/co19-dart2dart.status",
               "tests/co19/co19-dart2js.status"]);

  bool isTestFile(String filename) => _testRegExp.hasMatch(filename);
  bool get listRecursively => true;
}

// 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("co19_test_config");

#import('dart:io');
#import('../../tools/testing/dart/test_suite.dart');

class Co19TestSuite extends StandardTestSuite {
  RegExp _testRegExp = new RegExp(r"t[0-9]{2}.dart$");

  Co19TestSuite(Map configuration)
      : super(configuration,
              "co19",
              new Path("tests/co19/src"),
              [],
              ["tests/co19/co19-compiler.status",
               "tests/co19/co19-runtime.status",
               "tests/co19/co19-dart2dart.status",
               "tests/co19/co19-dart2js.status"]);

  bool isTestFile(String filename) => _testRegExp.hasMatch(filename);
  bool get listRecursively => true;
}

Fix up co19 tests with test.dart change.
Review URL: https://codereview.chromium.org//11788008

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@16672 260f80e4-7a28-3924-810f-c04153c831b5


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

#library("co19_test_config");

#import("../../tools/testing/dart/test_suite.dart");

class Co19TestSuite extends StandardTestSuite {
  RegExp _testRegExp = const RegExp(@"t[0-9]{2}.dart$");

  Co19TestSuite(Map configuration)
      : super(configuration,
              "co19",
              "tests/co19/src",
              ["tests/co19/co19-compiler.status",
               "tests/co19/co19-runtime.status",
               "tests/co19/co19-frog.status"]);

  bool isTestFile(String filename) => _testRegExp.hasMatch(filename);
  bool listRecursively() => true;
  bool complexStatusMatching() => true;
}

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

#library("co19_test_config");

#import("dart:io");
#import("../../tools/testing/dart/test_suite.dart");

class Co19TestSuite extends StandardTestSuite {
  RegExp _testRegExp = const RegExp(@"t[0-9]{2}.dart$");

  Co19TestSuite(Map configuration)
      : super(configuration,
              "co19",
              "tests/co19/src",
              ["tests/co19/co19-compiler.status",
               "tests/co19/co19-runtime.status",
               "tests/co19/co19-frog.status"]);

  // A Dart checkout may omit the check out of the co19 tests.
  void forEachTest(Function onTest, Map testCache, String globalTempDir(),
                   [Function onDone = null]) {
    Directory testDirectory =
        new Directory(TestUtils.dartDir() + '/tests/co19/src');
    if (testDirectory.existsSync()) {
      super.forEachTest(onTest, testCache, globalTempDir, onDone);
    } else {
      if (onDone != null) onDone();
    }
  }

  bool isTestFile(String filename) => _testRegExp.hasMatch(filename);
  bool listRecursively() => true;
  bool complexStatusMatching() => true;
}

Allow test.dart to handle the co19 test suite if it is not checked out.

BUG=
TEST=tools/test.dart co19

Review URL: https://chromiumcodereview.appspot.com//9315052

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@3843 260f80e4-7a28-3924-810f-c04153c831b5


import 'package:flutter/material.dart';
import 'package:sqflite_example/main.dart' as example;

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  example.main();
}

import 'main_ffi.dart' as main_ffi;

void main() {
  main_ffi.main();
}

Use sqflite_common_ffi for web in example app


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

import 'package:polymer/polymer.dart';

import '../common/spark_widget.dart';

// Ported from Polymer Javascript to Dart code.

@CustomTag("spark-menu-item")
class SparkMenuItem extends SparkWidget {
  /// URL image for the icon associated with this menu item.
  @published String src = "";
  /// Size of the icon.
  @published String iconsize = "24";
  /// Specifies the label for the menu item.
  @published String label = "";

  @observable bool isHovered = false;

  SparkMenuItem.created(): super.created() {
    // BUG: Use mouse events instead of :hover because Chrome fails to remove
    // :hover from an element after it's clicked and programmatically moved from
    // under the mouse, as is the case with our auto-closing spark-menu.
    bindCssClass(this, 'highlighted', this, 'isHovered');
    onMouseOver.listen((_) => isHovered = true);
    onMouseOut.listen((_) => isHovered = false);
  }
}

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

import 'package:polymer/polymer.dart';

import '../common/spark_widget.dart';

// Ported from Polymer Javascript to Dart code.

@CustomTag("spark-menu-item")
class SparkMenuItem extends SparkWidget {
  /// URL image for the icon associated with this menu item.
  @published String src = "";
  /// Size of the icon.
  @published String iconsize = "24";
  /// Specifies the label for the menu item.
  @published String label = "";

  @observable bool isHovered = false;

  SparkMenuItem.created(): super.created() {
    // BUG: Use mouse events instead of :hover because Chrome fails to remove
    // :hover from an element after it's clicked and programmatically moved from
    // under the mouse, as is the case with our auto-closing spark-menu.
    if (IS_DART2JS) {
      // TODO: bindCssClass() doesn't work after dart2js. Keeping it only
      // because widgets are a Polymer testing ground - investigate/file bug.
      onMouseOver.listen((_) { classes.add('highlighted'); });
      onMouseOut.listen((_) { classes.remove('highlighted'); });
    } else {
      bindCssClass(this, 'highlighted', this, 'isHovered');
      onMouseOver.listen((_) => isHovered = true);
      onMouseOut.listen((_) => isHovered = false);
    }
  }
}

Fix menu selection not working after dart2js


// Copyright (c) 2015, Brian G. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

/// The dartbase_server library.
part of dartbase_server;

final GameSupervisor _gameSuper = new GameSupervisor._singleton();

class GameSupervisor {
  List<Game> _games;
  final int MAX_GAMES = 2;

  GameSupervisor._singleton() {
    log("Constructing GameSupervisor");
    _games = [];
  }

  static int newGame(Map players){
    if(_gameSuper._games.length == 0){
      log("Creating new game with player data: " + players.toString());
      Game game = new Game();
      //TODO add players
      _gameSuper._games.add(game);
    }
    log("Returning gameid: 1");

    return 1;
  }
}

class WebGame {
  int gameid;
  Game game;
  final DateTime created = new DateTime.now();
  DateTime modified = new DateTime.now();

  WebGame(this.gameid, this.game);

  Map getGameData(){
    Map gameDataMap = {};

    return gameDataMap;
  }
}

// Copyright (c) 2015, Brian G. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

/// The dartbase_server library.
part of dartbase_server;

final GameSupervisor _gameSuper = new GameSupervisor._singleton();

class GameSupervisor {
  List<WebGame> _games;
  final int MAX_GAMES = 2;
  int currentid = 0;

  GameSupervisor._singleton() {
    log("Constructing GameSupervisor");
    _games = [];
  }

  static int newGame(Map players){
    if(_gameSuper._games.length < MAX_GAMES){
      log("Creating new game with player data: " + players.toString());
      currentid++;
      WebGame webGame = new WebGame();
      webGame.game = new Game();
      webGame.gameid = currentid;
      //TODO add players
      _gameSuper._games.add(game);
      log("Returning gameid: ${currentid}");

      return currentid;

    } else {
      log("Max simultaneous games already reached.");
      throw new app.ErrorResponse(400, {"error": "Max Games Reached"});
    }

  }
}

class WebGame {
  int gameid;
  Game game;
  final DateTime created = new DateTime.now();
  DateTime modified = new DateTime.now();

  WebGame(this.gameid, this.game);

  Map getGameData(){
    Map gameDataMap = {};

    return gameDataMap;
  }
}

Create webgame wrappers and error response