diff --git a/engine/src/flutter/sky/BUILD.gn b/engine/src/flutter/sky/BUILD.gn new file mode 100644 index 0000000000..ca79233b0e --- /dev/null +++ b/engine/src/flutter/sky/BUILD.gn @@ -0,0 +1,36 @@ +# Copyright 2014 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. + +group("sky") { + testonly = true + + deps = [ + "//sky/engine/platform:platform_unittests", + "//sky/engine/wtf:unittests", + "//sky/sdk/example", + "//sky/tools/imagediff", + "//sky/tools/packager($host_toolchain)", + ":sky_dev", + ] + + if (!is_android) { + deps += [ "//third_party/mesa:osmesa" ] + } +} + +group("sky_dev") { + testonly = true + + deps = [ + "//sky/sdk", + ] + + if (is_android) { + deps += [ "//sky/services/activity" ] + } + + if (is_linux) { + deps += [ "//sky/shell" ] + } +} diff --git a/engine/src/flutter/sky/HACKING.md b/engine/src/flutter/sky/HACKING.md new file mode 100644 index 0000000000..20c8c06262 --- /dev/null +++ b/engine/src/flutter/sky/HACKING.md @@ -0,0 +1,85 @@ +Hacking on Sky +============== + +Building +-------- + +* Follow the setup & build instructions for [Mojo](https://github.com/domokit/mojo) + +The build directory will be `out/Debug` for Linux debug builds, and +`out/Release` for Linux release builds. For Android builds, prefix +`android_`, as in, `android_Debug`. + +For Sky on iOS, you can try following these [experimental instructions](https://docs.google.com/document/d/1qm8Vvyz8Mngw6EsSg4FELQ7FOegjBJ5Itg9OBJGN5JM/edit#heading=h.ikz9bdwswdct). + +Running applications +-------------------- + +To run an application on your device, run: + +* `mojo/devtools/common/mojo_shell --sky [url] --android` + +When the shell is running, `mojo/devtools/common/debugger` allows you to +collect traces, symbolize stack crashes and attach gdb if needed. Refer to the +[documentation](https://github.com/domokit/mojo#debugging-tracing-profiling) +for the details. + +Running tests +------------- + +Tests are only supported on Linux currently. + +* ``sky/tools/test_sky --debug`` + * This runs the tests against ``//out/Debug``. If you want to run against + ``//out/Release``, omit the ``--debug`` flag. + +Running tests manually +---------------------- + +Running tests manually lets you more quickly iterate during +development; rather than having to compile and rerun all the tests, +then trawl through the build output to find the current results, you +can just run the test you're working on and reload it over and over, +seeing the output right there on your console. + +* ``sky/tools/skygo/linux64/sky_server -v -p 8000 out/Debug out/Debug/gen/dart-pkg/packages`` +* ``out/Debug/mojo_shell --args-for="mojo:native_viewport_service --use-headless-config --use-osmesa" --args-for"=mojo:sky_viewer --testing" --content-handlers=application/dart,mojo:sky_viewer --url-mappings=mojo:window_manager=mojo:sky_tester,mojo:surfaces_service=mojo:fake_surfaces_service mojo:window_manager`` +* The ``sky_tester`` should print ``#READY`` when ready +* Type the URL you wish to run, for example ``http://127.0.0.1:8000/sky/tests/widgets/dialog.dart``, and press the enter key +* The harness should print the results of the test. You can then type another URL. + +Writing tests +------------- + +We recommend using the [Dart +``test``](https://pub.dartlang.org/packages/test) testing framework. +See [``sky/tests/raw/color_bounds.dart``](tests/raw/color_bounds.dart) +for an example. + +Debugging Sky +------------- + +This document aims to explain how to debug Sky itself. + +### C++ + +Launch a debug Sky build on Android as usual: + +``` +mojo/devtools/common/mojo_shell --sky [url] --android` +``` + +and use the debugger to attach gdb: +``` +mojo/devtools/common/debugger gdb attach +``` + +Once gdb has loaded, hit `c` to continue the execution. When your app crashes, +it will pause in the debugger. At that point, regular gdb commands will work: +`n` to step over the current statement, `s` to step into the current statement, +`f` to step out of the current block, `c` to continue until the next breakpoint +or exception. + +### Dart + +Use Observatory. diff --git a/engine/src/flutter/sky/README.md b/engine/src/flutter/sky/README.md new file mode 100644 index 0000000000..3a63fcd806 --- /dev/null +++ b/engine/src/flutter/sky/README.md @@ -0,0 +1,14 @@ +Sky +=== + +For information about using our latest stable release of Sky, please +see the [Sky SDK](https://github.com/domokit/sky_sdk/) project page. + +For more current information about the bleeding edge of the Sky +framework, see [the sdk/ directory](sdk/lib/). + +For details about the internals of Sky's engine, see [the engine/ +directory](engine/). + +For information about contributing to Sky, please see +[HACKING.md](HACKING.md). diff --git a/engine/src/flutter/sky/tools/android_library_cacher.py b/engine/src/flutter/sky/tools/android_library_cacher.py new file mode 100755 index 0000000000..a0813979ee --- /dev/null +++ b/engine/src/flutter/sky/tools/android_library_cacher.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# 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 argparse +import logging +import os +import re +import skypy.paths +import subprocess +import sys + +SRC_ROOT = skypy.paths.Paths('ignored').src_root +ADB_PATH = os.path.join(SRC_ROOT, + 'third_party/android_tools/sdk/platform-tools/adb') + + +# TODO(eseidel): This should be shared with adb_gdb +def main(): + logging.basicConfig(level=logging.INFO) + parser = argparse.ArgumentParser( + description='Pull all libraries used by a pid on android into a cache.') + parser.add_argument('cache_root', type=str) + parser.add_argument('pid', type=int) + args = parser.parse_args() + + if not os.path.exists(args.cache_root): + os.makedirs(args.cache_root) + + subprocess.check_call([ADB_PATH, 'root']) + + # TODO(eseidel): Check the build.props, or find some way to avoid + # re-pulling every library every time. adb_gdb has code to do this + # but doesn't seem to notice when the set of needed libraries changed. + + library_regexp = re.compile(r'(?P/system/.*\.so)') + cat_maps_cmd = [ADB_PATH, 'shell', 'cat', '/proc/%s/maps' % args.pid] + maps_lines = subprocess.check_output(cat_maps_cmd).strip().split('\n') + # adb shell doesn't return the return code from the shell? + if not maps_lines or 'No such file or directory' in maps_lines[0]: + print 'Failed to get maps for pid %s on device.' % args.pid + sys.exit(1) + + def library_from_line(line): + result = library_regexp.search(line) + if not result: + return None + return result.group('library_path') + + dev_null = open(os.devnull, 'w') # Leaking. + to_pull = set(filter(None, map(library_from_line, maps_lines))) + to_pull.add('/system/bin/linker') # Unclear why but adb_gdb pulls this too. + for library_path in sorted(to_pull): + # Not using os.path.join since library_path is absolute. + dest_file = os.path.normpath("%s/%s" % (args.cache_root, library_path)) + dest_dir = os.path.dirname(dest_file) + if not os.path.exists(dest_dir): + os.makedirs(dest_dir) + if os.path.exists(dest_file): + continue + print '%s -> %s' % (library_path, dest_file) + pull_cmd = [ADB_PATH, 'pull', library_path, dest_file] + subprocess.check_call(pull_cmd, stderr=dev_null) + + +if __name__ == '__main__': + main() diff --git a/engine/src/flutter/sky/tools/big_red_button.py b/engine/src/flutter/sky/tools/big_red_button.py new file mode 100755 index 0000000000..1c3d4c9c93 --- /dev/null +++ b/engine/src/flutter/sky/tools/big_red_button.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python +# 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. + +# Prepare release script. +# +# 1) Bump versions using sky/tools/roll_versions.py +# 2) Add any additional information to touched CHANGELOG.md files. +# 3) Add any release_notes/version.txt files for updated apks. +# 4) Make a commit, upload it, land it. +# 5) Run this script. +# 6) Publish updated apks using sky/tools/publish_apk.py + +import argparse +import os +import subprocess +import sys +import distutils.util + + +DEFAULT_MOJO_ROOT = '/src/mojo/src' +DEFAULT_SKY_SDK_ROOT = '/src/sky_sdk' +DEFAULT_DEMO_SITE_ROOT = '/src/domokit.github.io' +CONFIRM_MESSAGE = """This tool is destructive and will revert your current branch to +origin/master among other things. Are you sure you wish to continue?""" +DRY_RUN = False + + +def run(cwd, args): + print 'RUNNING:', ' '.join(args), 'IN:', cwd + if DRY_RUN: + return + subprocess.check_call(args, cwd=cwd) + + +def confirm(prompt): + user_input = raw_input("%s (y/N) " % prompt) + try: + return distutils.util.strtobool(user_input) == 1 + except ValueError: + return False + + +def publish_packages(pub_path, packages_root): + for package in os.listdir(packages_root): + package_path = os.path.join(packages_root, package) + if not os.path.isdir(package_path): + continue + run(package_path, [pub_path, 'publish', '--force']) + + +def main(): + parser = argparse.ArgumentParser(description='Deploy!') + parser.add_argument('--mojo-root', help='Path to mojo/src', + default=DEFAULT_MOJO_ROOT) + parser.add_argument('--sky-sdk-root', help='Path to sky_sdk', + default=DEFAULT_SKY_SDK_ROOT) + parser.add_argument('--demo-site-root', help='Path to domokit.github.io', + default=DEFAULT_DEMO_SITE_ROOT) + parser.add_argument('--dry-run', action='store_true', default=False, + help='Just print commands w/o executing.') + parser.add_argument('--no-pub-publish', dest='publish', + action='store_false', default=True, help='Skip pub publish step.') + args = parser.parse_args() + + global DRY_RUN + DRY_RUN = args.dry_run + + if not args.dry_run and not confirm(CONFIRM_MESSAGE): + print "Aborted." + return 1 + + mojo_root = os.path.abspath(os.path.expanduser(args.mojo_root)) + sky_sdk_root = os.path.abspath(os.path.expanduser(args.sky_sdk_root)) + demo_site_root = os.path.abspath(os.path.expanduser(args.demo_site_root)) + + # Derived paths: + dart_sdk_root = os.path.join(mojo_root, 'third_party/dart-sdk/dart-sdk') + pub_path = os.path.join(dart_sdk_root, 'bin/pub') + packages_root = os.path.join(sky_sdk_root, 'packages') + + run(mojo_root, ['git', 'pull', '--rebase']) + run(mojo_root, ['gclient', 'sync']) + run(mojo_root, ['mojo/tools/mojob.py', 'gn', '--android', '--release']) + run(mojo_root, ['mojo/tools/mojob.py', 'build', '--android', '--release']) + # Run tests? + + run(sky_sdk_root, ['git', 'fetch']) + run(sky_sdk_root, ['git', 'reset', '--hard', 'origin/master']) + run(mojo_root, [ + 'sky/tools/deploy_sdk.py', + '--non-interactive', + '--commit', + sky_sdk_root + ]) + # tag for version? + + run(demo_site_root, ['git', 'fetch']) + run(demo_site_root, ['git', 'reset', '--hard', 'origin/master']) + run(mojo_root, ['mojo/tools/deploy_domokit_site.py', demo_site_root]) + # tag for version? + + if args.publish: + publish_packages(pub_path, packages_root) + + run(sky_sdk_root, ['git', 'push']) + run(demo_site_root, ['git', 'push']) + + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/engine/src/flutter/sky/tools/deploy_sdk.py b/engine/src/flutter/sky/tools/deploy_sdk.py new file mode 100755 index 0000000000..dcedc66d1a --- /dev/null +++ b/engine/src/flutter/sky/tools/deploy_sdk.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python +# 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 argparse +from datetime import datetime +import logging +import os +import shutil +import subprocess +import sys + +# Generates the sky_sdk from the template at sky/sdk. + +SKY_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) +SKY_DIR = os.path.dirname(SKY_TOOLS_DIR) +SRC_ROOT = os.path.dirname(SKY_DIR) + +DEFAULT_REL_BUILD_DIR = os.path.join('out', 'android_Release') + +def git_revision(): + return subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip() + + +def ensure_dir_exists(path): + if not os.path.exists(path): + os.makedirs(path) + + +def copy(from_root, to_root, filter_func=None): + assert os.path.exists(from_root), "%s does not exist!" % from_root + if os.path.isfile(from_root): + ensure_dir_exists(os.path.dirname(to_root)) + shutil.copy(from_root, to_root) + return + + ensure_dir_exists(to_root) + + for root, dirs, files in os.walk(from_root): + # filter_func expects paths not names, so wrap it to make them absolute. + wrapped_filter = None + if filter_func: + wrapped_filter = lambda name: filter_func(os.path.join(root, name)) + + for name in filter(wrapped_filter, files): + from_path = os.path.join(root, name) + root_rel_path = os.path.relpath(from_path, from_root) + to_path = os.path.join(to_root, root_rel_path) + to_dir = os.path.dirname(to_path) + if not os.path.exists(to_dir): + os.makedirs(to_dir) + shutil.copy(from_path, to_path) + + dirs[:] = filter(wrapped_filter, dirs) + + +def confirm(prompt): + response = raw_input('%s [N]|y: ' % prompt) + return response and response.lower() == 'y' + + +def delete_all_non_hidden_files_in_directory(root, non_interactive=False): + to_delete = [os.path.join(root, p) + for p in os.listdir(root) if not p.startswith('.')] + if not to_delete: + return + if not non_interactive: + prompt = 'This will delete everything in %s:\n%s\nAre you sure?' % ( + root, '\n'.join(to_delete)) + if not confirm(prompt): + print 'User aborted.' + sys.exit(2) + + for path in to_delete: + if os.path.isdir(path) and not os.path.islink(path): + shutil.rmtree(path) + else: + os.remove(path) + + +def main(): + logging.basicConfig(level=logging.WARN) + parser = argparse.ArgumentParser(description='Deploy a new sky_sdk.') + parser.add_argument('sdk_root', type=str) + parser.add_argument('--build-dir', action='store', type=str, + default=os.path.join(SRC_ROOT, DEFAULT_REL_BUILD_DIR)) + parser.add_argument('--non-interactive', action='store_true') + parser.add_argument('--commit', action='store_true') + args = parser.parse_args() + + build_dir = os.path.abspath(args.build_dir) + sdk_root = os.path.abspath(args.sdk_root) + + print 'Building SDK from %s into %s' % (build_dir, sdk_root) + start_time = datetime.now() + + should_commit = args.commit + + def sdk_path(rel_path): + return os.path.join(sdk_root, rel_path) + + def src_path(rel_path): + return os.path.join(SRC_ROOT, rel_path) + + ensure_dir_exists(sdk_root) + # Manually clear sdk_root above to avoid deleting dot-files. + delete_all_non_hidden_files_in_directory(sdk_root, args.non_interactive) + + copy(src_path('sky/sdk/README.md'), sdk_root) + + ensure_dir_exists(sdk_path('packages')) + subprocess.check_call([ + 'mojo/tools/prepare_pub_packages.py', + '--out-dir', sdk_path('packages'), + 'out' + ]) + + with open(sdk_path('LICENSES.sky'), 'w') as license_file: + subprocess.check_call([src_path('tools/licenses.py'), 'credits'], + stdout=license_file) + + if should_commit: + # Kinda a hack to make a prettier build dir for the commit: + script_path = os.path.relpath(os.path.abspath(__file__), SRC_ROOT) + rel_build_dir = os.path.relpath(build_dir, SRC_ROOT) + revision = git_revision() + commit_url = "https://github.com/domokit/mojo/commit/%s" % revision + pattern = """Autogenerated from %s +Using %s and build output from %s. +""" + commit_message = pattern % (commit_url, script_path, rel_build_dir) + subprocess.check_call(['git', 'add', '.'], cwd=sdk_root) + subprocess.check_call([ + 'git', 'commit', + '-m', commit_message + ], cwd=sdk_root) + + time_delta = datetime.now() - start_time + print 'SDK built at %s in %ss' % (sdk_root, time_delta.total_seconds()) + + +if __name__ == '__main__': + main() diff --git a/engine/src/flutter/sky/tools/imagediff/BUILD.gn b/engine/src/flutter/sky/tools/imagediff/BUILD.gn new file mode 100644 index 0000000000..d63fd5cb42 --- /dev/null +++ b/engine/src/flutter/sky/tools/imagediff/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright 2014 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. + +executable("imagediff") { + output_name = "image_diff" # Different than dir nam for historical reasons. + sources = [ + "image_diff.cc", + "image_diff_png.h", + "image_diff_png.cc", + ] + + configs += [ "//build/config/compiler:wexit_time_destructors" ] + + deps = [ + "//base", + "//build/config/sanitizers:deps", + "//third_party/libpng", + "//third_party/zlib", + ] +} diff --git a/engine/src/flutter/sky/tools/imagediff/image_diff.cc b/engine/src/flutter/sky/tools/imagediff/image_diff.cc new file mode 100644 index 0000000000..4aed16adc6 --- /dev/null +++ b/engine/src/flutter/sky/tools/imagediff/image_diff.cc @@ -0,0 +1,450 @@ +// Copyright (c) 2011 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. + +// This file input format is based loosely on +// Tools/DumpRenderTree/ImageDiff.m + +// The exact format of this tool's output to stdout is important, to match +// what the run-webkit-tests script expects. + +#include +#include +#include +#include + +#include "base/basictypes.h" +#include "base/command_line.h" +#include "base/containers/hash_tables.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/memory/scoped_ptr.h" +#include "base/numerics/safe_conversions.h" +#include "base/process/memory.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "sky/tools/imagediff/image_diff_png.h" + +#if defined(OS_WIN) +#include "windows.h" +#endif + +// Causes the app to remain open, waiting for pairs of filenames on stdin. +// The caller is then responsible for terminating this app. +static const char kOptionPollStdin[] = "use-stdin"; +// Causes the app to additionally calculate a diff of the color histograms +// (which is resistant to shifts in layout). +static const char kOptionCompareHistograms[] = "histogram"; +// Causes the app to output an image that visualizes the difference. +static const char kOptionGenerateDiff[] = "diff"; + +// Return codes used by this utility. +static const int kStatusSame = 0; +static const int kStatusDifferent = 1; +static const int kStatusError = 2; + +// Color codes. +static const uint32 RGBA_RED = 0x000000ff; +static const uint32 RGBA_ALPHA = 0xff000000; + +class Image { + public: + Image() : w_(0), h_(0) { + } + + Image(const Image& image) + : w_(image.w_), + h_(image.h_), + data_(image.data_) { + } + + bool has_image() const { + return w_ > 0 && h_ > 0; + } + + int w() const { + return w_; + } + + int h() const { + return h_; + } + + const unsigned char* data() const { + return &data_.front(); + } + + // Creates the image from stdin with the given data length. On success, it + // will return true. On failure, no other methods should be accessed. + bool CreateFromStdin(size_t byte_length) { + if (byte_length == 0) + return false; + + scoped_ptr source(new unsigned char[byte_length]); + if (fread(source.get(), 1, byte_length, stdin) != byte_length) + return false; + + if (!image_diff_png::DecodePNG(source.get(), byte_length, + &data_, &w_, &h_)) { + Clear(); + return false; + } + return true; + } + + // Creates the image from the given filename on disk, and returns true on + // success. + bool CreateFromFilename(const base::FilePath& path) { + FILE* f = base::OpenFile(path, "rb"); + if (!f) + return false; + + std::vector compressed; + const int buf_size = 1024; + unsigned char buf[buf_size]; + size_t num_read = 0; + while ((num_read = fread(buf, 1, buf_size, f)) > 0) { + compressed.insert(compressed.end(), buf, buf + num_read); + } + + base::CloseFile(f); + + if (!image_diff_png::DecodePNG(&compressed[0], compressed.size(), + &data_, &w_, &h_)) { + Clear(); + return false; + } + return true; + } + + void Clear() { + w_ = h_ = 0; + data_.clear(); + } + + // Returns the RGBA value of the pixel at the given location + uint32 pixel_at(int x, int y) const { + DCHECK(x >= 0 && x < w_); + DCHECK(y >= 0 && y < h_); + return *reinterpret_cast(&(data_[(y * w_ + x) * 4])); + } + + void set_pixel_at(int x, int y, uint32 color) const { + DCHECK(x >= 0 && x < w_); + DCHECK(y >= 0 && y < h_); + void* addr = &const_cast(&data_.front())[(y * w_ + x) * 4]; + *reinterpret_cast(addr) = color; + } + + private: + // pixel dimensions of the image + int w_, h_; + + std::vector data_; +}; + +float PercentageDifferent(const Image& baseline, const Image& actual) { + int w = std::min(baseline.w(), actual.w()); + int h = std::min(baseline.h(), actual.h()); + + // Compute pixels different in the overlap. + int pixels_different = 0; + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + if (baseline.pixel_at(x, y) != actual.pixel_at(x, y)) + pixels_different++; + } + } + + // Count pixels that are a difference in size as also being different. + int max_w = std::max(baseline.w(), actual.w()); + int max_h = std::max(baseline.h(), actual.h()); + // These pixels are off the right side, not including the lower right corner. + pixels_different += (max_w - w) * h; + // These pixels are along the bottom, including the lower right corner. + pixels_different += (max_h - h) * max_w; + + // Like the WebKit ImageDiff tool, we define percentage different in terms + // of the size of the 'actual' bitmap. + float total_pixels = static_cast(actual.w()) * + static_cast(actual.h()); + if (total_pixels == 0) { + // When the bitmap is empty, they are 100% different. + return 100.0f; + } + return 100.0f * pixels_different / total_pixels; +} + +typedef base::hash_map RgbaToCountMap; + +float HistogramPercentageDifferent(const Image& baseline, const Image& actual) { + // TODO(johnme): Consider using a joint histogram instead, as described in + // "Comparing Images Using Joint Histograms" by Pass & Zabih + // http://www.cs.cornell.edu/~rdz/papers/pz-jms99.pdf + + int w = std::min(baseline.w(), actual.w()); + int h = std::min(baseline.h(), actual.h()); + + // Count occurences of each RGBA pixel value of baseline in the overlap. + RgbaToCountMap baseline_histogram; + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + // hash_map operator[] inserts a 0 (default constructor) if key not found. + baseline_histogram[baseline.pixel_at(x, y)]++; + } + } + + // Compute pixels different in the histogram of the overlap. + int pixels_different = 0; + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + uint32 actual_rgba = actual.pixel_at(x, y); + RgbaToCountMap::iterator it = baseline_histogram.find(actual_rgba); + if (it != baseline_histogram.end() && it->second > 0) + it->second--; + else + pixels_different++; + } + } + + // Count pixels that are a difference in size as also being different. + int max_w = std::max(baseline.w(), actual.w()); + int max_h = std::max(baseline.h(), actual.h()); + // These pixels are off the right side, not including the lower right corner. + pixels_different += (max_w - w) * h; + // These pixels are along the bottom, including the lower right corner. + pixels_different += (max_h - h) * max_w; + + // Like the WebKit ImageDiff tool, we define percentage different in terms + // of the size of the 'actual' bitmap. + float total_pixels = static_cast(actual.w()) * + static_cast(actual.h()); + if (total_pixels == 0) { + // When the bitmap is empty, they are 100% different. + return 100.0f; + } + return 100.0f * pixels_different / total_pixels; +} + +void PrintHelp() { + fprintf(stderr, + "Usage:\n" + " image_diff [--histogram] \n" + " Compares two files on disk, returning 0 when they are the same;\n" + " passing \"--histogram\" additionally calculates a diff of the\n" + " RGBA value histograms (which is resistant to shifts in layout)\n" + " image_diff --use-stdin\n" + " Stays open reading pairs of filenames from stdin, comparing them,\n" + " and sending 0 to stdout when they are the same\n" + " image_diff --diff \n" + " Compares two files on disk, outputs an image that visualizes the\n" + " difference to \n"); + /* For unfinished webkit-like-mode (see below) + "\n" + " image_diff -s\n" + " Reads stream input from stdin, should be EXACTLY of the format\n" + " \"Content-length: Content-length: ...\n" + " it will take as many file pairs as given, and will compare them as\n" + " (cmp_file, reference_file) pairs\n"); + */ +} + +int CompareImages(const base::FilePath& file1, + const base::FilePath& file2, + bool compare_histograms) { + Image actual_image; + Image baseline_image; + + if (!actual_image.CreateFromFilename(file1)) { + fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n", + file1.value().c_str()); + return kStatusError; + } + if (!baseline_image.CreateFromFilename(file2)) { + fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n", + file2.value().c_str()); + return kStatusError; + } + + if (compare_histograms) { + float percent = HistogramPercentageDifferent(actual_image, baseline_image); + const char* passed = percent > 0.0 ? "failed" : "passed"; + printf("histogram diff: %01.2f%% %s\n", percent, passed); + } + + const char* diff_name = compare_histograms ? "exact diff" : "diff"; + float percent = PercentageDifferent(actual_image, baseline_image); + const char* passed = percent > 0.0 ? "failed" : "passed"; + printf("%s: %01.2f%% %s\n", diff_name, percent, passed); + if (percent > 0.0) { + // failure: The WebKit version also writes the difference image to + // stdout, which seems excessive for our needs. + return kStatusDifferent; + } + // success + return kStatusSame; + +/* Untested mode that acts like WebKit's image comparator. I wrote this but + decided it's too complicated. We may use it in the future if it looks useful + + char buffer[2048]; + while (fgets(buffer, sizeof(buffer), stdin)) { + + if (strncmp("Content-length: ", buffer, 16) == 0) { + char* context; + strtok_s(buffer, " ", &context); + int image_size = strtol(strtok_s(NULL, " ", &context), NULL, 10); + + bool success = false; + if (image_size > 0 && actual_image.has_image() == 0) { + if (!actual_image.CreateFromStdin(image_size)) { + fputs("Error, input image can't be decoded.\n", stderr); + return 1; + } + } else if (image_size > 0 && baseline_image.has_image() == 0) { + if (!baseline_image.CreateFromStdin(image_size)) { + fputs("Error, baseline image can't be decoded.\n", stderr); + return 1; + } + } else { + fputs("Error, image size must be specified.\n", stderr); + return 1; + } + } + + if (actual_image.has_image() && baseline_image.has_image()) { + float percent = PercentageDifferent(actual_image, baseline_image); + if (percent > 0.0) { + // failure: The WebKit version also writes the difference image to + // stdout, which seems excessive for our needs. + printf("diff: %01.2f%% failed\n", percent); + } else { + // success + printf("diff: %01.2f%% passed\n", percent); + } + actual_image.Clear(); + baseline_image.Clear(); + } + + fflush(stdout); + } +*/ +} + +bool CreateImageDiff(const Image& image1, const Image& image2, Image* out) { + int w = std::min(image1.w(), image2.w()); + int h = std::min(image1.h(), image2.h()); + *out = Image(image1); + bool same = (image1.w() == image2.w()) && (image1.h() == image2.h()); + + // TODO(estade): do something with the extra pixels if the image sizes + // are different. + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + uint32 base_pixel = image1.pixel_at(x, y); + if (base_pixel != image2.pixel_at(x, y)) { + // Set differing pixels red. + out->set_pixel_at(x, y, RGBA_RED | RGBA_ALPHA); + same = false; + } else { + // Set same pixels as faded. + uint32 alpha = base_pixel & RGBA_ALPHA; + uint32 new_pixel = base_pixel - ((alpha / 2) & RGBA_ALPHA); + out->set_pixel_at(x, y, new_pixel); + } + } + } + + return same; +} + +int DiffImages(const base::FilePath& file1, const base::FilePath& file2, + const base::FilePath& out_file) { + Image actual_image; + Image baseline_image; + + if (!actual_image.CreateFromFilename(file1)) { + fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n", + file1.value().c_str()); + return kStatusError; + } + if (!baseline_image.CreateFromFilename(file2)) { + fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n", + file2.value().c_str()); + return kStatusError; + } + + Image diff_image; + bool same = CreateImageDiff(baseline_image, actual_image, &diff_image); + if (same) + return kStatusSame; + + std::vector png_encoding; + image_diff_png::EncodeRGBAPNG( + diff_image.data(), diff_image.w(), diff_image.h(), + diff_image.w() * 4, &png_encoding); + if (base::WriteFile(out_file, + reinterpret_cast(&png_encoding.front()), + base::checked_cast(png_encoding.size())) < 0) + return kStatusError; + + return kStatusDifferent; +} + +// It isn't strictly correct to only support ASCII paths, but this +// program reads paths on stdin and the program that spawns it outputs +// paths as non-wide strings anyway. +base::FilePath FilePathFromASCII(const std::string& str) { +#if defined(OS_WIN) + return base::FilePath(base::ASCIIToUTF16(str)); +#else + return base::FilePath(str); +#endif +} + +int main(int argc, const char* argv[]) { + base::EnableTerminationOnHeapCorruption(); + base::CommandLine::Init(argc, argv); + const base::CommandLine& parsed_command_line = + *base::CommandLine::ForCurrentProcess(); + bool histograms = parsed_command_line.HasSwitch(kOptionCompareHistograms); + if (parsed_command_line.HasSwitch(kOptionPollStdin)) { + // Watch stdin for filenames. + std::string stdin_buffer; + base::FilePath filename1; + while (std::getline(std::cin, stdin_buffer)) { + if (stdin_buffer.empty()) + continue; + + if (!filename1.empty()) { + // CompareImages writes results to stdout unless an error occurred. + base::FilePath filename2 = FilePathFromASCII(stdin_buffer); + if (CompareImages(filename1, filename2, histograms) == kStatusError) + printf("error\n"); + fflush(stdout); + filename1 = base::FilePath(); + } else { + // Save the first filename in another buffer and wait for the second + // filename to arrive via stdin. + filename1 = FilePathFromASCII(stdin_buffer); + } + } + return 0; + } + + const base::CommandLine::StringVector& args = parsed_command_line.GetArgs(); + if (parsed_command_line.HasSwitch(kOptionGenerateDiff)) { + if (args.size() == 3) { + return DiffImages(base::FilePath(args[0]), + base::FilePath(args[1]), + base::FilePath(args[2])); + } + } else if (args.size() == 2) { + return CompareImages( + base::FilePath(args[0]), base::FilePath(args[1]), histograms); + } + + PrintHelp(); + return kStatusError; +} diff --git a/engine/src/flutter/sky/tools/imagediff/image_diff_png.cc b/engine/src/flutter/sky/tools/imagediff/image_diff_png.cc new file mode 100644 index 0000000000..e9d98c8c90 --- /dev/null +++ b/engine/src/flutter/sky/tools/imagediff/image_diff_png.cc @@ -0,0 +1,643 @@ +// Copyright 2013 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. + +#include "sky/tools/imagediff/image_diff_png.h" + +#include +#include + +#include "base/logging.h" +#include "build/build_config.h" +#include "third_party/libpng/png.h" +#include "third_party/zlib/zlib.h" + +namespace image_diff_png { + +// This is a duplicate of ui/gfx/codec/png_codec.cc, after removing code related +// to Skia, that we can use when running layout tests with minimal dependencies. +namespace { + +enum ColorFormat { + // 3 bytes per pixel (packed), in RGB order regardless of endianness. + // This is the native JPEG format. + FORMAT_RGB, + + // 4 bytes per pixel, in RGBA order in memory regardless of endianness. + FORMAT_RGBA, + + // 4 bytes per pixel, in BGRA order in memory regardless of endianness. + // This is the default Windows DIB order. + FORMAT_BGRA, + + // 4 bytes per pixel, in pre-multiplied kARGB_8888_Config format. For use + // with directly writing to a skia bitmap. + FORMAT_SkBitmap +}; + +// Represents a comment in the tEXt ancillary chunk of the png. +struct Comment { + std::string key; + std::string text; +}; + +// Converts BGRA->RGBA and RGBA->BGRA. +void ConvertBetweenBGRAandRGBA(const unsigned char* input, int pixel_width, + unsigned char* output, bool* is_opaque) { + for (int x = 0; x < pixel_width; x++) { + const unsigned char* pixel_in = &input[x * 4]; + unsigned char* pixel_out = &output[x * 4]; + pixel_out[0] = pixel_in[2]; + pixel_out[1] = pixel_in[1]; + pixel_out[2] = pixel_in[0]; + pixel_out[3] = pixel_in[3]; + } +} + +void ConvertRGBAtoRGB(const unsigned char* rgba, int pixel_width, + unsigned char* rgb, bool* is_opaque) { + for (int x = 0; x < pixel_width; x++) { + const unsigned char* pixel_in = &rgba[x * 4]; + unsigned char* pixel_out = &rgb[x * 3]; + pixel_out[0] = pixel_in[0]; + pixel_out[1] = pixel_in[1]; + pixel_out[2] = pixel_in[2]; + } +} + +} // namespace + +// Decoder -------------------------------------------------------------------- +// +// This code is based on WebKit libpng interface (PNGImageDecoder), which is +// in turn based on the Mozilla png decoder. + +namespace { + +// Gamma constants: We assume we're on Windows which uses a gamma of 2.2. +const double kMaxGamma = 21474.83; // Maximum gamma accepted by png library. +const double kDefaultGamma = 2.2; +const double kInverseGamma = 1.0 / kDefaultGamma; + +class PngDecoderState { + public: + // Output is a vector. + PngDecoderState(ColorFormat ofmt, std::vector* o) + : output_format(ofmt), + output_channels(0), + is_opaque(true), + output(o), + row_converter(NULL), + width(0), + height(0), + done(false) { + } + + ColorFormat output_format; + int output_channels; + + // Used during the reading of an SkBitmap. Defaults to true until we see a + // pixel with anything other than an alpha of 255. + bool is_opaque; + + // An intermediary buffer for decode output. + std::vector* output; + + // Called to convert a row from the library to the correct output format. + // When NULL, no conversion is necessary. + void (*row_converter)(const unsigned char* in, int w, unsigned char* out, + bool* is_opaque); + + // Size of the image, set in the info callback. + int width; + int height; + + // Set to true when we've found the end of the data. + bool done; +}; + +void ConvertRGBtoRGBA(const unsigned char* rgb, int pixel_width, + unsigned char* rgba, bool* is_opaque) { + for (int x = 0; x < pixel_width; x++) { + const unsigned char* pixel_in = &rgb[x * 3]; + unsigned char* pixel_out = &rgba[x * 4]; + pixel_out[0] = pixel_in[0]; + pixel_out[1] = pixel_in[1]; + pixel_out[2] = pixel_in[2]; + pixel_out[3] = 0xff; + } +} + +void ConvertRGBtoBGRA(const unsigned char* rgb, int pixel_width, + unsigned char* bgra, bool* is_opaque) { + for (int x = 0; x < pixel_width; x++) { + const unsigned char* pixel_in = &rgb[x * 3]; + unsigned char* pixel_out = &bgra[x * 4]; + pixel_out[0] = pixel_in[2]; + pixel_out[1] = pixel_in[1]; + pixel_out[2] = pixel_in[0]; + pixel_out[3] = 0xff; + } +} + +// Called when the png header has been read. This code is based on the WebKit +// PNGImageDecoder +void DecodeInfoCallback(png_struct* png_ptr, png_info* info_ptr) { + PngDecoderState* state = static_cast( + png_get_progressive_ptr(png_ptr)); + + int bit_depth, color_type, interlace_type, compression_type; + int filter_type, channels; + png_uint_32 w, h; + png_get_IHDR(png_ptr, info_ptr, &w, &h, &bit_depth, &color_type, + &interlace_type, &compression_type, &filter_type); + + // Bounds check. When the image is unreasonably big, we'll error out and + // end up back at the setjmp call when we set up decoding. "Unreasonably big" + // means "big enough that w * h * 32bpp might overflow an int"; we choose this + // threshold to match WebKit and because a number of places in code assume + // that an image's size (in bytes) fits in a (signed) int. + unsigned long long total_size = + static_cast(w) * static_cast(h); + if (total_size > ((1 << 29) - 1)) + longjmp(png_jmpbuf(png_ptr), 1); + state->width = static_cast(w); + state->height = static_cast(h); + + // Expand to ensure we use 24-bit for RGB and 32-bit for RGBA. + if (color_type == PNG_COLOR_TYPE_PALETTE || + (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)) + png_set_expand(png_ptr); + + // Transparency for paletted images. + if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) + png_set_expand(png_ptr); + + // Convert 16-bit to 8-bit. + if (bit_depth == 16) + png_set_strip_16(png_ptr); + + // Expand grayscale to RGB. + if (color_type == PNG_COLOR_TYPE_GRAY || + color_type == PNG_COLOR_TYPE_GRAY_ALPHA) + png_set_gray_to_rgb(png_ptr); + + // Deal with gamma and keep it under our control. + double gamma; + if (png_get_gAMA(png_ptr, info_ptr, &gamma)) { + if (gamma <= 0.0 || gamma > kMaxGamma) { + gamma = kInverseGamma; + png_set_gAMA(png_ptr, info_ptr, gamma); + } + png_set_gamma(png_ptr, kDefaultGamma, gamma); + } else { + png_set_gamma(png_ptr, kDefaultGamma, kInverseGamma); + } + + // Tell libpng to send us rows for interlaced pngs. + if (interlace_type == PNG_INTERLACE_ADAM7) + png_set_interlace_handling(png_ptr); + + // Update our info now + png_read_update_info(png_ptr, info_ptr); + channels = png_get_channels(png_ptr, info_ptr); + + // Pick our row format converter necessary for this data. + if (channels == 3) { + switch (state->output_format) { + case FORMAT_RGB: + state->row_converter = NULL; // no conversion necessary + state->output_channels = 3; + break; + case FORMAT_RGBA: + state->row_converter = &ConvertRGBtoRGBA; + state->output_channels = 4; + break; + case FORMAT_BGRA: + state->row_converter = &ConvertRGBtoBGRA; + state->output_channels = 4; + break; + default: + NOTREACHED() << "Unknown output format"; + break; + } + } else if (channels == 4) { + switch (state->output_format) { + case FORMAT_RGB: + state->row_converter = &ConvertRGBAtoRGB; + state->output_channels = 3; + break; + case FORMAT_RGBA: + state->row_converter = NULL; // no conversion necessary + state->output_channels = 4; + break; + case FORMAT_BGRA: + state->row_converter = &ConvertBetweenBGRAandRGBA; + state->output_channels = 4; + break; + default: + NOTREACHED() << "Unknown output format"; + break; + } + } else { + NOTREACHED() << "Unknown input channels"; + longjmp(png_jmpbuf(png_ptr), 1); + } + + state->output->resize( + state->width * state->output_channels * state->height); +} + +void DecodeRowCallback(png_struct* png_ptr, png_byte* new_row, + png_uint_32 row_num, int pass) { + PngDecoderState* state = static_cast( + png_get_progressive_ptr(png_ptr)); + + DCHECK(pass == 0); + if (static_cast(row_num) > state->height) { + NOTREACHED() << "Invalid row"; + return; + } + + unsigned char* base = NULL; + base = &state->output->front(); + + unsigned char* dest = &base[state->width * state->output_channels * row_num]; + if (state->row_converter) + state->row_converter(new_row, state->width, dest, &state->is_opaque); + else + memcpy(dest, new_row, state->width * state->output_channels); +} + +void DecodeEndCallback(png_struct* png_ptr, png_info* info) { + PngDecoderState* state = static_cast( + png_get_progressive_ptr(png_ptr)); + + // Mark the image as complete, this will tell the Decode function that we + // have successfully found the end of the data. + state->done = true; +} + +// Automatically destroys the given read structs on destruction to make +// cleanup and error handling code cleaner. +class PngReadStructDestroyer { + public: + PngReadStructDestroyer(png_struct** ps, png_info** pi) : ps_(ps), pi_(pi) { + } + ~PngReadStructDestroyer() { + png_destroy_read_struct(ps_, pi_, NULL); + } + private: + png_struct** ps_; + png_info** pi_; +}; + +bool BuildPNGStruct(const unsigned char* input, size_t input_size, + png_struct** png_ptr, png_info** info_ptr) { + if (input_size < 8) + return false; // Input data too small to be a png + + // Have libpng check the signature, it likes the first 8 bytes. + if (png_sig_cmp(const_cast(input), 0, 8) != 0) + return false; + + *png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + if (!*png_ptr) + return false; + + *info_ptr = png_create_info_struct(*png_ptr); + if (!*info_ptr) { + png_destroy_read_struct(png_ptr, NULL, NULL); + return false; + } + + return true; +} + +} // namespace + +// static +bool Decode(const unsigned char* input, size_t input_size, + ColorFormat format, std::vector* output, + int* w, int* h) { + png_struct* png_ptr = NULL; + png_info* info_ptr = NULL; + if (!BuildPNGStruct(input, input_size, &png_ptr, &info_ptr)) + return false; + + PngReadStructDestroyer destroyer(&png_ptr, &info_ptr); + if (setjmp(png_jmpbuf(png_ptr))) { + // The destroyer will ensure that the structures are cleaned up in this + // case, even though we may get here as a jump from random parts of the + // PNG library called below. + return false; + } + + PngDecoderState state(format, output); + + png_set_progressive_read_fn(png_ptr, &state, &DecodeInfoCallback, + &DecodeRowCallback, &DecodeEndCallback); + png_process_data(png_ptr, + info_ptr, + const_cast(input), + input_size); + + if (!state.done) { + // Fed it all the data but the library didn't think we got all the data, so + // this file must be truncated. + output->clear(); + return false; + } + + *w = state.width; + *h = state.height; + return true; +} + +// Encoder -------------------------------------------------------------------- +// +// This section of the code is based on nsPNGEncoder.cpp in Mozilla +// (Copyright 2005 Google Inc.) + +namespace { + +// Passed around as the io_ptr in the png structs so our callbacks know where +// to write data. +struct PngEncoderState { + explicit PngEncoderState(std::vector* o) : out(o) {} + std::vector* out; +}; + +// Called by libpng to flush its internal buffer to ours. +void EncoderWriteCallback(png_structp png, png_bytep data, png_size_t size) { + PngEncoderState* state = static_cast(png_get_io_ptr(png)); + DCHECK(state->out); + + size_t old_size = state->out->size(); + state->out->resize(old_size + size); + memcpy(&(*state->out)[old_size], data, size); +} + +void FakeFlushCallback(png_structp png) { + // We don't need to perform any flushing since we aren't doing real IO, but + // we're required to provide this function by libpng. +} + +void ConvertBGRAtoRGB(const unsigned char* bgra, int pixel_width, + unsigned char* rgb, bool* is_opaque) { + for (int x = 0; x < pixel_width; x++) { + const unsigned char* pixel_in = &bgra[x * 4]; + unsigned char* pixel_out = &rgb[x * 3]; + pixel_out[0] = pixel_in[2]; + pixel_out[1] = pixel_in[1]; + pixel_out[2] = pixel_in[0]; + } +} + +#ifdef PNG_TEXT_SUPPORTED + +inline char* strdup(const char* str) { +#if defined(OS_WIN) + return _strdup(str); +#else + return ::strdup(str); +#endif +} + +class CommentWriter { + public: + explicit CommentWriter(const std::vector& comments) + : comments_(comments), + png_text_(new png_text[comments.size()]) { + for (size_t i = 0; i < comments.size(); ++i) + AddComment(i, comments[i]); + } + + ~CommentWriter() { + for (size_t i = 0; i < comments_.size(); ++i) { + free(png_text_[i].key); + free(png_text_[i].text); + } + delete [] png_text_; + } + + bool HasComments() { + return !comments_.empty(); + } + + png_text* get_png_text() { + return png_text_; + } + + int size() { + return static_cast(comments_.size()); + } + + private: + void AddComment(size_t pos, const Comment& comment) { + png_text_[pos].compression = PNG_TEXT_COMPRESSION_NONE; + // A PNG comment's key can only be 79 characters long. + DCHECK(comment.key.length() < 79); + png_text_[pos].key = strdup(comment.key.substr(0, 78).c_str()); + png_text_[pos].text = strdup(comment.text.c_str()); + png_text_[pos].text_length = comment.text.length(); +#ifdef PNG_iTXt_SUPPORTED + png_text_[pos].itxt_length = 0; + png_text_[pos].lang = 0; + png_text_[pos].lang_key = 0; +#endif + } + + const std::vector comments_; + png_text* png_text_; +}; +#endif // PNG_TEXT_SUPPORTED + +// The type of functions usable for converting between pixel formats. +typedef void (*FormatConverter)(const unsigned char* in, int w, + unsigned char* out, bool* is_opaque); + +// libpng uses a wacky setjmp-based API, which makes the compiler nervous. +// We constrain all of the calls we make to libpng where the setjmp() is in +// place to this function. +// Returns true on success. +bool DoLibpngWrite(png_struct* png_ptr, png_info* info_ptr, + PngEncoderState* state, + int width, int height, int row_byte_width, + const unsigned char* input, int compression_level, + int png_output_color_type, int output_color_components, + FormatConverter converter, + const std::vector& comments) { +#ifdef PNG_TEXT_SUPPORTED + CommentWriter comment_writer(comments); +#endif + unsigned char* row_buffer = NULL; + + // Make sure to not declare any locals here -- locals in the presence + // of setjmp() in C++ code makes gcc complain. + + if (setjmp(png_jmpbuf(png_ptr))) { + delete[] row_buffer; + return false; + } + + png_set_compression_level(png_ptr, compression_level); + + // Set our callback for libpng to give us the data. + png_set_write_fn(png_ptr, state, EncoderWriteCallback, FakeFlushCallback); + + png_set_IHDR(png_ptr, info_ptr, width, height, 8, png_output_color_type, + PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, + PNG_FILTER_TYPE_DEFAULT); + +#ifdef PNG_TEXT_SUPPORTED + if (comment_writer.HasComments()) { + png_set_text(png_ptr, info_ptr, comment_writer.get_png_text(), + comment_writer.size()); + } +#endif + + png_write_info(png_ptr, info_ptr); + + if (!converter) { + // No conversion needed, give the data directly to libpng. + for (int y = 0; y < height; y ++) { + png_write_row(png_ptr, + const_cast(&input[y * row_byte_width])); + } + } else { + // Needs conversion using a separate buffer. + row_buffer = new unsigned char[width * output_color_components]; + for (int y = 0; y < height; y ++) { + converter(&input[y * row_byte_width], width, row_buffer, NULL); + png_write_row(png_ptr, row_buffer); + } + delete[] row_buffer; + } + + png_write_end(png_ptr, info_ptr); + return true; +} + +} // namespace + +// static +bool EncodeWithCompressionLevel(const unsigned char* input, ColorFormat format, + const int width, const int height, + int row_byte_width, + bool discard_transparency, + const std::vector& comments, + int compression_level, + std::vector* output) { + // Run to convert an input row into the output row format, NULL means no + // conversion is necessary. + FormatConverter converter = NULL; + + int input_color_components, output_color_components; + int png_output_color_type; + switch (format) { + case FORMAT_RGB: + input_color_components = 3; + output_color_components = 3; + png_output_color_type = PNG_COLOR_TYPE_RGB; + discard_transparency = false; + break; + + case FORMAT_RGBA: + input_color_components = 4; + if (discard_transparency) { + output_color_components = 3; + png_output_color_type = PNG_COLOR_TYPE_RGB; + converter = ConvertRGBAtoRGB; + } else { + output_color_components = 4; + png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA; + converter = NULL; + } + break; + + case FORMAT_BGRA: + input_color_components = 4; + if (discard_transparency) { + output_color_components = 3; + png_output_color_type = PNG_COLOR_TYPE_RGB; + converter = ConvertBGRAtoRGB; + } else { + output_color_components = 4; + png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA; + converter = ConvertBetweenBGRAandRGBA; + } + break; + + default: + NOTREACHED() << "Unknown pixel format"; + return false; + } + + // Row stride should be at least as long as the length of the data. + DCHECK(input_color_components * width <= row_byte_width); + + png_struct* png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, + NULL, NULL, NULL); + if (!png_ptr) + return false; + png_info* info_ptr = png_create_info_struct(png_ptr); + if (!info_ptr) { + png_destroy_write_struct(&png_ptr, NULL); + return false; + } + + PngEncoderState state(output); + bool success = DoLibpngWrite(png_ptr, info_ptr, &state, + width, height, row_byte_width, + input, compression_level, png_output_color_type, + output_color_components, converter, comments); + png_destroy_write_struct(&png_ptr, &info_ptr); + + return success; +} + +// static +bool Encode(const unsigned char* input, ColorFormat format, + const int width, const int height, int row_byte_width, + bool discard_transparency, + const std::vector& comments, + std::vector* output) { + return EncodeWithCompressionLevel(input, format, width, height, + row_byte_width, + discard_transparency, + comments, Z_DEFAULT_COMPRESSION, + output); +} + +// Decode a PNG into an RGBA pixel array. +bool DecodePNG(const unsigned char* input, size_t input_size, + std::vector* output, + int* width, int* height) { + return Decode(input, input_size, FORMAT_RGBA, output, width, height); +} + +// Encode an RGBA pixel array into a PNG. +bool EncodeRGBAPNG(const unsigned char* input, + int width, + int height, + int row_byte_width, + std::vector* output) { + return Encode(input, FORMAT_RGBA, + width, height, row_byte_width, false, + std::vector(), output); +} + +// Encode an BGRA pixel array into a PNG. +bool EncodeBGRAPNG(const unsigned char* input, + int width, + int height, + int row_byte_width, + bool discard_transparency, + std::vector* output) { + return Encode(input, FORMAT_BGRA, + width, height, row_byte_width, discard_transparency, + std::vector(), output); +} + +} // image_diff_png diff --git a/engine/src/flutter/sky/tools/imagediff/image_diff_png.h b/engine/src/flutter/sky/tools/imagediff/image_diff_png.h new file mode 100644 index 0000000000..c371337f99 --- /dev/null +++ b/engine/src/flutter/sky/tools/imagediff/image_diff_png.h @@ -0,0 +1,35 @@ +// Copyright 2013 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. + +#ifndef TOOLS_IMAGEDIFF_IMAGE_DIFF_PNG_H_ +#define TOOLS_IMAGEDIFF_IMAGE_DIFF_PNG_H_ + +#include +#include + +namespace image_diff_png { + +// Decode a PNG into an RGBA pixel array. +bool DecodePNG(const unsigned char* input, size_t input_size, + std::vector* output, + int* width, int* height); + +// Encode an RGBA pixel array into a PNG. +bool EncodeRGBAPNG(const unsigned char* input, + int width, + int height, + int row_byte_width, + std::vector* output); + +// Encode an BGRA pixel array into a PNG. +bool EncodeBGRAPNG(const unsigned char* input, + int width, + int height, + int row_byte_width, + bool discard_transparency, + std::vector* output); + +} // namespace image_diff_png + +#endif // TOOLS_IMAGEDIFF_IMAGE_DIFF_PNG_H_ diff --git a/engine/src/flutter/sky/tools/lint_test_expectations b/engine/src/flutter/sky/tools/lint_test_expectations new file mode 100755 index 0000000000..c56eb77dbb --- /dev/null +++ b/engine/src/flutter/sky/tools/lint_test_expectations @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# Copyright (C) 2012 Google Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import sys + +from webkitpy.common import version_check +from webkitpy.layout_tests import lint_test_expectations + + +sys.exit(lint_test_expectations.main(sys.argv[1:], sys.stdout, sys.stderr)) + diff --git a/engine/src/flutter/sky/tools/lint_webkitpy b/engine/src/flutter/sky/tools/lint_webkitpy new file mode 100755 index 0000000000..4e6af9fae9 --- /dev/null +++ b/engine/src/flutter/sky/tools/lint_webkitpy @@ -0,0 +1,36 @@ +#!/usr/bin/env python +# Copyright (c) 2012 Google Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import sys + +from webkitpy.style.checkers.python import PythonChecker + +for path in sys.argv[1:]: + checker = PythonChecker(path, lambda *args: None) + sys.stdout.write(checker._run_pylint(path)) diff --git a/engine/src/flutter/sky/tools/missing_from_gn b/engine/src/flutter/sky/tools/missing_from_gn new file mode 100755 index 0000000000..88ecee6894 --- /dev/null +++ b/engine/src/flutter/sky/tools/missing_from_gn @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# Copyright 2014 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 subprocess +import os +import argparse +import logging + +ROOT_DIR = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, + os.pardir)) + +# Where to cache GN results (they're expensive to compute). +GN_CACHE_PATH = os.path.abspath(os.path.join(ROOT_DIR, 'in_gn.txt')) + + +def stripped_lines_from_command(cmd, cwd=None): + lines = subprocess.check_output(cmd, cwd=cwd).splitlines() + return map(str.strip, lines) + + +def gn_desc(*args): + # GN doesn't understand absolute paths yet, so use a relative BUILD_DIR + # and pass ROOT_DIR as the CWD. + # Hard-coding Debug for now: + BUILD_DIR = '//out/Debug' # // means repository root-relative. + cmd = ['gn', 'desc', BUILD_DIR] + list(args) + return stripped_lines_from_command(cmd, cwd=ROOT_DIR) + + +def targets_under(target): + targets = gn_desc(target, 'deps', '--all') + return filter(lambda s: s.startswith(target), targets) + + +def used_files(target): + logging.info(target) + sources = map(lambda s: s[2:], gn_desc(target, 'sources')) + inputs = map(lambda s: s[2:], gn_desc(target, 'inputs')) + public = map(lambda s: s[2:], gn_desc(target, 'public')) + script = map(lambda s: s[2:], gn_desc(target, 'script')) + return sources + inputs + public + script + + +def find_on_disk(path): + # FIXME: Use os.walk and do fancier ignoring. + find_cmd = ['find', path, '-type', 'f'] + return stripped_lines_from_command(find_cmd, cwd=ROOT_DIR) + + +def main(): + logging.basicConfig(level=logging.INFO) + + if os.path.exists(GN_CACHE_PATH): + logging.info('Using cached GN list: %s' % GN_CACHE_PATH) + in_gn = set(map(str.strip, open(GN_CACHE_PATH).readlines())) + else: + logging.info('No gn cache found, rebuilding: %s' % GN_CACHE_PATH) + in_gn = set(sum(map(used_files, targets_under('//sky')), [])) + open(GN_CACHE_PATH, 'w+').write('\n'.join(in_gn)) + + on_disk = set(find_on_disk('sky/engine')) + # Ignore web/tests and bindings/tests + on_disk = set(filter(lambda p: '/tests/' not in p, on_disk)) + + missing_from_gn = sorted(on_disk - in_gn) + + IGNORED_EXTENSIONS = [ + '.py', # Probably some to remove, probably some to teach gn about. + # Python files not being known to gn can cause flaky builds too! + '.pyc', + '.gypi', + '.gn', + '.gni', + ] + for ext in IGNORED_EXTENSIONS: + missing_from_gn = filter(lambda p: not p.endswith(ext), missing_from_gn) + + # All upper-case files like README, DEPS, etc. are fine. + missing_from_gn = filter(lambda p: not os.path.basename(p).isupper(), + missing_from_gn) + + print '\n'.join(missing_from_gn) + + +if __name__ == '__main__': + main() diff --git a/engine/src/flutter/sky/tools/mojo_cache_linker.py b/engine/src/flutter/sky/tools/mojo_cache_linker.py new file mode 100755 index 0000000000..783377479e --- /dev/null +++ b/engine/src/flutter/sky/tools/mojo_cache_linker.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python +# 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 argparse +import logging +import os +import sys +import subprocess +import json +import platform + + +def library_paths(build_dir): + for name in os.listdir(build_dir): + path = os.path.realpath(os.path.join(build_dir, name)) + if not os.path.isfile(path): + continue + + # Only include suffixes we care about: + basename, ext = os.path.splitext(name) + if ext not in ('', '.mojo', '.so'): + continue + + # Ignore ninja's dot-files. + if basename.startswith('.'): + continue + yield path + + +def get_cached_app_id(path, cache, cache_mtime): + if not cache_mtime: + return None + try: + if os.path.getmtime(path) > cache_mtime: + return None + except: + return None + return cache.get(path) + + +def compute_path_to_app_id_map(paths, cache, cache_mtime): + path_to_app_id_map = {} + for path in paths: + app_id = get_cached_app_id(path, cache, cache_mtime) + if not app_id: + if platform.system() == 'Darwin': + logging.info('shasum -a 256 %s' % path) + output = subprocess.check_output(['shasum', '-a', '256', path]) + else: + logging.info('sha256sum %s' % path) + output = subprocess.check_output(['sha256sum', path]) + # Example output: + # f82a3551478a9a0e010adccd675053b9 png_viewer.mojo + app_id = output.strip().split()[0] + path_to_app_id_map[path] = app_id + return path_to_app_id_map + + +def read_app_id_cache(cache_path): + try: + with open(cache_path, 'r') as cache_file: + return json.load(cache_file), os.path.getmtime(cache_path) + except: + logging.warn('Failed to read file: %s' % cache_path) + return {}, None + + +def write_app_id_cache(cache_path, cache): + try: + with open(cache_path, 'w') as cache_file: + json.dump(cache, cache_file, indent=2, sort_keys=True) + except: + logging.warn('Failed to write file: %s' % cache_path) + + +# TODO(eseidel): Share logic with tools/android_stack_parser/stack +def main(): + logging.basicConfig(level=logging.WARN) + parser = argparse.ArgumentParser( + description='Builds a directory of app_id symlinks to symbols' + ' to match expected dlopen names from mojo_shell\'s NetworkLoader.') + parser.add_argument('links_dir', type=str) + parser.add_argument('build_dir', type=str) + parser.add_argument('-f', '--force', action='store_true') + parser.add_argument('-v', '--verbose', action='store_true') + args = parser.parse_args() + + if args.verbose: + logging.getLogger().setLevel(logging.INFO) + + if not os.path.isdir(args.links_dir): + logging.fatal('links_dir: %s is not a directory' % args.links_dir) + sys.exit(1) + + # Some of the .so files are 100s of megabytes. Cache the md5s to save time. + cache_path = os.path.join(args.build_dir, '.app_id_cache') + cache, cache_mtime = read_app_id_cache(cache_path) + if args.force: + cache_mtime = None + + paths = library_paths(args.build_dir) + path_to_app_id_map = compute_path_to_app_id_map(list(paths), + cache, cache_mtime) + + # The cache contains unmodified app-ids. + write_app_id_cache(cache_path, path_to_app_id_map) + + for path, app_id in path_to_app_id_map.items(): + basename = os.path.basename(path) + root_name, ext = os.path.splitext(basename) + + # On android foo.mojo is stripped, but libfoo_library.so is not. + if ext == '.mojo': + symboled_name = 'lib%s_library.so' % root_name + symboled_path = os.path.realpath( + os.path.join(args.build_dir, symboled_name)) + if os.path.exists(symboled_path): + path = symboled_path + + link_path = os.path.join(args.links_dir, '%s.mojo' % app_id) + + logging.info("%s -> %s" % (link_path, path)) + + if os.path.lexists(link_path): + logging.debug('link already exists %s, replacing' % path) + os.unlink(link_path) + + os.symlink(path, link_path) + + +if __name__ == '__main__': + main() diff --git a/engine/src/flutter/sky/tools/packager/BUILD.gn b/engine/src/flutter/sky/tools/packager/BUILD.gn new file mode 100644 index 0000000000..a8ad042ee9 --- /dev/null +++ b/engine/src/flutter/sky/tools/packager/BUILD.gn @@ -0,0 +1,28 @@ +# Copyright 2014 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. + +executable("packager") { + output_name = "sky_packager" + + sources = [ + "loader.cc", + "loader.h", + "logging.cc", + "logging.h", + "main.cc", + "scope.h", + "switches.cc", + "switches.h", + "vm.cc", + "vm.h", + ] + + deps = [ + "//base", + "//dart/runtime/vm:libdart_platform", + "//dart/runtime:libdart", + "//sky/engine/bindings:snapshot_cc", + "//third_party/zlib", + ] +} diff --git a/engine/src/flutter/sky/tools/packager/loader.cc b/engine/src/flutter/sky/tools/packager/loader.cc new file mode 100644 index 0000000000..9b5e0240c9 --- /dev/null +++ b/engine/src/flutter/sky/tools/packager/loader.cc @@ -0,0 +1,127 @@ +// 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. + +#include "sky/tools/packager/loader.h" + +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/strings/string_util.h" +#include "sky/tools/packager/logging.h" +#include "sky/tools/packager/scope.h" +#include "sky/tools/packager/switches.h" + +namespace { + +std::string Fetch(const std::string& url) { + base::FilePath path(url); + std::string source; + CHECK(base::ReadFileToString(path, &source)) << url; + return source; +} + +base::FilePath SimplifyPath(const base::FilePath& path) { + std::vector components; + path.GetComponents(&components); + base::FilePath result; + for (const auto& component : components) { + if (component == base::FilePath::kCurrentDirectory) + continue; + if (component == base::FilePath::kParentDirectory) + result = result.DirName(); + else + result = result.Append(component); + } + return result; +} + +class Loader { + public: + Loader(const base::FilePath& package_root); + + std::string CanonicalizePackageURL(std::string url); + Dart_Handle CanonicalizeURL(Dart_Handle library, Dart_Handle url); + Dart_Handle Import(Dart_Handle url); + Dart_Handle Source(Dart_Handle library, Dart_Handle url); + + private: + base::FilePath package_root_; + + DISALLOW_COPY_AND_ASSIGN(Loader); +}; + +Loader::Loader(const base::FilePath& package_root) + : package_root_(package_root) { +} + +std::string Loader::CanonicalizePackageURL(std::string url) { + DCHECK(StartsWithASCII(url, "package:", true)); + ReplaceFirstSubstringAfterOffset(&url, 0, "package:", ""); + return package_root_.Append(url).AsUTF8Unsafe(); +} + +Dart_Handle Loader::CanonicalizeURL(Dart_Handle library, Dart_Handle url) { + std::string string = StringFromDart(url); + if (StartsWithASCII(string, "dart:", true)) + return url; + if (StartsWithASCII(string, "package:", true)) + return StringToDart(CanonicalizePackageURL(string)); + base::FilePath base_path(StringFromDart(Dart_LibraryUrl(library))); + base::FilePath resolved_path = base_path.DirName().Append(string); + base::FilePath normalized_path = SimplifyPath(resolved_path); + return StringToDart(normalized_path.AsUTF8Unsafe()); +} + +Dart_Handle Loader::Import(Dart_Handle url) { + Dart_Handle source = StringToDart(Fetch(StringFromDart(url))); + Dart_Handle result = Dart_LoadLibrary(url, source, 0, 0); + LogIfError(result); + return result; +} + +Dart_Handle Loader::Source(Dart_Handle library, Dart_Handle url) { + Dart_Handle source = StringToDart(Fetch(StringFromDart(url))); + Dart_Handle result = Dart_LoadSource(library, url, source, 0, 0); + LogIfError(result); + return result; +} + +Loader* g_loader = nullptr; + +Loader& GetLoader() { + if (!g_loader) { + base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); + CHECK(command_line.HasSwitch(switches::kPackageRoot)) + << "Need --package-root"; + g_loader = + new Loader(command_line.GetSwitchValuePath(switches::kPackageRoot)); + } + return *g_loader; +} + +} // namespace + +Dart_Handle HandleLibraryTag(Dart_LibraryTag tag, + Dart_Handle library, + Dart_Handle url) { + CHECK(Dart_IsLibrary(library)); + CHECK(Dart_IsString(url)); + + if (tag == Dart_kCanonicalizeUrl) + return GetLoader().CanonicalizeURL(library, url); + + if (tag == Dart_kImportTag) + return GetLoader().Import(url); + + if (tag == Dart_kSourceTag) + return GetLoader().Source(library, url); + + return Dart_NewApiError("Unknown library tag."); +} + +void LoadScript(const std::string& url) { + LogIfError( + Dart_LoadScript(StringToDart(url), StringToDart(Fetch(url)), 0, 0)); +} diff --git a/engine/src/flutter/sky/tools/packager/loader.h b/engine/src/flutter/sky/tools/packager/loader.h new file mode 100644 index 0000000000..da9b67a4e3 --- /dev/null +++ b/engine/src/flutter/sky/tools/packager/loader.h @@ -0,0 +1,17 @@ +// 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. + +#ifndef SKY_TOOLS_PACKAGER_LOADER_H_ +#define SKY_TOOLS_PACKAGER_LOADER_H_ + +#include + +#include "dart/runtime/include/dart_api.h" + +Dart_Handle HandleLibraryTag(Dart_LibraryTag tag, + Dart_Handle library, + Dart_Handle url); +void LoadScript(const std::string& url); + +#endif // SKY_TOOLS_PACKAGER_LOADER_H_ diff --git a/engine/src/flutter/sky/tools/packager/logging.cc b/engine/src/flutter/sky/tools/packager/logging.cc new file mode 100644 index 0000000000..e61820cb97 --- /dev/null +++ b/engine/src/flutter/sky/tools/packager/logging.cc @@ -0,0 +1,37 @@ +// 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. + +#include "sky/tools/packager/logging.h" + +#include "base/logging.h" + +bool LogIfError(Dart_Handle handle) { + if (Dart_IsError(handle)) { + LOG(ERROR) << Dart_GetError(handle); + + // Only unhandled exceptions have stacktraces. + if (!Dart_ErrorHasException(handle)) + return true; + + Dart_Handle stacktrace = Dart_ErrorGetStacktrace(handle); + const char* stacktrace_cstr = ""; + Dart_StringToCString(Dart_ToString(stacktrace), &stacktrace_cstr); + LOG(ERROR) << stacktrace_cstr; + return true; + } + return false; +} + +std::string StringFromDart(Dart_Handle string) { + CHECK(Dart_IsString(string)); + uint8_t* utf8_array; + intptr_t length; + Dart_StringToUTF8(string, &utf8_array, &length); + return std::string(reinterpret_cast(utf8_array), length); +} + +Dart_Handle StringToDart(const std::string& string) { + return Dart_NewStringFromUTF8(reinterpret_cast(string.data()), + string.length()); +} diff --git a/engine/src/flutter/sky/tools/packager/logging.h b/engine/src/flutter/sky/tools/packager/logging.h new file mode 100644 index 0000000000..227a9d8f5e --- /dev/null +++ b/engine/src/flutter/sky/tools/packager/logging.h @@ -0,0 +1,16 @@ +// 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. + +#ifndef SKY_TOOLS_PACKAGER_LOGGING_H_ +#define SKY_TOOLS_PACKAGER_LOGGING_H_ + +#include + +#include "dart/runtime/include/dart_api.h" + +bool LogIfError(Dart_Handle handle); +std::string StringFromDart(Dart_Handle string); +Dart_Handle StringToDart(const std::string& string); + +#endif // SKY_TOOLS_PACKAGER_LOGGING_H_ diff --git a/engine/src/flutter/sky/tools/packager/main.cc b/engine/src/flutter/sky/tools/packager/main.cc new file mode 100644 index 0000000000..7b20c436a4 --- /dev/null +++ b/engine/src/flutter/sky/tools/packager/main.cc @@ -0,0 +1,67 @@ +// 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. + +#include + +#include "base/at_exit.h" +#include "base/basictypes.h" +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/process/memory.h" +#include "dart/runtime/include/dart_api.h" +#include "sky/tools/packager/loader.h" +#include "sky/tools/packager/logging.h" +#include "sky/tools/packager/scope.h" +#include "sky/tools/packager/switches.h" +#include "sky/tools/packager/vm.h" + +void Usage() { + std::cerr << "Usage: sky_packager" + << " --" << switches::kPackageRoot << " --" << switches::kSnapshot + << " " << std::endl; +} + +void WriteSnapshot(base::FilePath path) { + uint8_t* buffer; + intptr_t size; + CHECK(!LogIfError(Dart_CreateScriptSnapshot(&buffer, &size))); + + CHECK_EQ(base::WriteFile(path, reinterpret_cast(buffer), size), + size); +} + +int main(int argc, const char* argv[]) { + base::AtExitManager exit_manager; + base::EnableTerminationOnHeapCorruption(); + base::CommandLine::Init(argc, argv); + + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + + if (command_line.HasSwitch(switches::kHelp) || + command_line.GetArgs().empty()) { + Usage(); + return 0; + } + + InitDartVM(); + Dart_Isolate isolate = CreateDartIsolate(); + CHECK(isolate); + + DartIsolateScope scope(isolate); + DartApiScope api_scope; + + auto args = command_line.GetArgs(); + CHECK(args.size() == 1); + LoadScript(args[0]); + + CHECK(!LogIfError(Dart_FinalizeLoading(true))); + + CHECK(command_line.HasSwitch(switches::kSnapshot)) << "Need --snapshot"; + WriteSnapshot(command_line.GetSwitchValuePath(switches::kSnapshot)); + + return 0; +} diff --git a/engine/src/flutter/sky/tools/packager/scope.h b/engine/src/flutter/sky/tools/packager/scope.h new file mode 100644 index 0000000000..b039d24dcc --- /dev/null +++ b/engine/src/flutter/sky/tools/packager/scope.h @@ -0,0 +1,33 @@ +// 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. + +#ifndef SKY_TOOLS_PACKAGER_SCOPE_H_ +#define SKY_TOOLS_PACKAGER_SCOPE_H_ + +#include "base/basictypes.h" +#include "base/logging.h" +#include "dart/runtime/include/dart_api.h" + +class DartIsolateScope { + public: + explicit DartIsolateScope(Dart_Isolate isolate) { + CHECK(!Dart_CurrentIsolate()); + Dart_EnterIsolate(isolate); + } + ~DartIsolateScope() { Dart_ExitIsolate(); } + + private: + DISALLOW_COPY_AND_ASSIGN(DartIsolateScope); +}; + +class DartApiScope { + public: + DartApiScope() { Dart_EnterScope(); } + ~DartApiScope() { Dart_ExitScope(); } + + private: + DISALLOW_COPY_AND_ASSIGN(DartApiScope); +}; + +#endif // SKY_TOOLS_PACKAGER_SCOPE_H_ diff --git a/engine/src/flutter/sky/tools/packager/switches.cc b/engine/src/flutter/sky/tools/packager/switches.cc new file mode 100644 index 0000000000..664055f545 --- /dev/null +++ b/engine/src/flutter/sky/tools/packager/switches.cc @@ -0,0 +1,13 @@ +// 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. + +#include "sky/tools/packager/switches.h" + +namespace switches { + +const char kHelp[] = "help"; +const char kPackageRoot[] = "package-root"; +const char kSnapshot[] = "snapshot"; + +} // namespace switches diff --git a/engine/src/flutter/sky/tools/packager/switches.h b/engine/src/flutter/sky/tools/packager/switches.h new file mode 100644 index 0000000000..0a5d1be7ef --- /dev/null +++ b/engine/src/flutter/sky/tools/packager/switches.h @@ -0,0 +1,16 @@ +// 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. + +#ifndef SKY_TOOLS_PACKAGER_SWITCHES_H_ +#define SKY_TOOLS_PACKAGER_SWITCHES_H_ + +namespace switches { + +extern const char kHelp[]; +extern const char kPackageRoot[]; +extern const char kSnapshot[]; + +} // namespace switches + +#endif // SKY_TOOLS_PACKAGER_SWITCHES_H_ diff --git a/engine/src/flutter/sky/tools/packager/vm.cc b/engine/src/flutter/sky/tools/packager/vm.cc new file mode 100644 index 0000000000..b4cb8e903e --- /dev/null +++ b/engine/src/flutter/sky/tools/packager/vm.cc @@ -0,0 +1,39 @@ +// 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. + +#include "sky/tools/packager/vm.h" + +#include "base/logging.h" +#include "sky/tools/packager/loader.h" +#include "sky/tools/packager/logging.h" + +namespace blink { +extern const uint8_t* kDartVmIsolateSnapshotBuffer; +extern const uint8_t* kDartIsolateSnapshotBuffer; +} + +static const char* kDartArgs[] = { + "--enable_mirrors=false", +}; + +void InitDartVM() { + CHECK(Dart_SetVMFlags(arraysize(kDartArgs), kDartArgs)); + CHECK(Dart_Initialize(blink::kDartVmIsolateSnapshotBuffer, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr)); +} + +Dart_Isolate CreateDartIsolate() { + CHECK(blink::kDartIsolateSnapshotBuffer); + char* error = nullptr; + Dart_Isolate isolate = Dart_CreateIsolate("dart:snapshot", "main", + blink::kDartIsolateSnapshotBuffer, + nullptr, nullptr, &error); + + CHECK(isolate) << error; + CHECK(!LogIfError(Dart_SetLibraryTagHandler(HandleLibraryTag))); + + Dart_ExitIsolate(); + return isolate; +} diff --git a/engine/src/flutter/sky/tools/packager/vm.h b/engine/src/flutter/sky/tools/packager/vm.h new file mode 100644 index 0000000000..681fbc9e31 --- /dev/null +++ b/engine/src/flutter/sky/tools/packager/vm.h @@ -0,0 +1,13 @@ +// 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. + +#ifndef SKY_TOOLS_PACKAGER_VM_H_ +#define SKY_TOOLS_PACKAGER_VM_H_ + +#include "dart/runtime/include/dart_api.h" + +void InitDartVM(); +Dart_Isolate CreateDartIsolate(); + +#endif // SKY_TOOLS_PACKAGER_VM_H_ diff --git a/engine/src/flutter/sky/tools/pretty-diff b/engine/src/flutter/sky/tools/pretty-diff new file mode 100755 index 0000000000..5ddeab0ac6 --- /dev/null +++ b/engine/src/flutter/sky/tools/pretty-diff @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# Copyright (c) 2011 Code Aurora Forum. All rights reserved. +# Copyright (c) 2010 Google Inc. All rights reserved. +# Copyright (c) 2009 Apple Inc. All rights reserved. +# Copyright (C) 2010 Chris Jerdonek (cjerdonek@webkit.org) +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# A tool for automating dealing with bugzilla, posting patches, committing patches, etc. + +import time +import urllib +import webbrowser + +from webkitpy.common.prettypatch import PrettyPatch +from webkitpy.common.system import logutils +from webkitpy.common.system.executive import Executive +from webkitpy.common.system.executive import ScriptError +from webkitpy.common.system.filesystem import FileSystem +from webkitpy.common.checkout.scm.detection import detect_scm_system + + +_log = logutils.get_logger(__file__) + + +def can_open_url(): + try: + webbrowser.get() + return True + except webbrowser.Error, e: + return False + +def open_url(url): + if not can_open_url(): + _log.warn("Failed to open %s" % url) + webbrowser.open(url) + +def show_pretty_diff(): + if not can_open_url(): + return None + + try: + pretty_patch = PrettyPatch(Executive()) + pretty_diff_file = pretty_patch.pretty_diff_file(diff()) + url = "file://%s" % urllib.quote(pretty_diff_file.name) + open_url(url) + # We return the pretty_diff_file here because we need to keep the + # file alive until the user has had a chance to confirm the diff. + return pretty_diff_file + except ScriptError, e: + _log.warning("PrettyPatch failed. :(") + except OSError, e: + _log.warning("PrettyPatch unavailable.") + +def diff(): + scm = detect_scm_system(FileSystem().getcwd()) + changed_files = scm.changed_files() + return scm.create_patch(None, changed_files=changed_files) + +def main(): + pretty_diff_file = show_pretty_diff() + # This is a terrible hack. Try to give enough time for the + # browser to actually load the file. + time.sleep(1) + if pretty_diff_file: + pretty_diff_file.close() + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + sys.exit(signal.SIGINT + 128) diff --git a/engine/src/flutter/sky/tools/publish_apk.py b/engine/src/flutter/sky/tools/publish_apk.py new file mode 100755 index 0000000000..b3bd6c5027 --- /dev/null +++ b/engine/src/flutter/sky/tools/publish_apk.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python +# 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. + +# Modeled on examples from: +# https://github.com/googlesamples/android-play-publisher-api/tree/master/v2/python + +import argparse +import httplib2 +import logging +import os +import sys + +from apiclient.discovery import build +from oauth2client import client + + +SERVICE_ACCOUNT_EMAIL = ( + '69268379666-mu02g6delkg25t856t773fkdt9p90lpd@developer.gserviceaccount.com') +KEY_FILE_PATH = os.path.expanduser('~/sky_publish_key.p12') +API_AUTH_SCOPE = 'https://www.googleapis.com/auth/androidpublisher' +DEFAULT_TRACK = 'production' + + +def read_binary_file(path): + with file(path, 'rb') as f: + return f.read() + + +def read_text_file(path): + with file(path, 'r') as f: + return f.read() + + +def publish_apk(service, package_name, apk_path, changes_text, track): + edit_request = service.edits().insert(body={}, packageName=package_name) + result = edit_request.execute() + edit_id = result['id'] + + apk_response = service.edits().apks().upload( + editId=edit_id, + packageName=package_name, + media_body=apk_path).execute() + + print 'Version code %d has been uploaded' % apk_response['versionCode'] + + track_response = service.edits().tracks().update( + editId=edit_id, + track=track, + packageName=package_name, + body={u'versionCodes': [apk_response['versionCode']]}).execute() + + print 'Track %s is set for version code(s) %s' % ( + track_response['track'], str(track_response['versionCodes'])) + + listing_response = service.edits().apklistings().update( + editId=edit_id, packageName=package_name, language='en-US', + apkVersionCode=apk_response['versionCode'], + body={'recentChanges': changes_text}).execute() + + print ('Listing for language %s was updated.' + % listing_response['language']) + + commit_request = service.edits().commit( + editId=edit_id, packageName=package_name).execute() + + print 'Edit "%s" has been committed' % (commit_request['id']) + + +def connect_to_service(email, key_file, auth_scope): + credentials = client.SignedJwtAssertionCredentials( + email, + read_binary_file(key_file), + scope=auth_scope) + http = httplib2.Http() + http = credentials.authorize(http) + + return build('androidpublisher', 'v2', http=http) + + +def main(argv): + logging.basicConfig() + + parser = argparse.ArgumentParser() + parser.add_argument('package_name', help='Package (e.g. com.android.sample)') + parser.add_argument('apk_path', help='Path to the APK file to upload.') + parser.add_argument('changes_file', + help='Path to file containing "What\'s new in this version?" text.') + parser.add_argument('--track', default=DEFAULT_TRACK, + choices=['alpha', 'beta', 'production', 'rollout']) + args = parser.parse_args() + + changes_text = read_text_file(args.changes_file) + + service = connect_to_service(SERVICE_ACCOUNT_EMAIL, KEY_FILE_PATH, + API_AUTH_SCOPE) + + try: + publish_apk(service, args.package_name, args.apk_path, changes_text, + args.track) + except client.AccessTokenRefreshError: + print ('The credentials have been revoked or expired, please re-run the ' + 'application to re-authorize') + + +if __name__ == '__main__': + main(sys.argv) diff --git a/engine/src/flutter/sky/tools/resurrect.py b/engine/src/flutter/sky/tools/resurrect.py new file mode 100755 index 0000000000..878eca5e18 --- /dev/null +++ b/engine/src/flutter/sky/tools/resurrect.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python +# Copyright 2014 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. + +# Knows how to pull down files from the version of Blink we forked from. + +import argparse +import requests +import os +import sys + +FORK_VERSION = "086acdd04cbe6fcb89b2fc6bd438fb8819a26776" + +parser = argparse.ArgumentParser("Tool for resurrecting pre-fork Blink files.") +parser.add_argument("path", help="Path from Blink's Source root to the file." + "e.g. core/dom/ExecutionContextTask.h") +args = parser.parse_args() + +BASE_URL = "http://blink.lc/blink/plain/Source/%s?id=%s" +url = BASE_URL % (args.path, FORK_VERSION) +response = requests.get(url) +if response.status_code != 200: + print "Load failure: %s" % url + sys.exit(0) +contents = response.text + +file_name = os.path.basename(args.path) + +if os.path.exists(file_name): + print "%s exists, do you want to overwrite [y/N]?" % file_name + if raw_input().lower() not in ('y', 'yes'): + print "Aborting." + sys.exit(1) + +with open(file_name, "w+") as output: + output.write(contents) + print "Wrote %s" % file_name \ No newline at end of file diff --git a/engine/src/flutter/sky/tools/roll_versions.py b/engine/src/flutter/sky/tools/roll_versions.py new file mode 100755 index 0000000000..08b4c009d1 --- /dev/null +++ b/engine/src/flutter/sky/tools/roll_versions.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python +# 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 os +import subprocess +import yaml +import xml.etree.ElementTree as ET + + +PUBSPECS = [ + 'sky/sdk/pubspec.yaml', + 'mojo/public/dart/pubspec.yaml', + 'mojo/dart/mojo_services/pubspec.yaml', + 'mojo/dart/mojom/pubspec.yaml', +] + +MANIFESTS = [ + 'sky/sdk/example/demo_launcher/apk/AndroidManifest.xml', +] + +MANIFEST_PREFACE = ''' + +''' + + +def increment_version(version): + pieces = version.split('.') + pieces[-1] = str(int(pieces[-1]) + 1) + return '.'.join(pieces) + + +def sort_dict(unsorted): + sorted_dict = collections.OrderedDict() + for key in sorted(unsorted.keys()): + sorted_dict[key] = unsorted[key] + return sorted_dict + + +def count_commits(start, end): + return subprocess.check_output([ + 'git', 'rev-list', '%s...%s' % (start, end)]).count('\n') + + +def last_commit_to(file_path): + return subprocess.check_output(['git', 'log', '-1', '--format=%h', file_path]).strip() + + +def update_pubspec(pubspec): + # TODO(eseidel): This does not prserve any manual sort-order of the yaml. + with open(pubspec, 'r') as stream: + spec = yaml.load(stream) + old_version = spec['version'] + spec['version'] = increment_version(old_version) + print "%20s %6s => %6s" % (spec['name'], old_version, spec['version']) + + with open(pubspec, 'w') as stream: + yaml.dump(spec, stream=stream, default_flow_style=False) + return spec['version'] + + +def update_changelog(changelog, pubspec, version): + old = last_commit_to(pubspec) + new = last_commit_to('.') + url = "https://github.com/domokit/mojo/compare/%s...%s" % (old, new) + count = count_commits(old, new) + message = """## %s + + - %s changes: %s + +""" % (version, count, url) + prepend_to_file(message, changelog) + + +def prepend_to_file(to_prepend, filepath): + with open(filepath, 'r+') as f: + content = f.read() + f.seek(0, 0) + f.write(to_prepend + content) + + +def update_manifest(manifest): + VERSION_CODE = '{http://schemas.android.com/apk/res/android}versionCode' + VERSION_NAME = '{http://schemas.android.com/apk/res/android}versionName' + tree = ET.parse(manifest) + root = tree.getroot() + package_name = root.get('package') + old_code = root.get(VERSION_CODE) + old_name = root.get(VERSION_NAME) + root.set(VERSION_CODE, increment_version(old_code)) + root.set(VERSION_NAME, increment_version(old_name)) + print "%20s %6s (%s) => %6s (%s)" % (package_name, old_name, old_code, + root.get(VERSION_NAME), root.get(VERSION_CODE)) + # TODO(eseidel): This isn't smart enough to wrap/intent multi-attribute + # elements like as is the typical AndroidManifiest.xml style + # we could write our own custom prettyprinter to do that? + tree.write(manifest) + prepend_to_file(MANIFEST_PREFACE, manifest) + + +def main(): + # Should chdir to the root directory. + + print 'Pub packages:' + for pubspec in PUBSPECS: + new_version = update_pubspec(pubspec) + changelog = os.path.join(os.path.dirname(pubspec), 'CHANGELOG.md') + update_changelog(changelog, pubspec, new_version) + + # TODO(eseidel): Without this ET uses 'ns0' for 'android' which is wrong. + ET.register_namespace('android', 'http://schemas.android.com/apk/res/android') + + print 'APKs:' + for manifest in MANIFESTS: + update_manifest(manifest) + + +if __name__ == '__main__': + main() diff --git a/engine/src/flutter/sky/tools/setup_dart_analyzer b/engine/src/flutter/sky/tools/setup_dart_analyzer new file mode 100755 index 0000000000..65e69cc5ac --- /dev/null +++ b/engine/src/flutter/sky/tools/setup_dart_analyzer @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# 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 argparse +import subprocess +import sys +import os +import yaml + + +SKY_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) +SRC_ROOT = os.path.dirname(os.path.dirname(SKY_TOOLS_DIR)) +SKY_SDK_DIR = os.path.join(SRC_ROOT, 'sky', 'sdk') +SKY_PUBSPEC = os.path.join(SKY_SDK_DIR, 'pubspec.yaml') +SKY_PUBSPEC_LOCK = os.path.join(SKY_SDK_DIR, 'pubspec.lock') +SDK_EXT = os.path.join(SKY_SDK_DIR, 'lib', '_sdkext') + +SDK_EXT_TEMPLATE = '''{ + "dart:sky": "%(build_dir)s/gen/dart-pkg/sky/sdk_ext/dart_sky.dart", + "dart:sky.internals": "%(build_dir)s/gen/dart-pkg/sky/sdk_ext/sky_internals.dart", + "dart:sky_builtin_natvies": "%(build_dir)s/gen/dart-pkg/sky/sdk_ext/builtin_natives.dart" +}''' + +def version_for_pubspec(pubspec_path): + with open(pubspec_path, 'r') as stream: + dependency_spec = yaml.load(stream) + return dependency_spec['version'] + + +def entry_for_dependency(dart_pkg_dir, dependency): + dependency_path = os.path.join(dart_pkg_dir, dependency) + version = version_for_pubspec(os.path.join(dependency_path, 'pubspec.yaml')) + return { + 'description': { + 'path': os.path.relpath(dependency_path, SKY_SDK_DIR), + 'relative': True, + }, + 'source': 'path', + 'version': version, + } + + +def main(): + parser = argparse.ArgumentParser(description='Adds files to the source tree to make the dart analyzer happy') + parser.add_argument('build_dir', type=str, help='Path the build directory to use for build artifacts') + args = parser.parse_args() + + dart_pkg_dir = os.path.join(args.build_dir, 'gen', 'dart-pkg') + + if not os.path.exists(dart_pkg_dir): + print 'Cannot find Dart pacakges at "%s".' % dart_pkg_dir + print 'Did you run `ninja -C %s sky` ?' % os.path.relpath(args.build_dir, os.getcwd()) + return 1 + + packages = {} + + with open(SKY_PUBSPEC, 'r') as stream: + spec = yaml.load(stream) + for dependency in spec['dependencies'].keys(): + packages[dependency] = entry_for_dependency(dart_pkg_dir, dependency) + + lock = { 'packages': packages } + with open(SKY_PUBSPEC_LOCK, 'w') as stream: + yaml.dump(lock, stream=stream, default_flow_style=False) + + with open(SDK_EXT, 'w') as stream: + rebased_build_dir = os.path.relpath(args.build_dir, os.path.dirname(SDK_EXT)) + stream.write(SDK_EXT_TEMPLATE % { 'build_dir': rebased_build_dir }) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/engine/src/flutter/sky/tools/shelldb b/engine/src/flutter/sky/tools/shelldb new file mode 100755 index 0000000000..ae1c588d2d --- /dev/null +++ b/engine/src/flutter/sky/tools/shelldb @@ -0,0 +1,502 @@ +#!/usr/bin/env python +# 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. + +from skypy.skyserver import SkyServer +import argparse +import hashlib +import json +import logging +import os +import pipes +import platform +import re +import signal +import subprocess +import sys +import tempfile +import time +import urlparse + +SKY_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) +SKY_ROOT = os.path.dirname(SKY_TOOLS_DIR) +SRC_ROOT = os.path.dirname(SKY_ROOT) + +GDB_PORT = 8888 +SKY_SERVER_PORT = 9888 +OBSERVATORY_PORT = 8181 +DEFAULT_URL = "https://domokit.github.io/home.dart" +APK_NAME = 'SkyDemo.apk' +ADB_PATH = os.path.join(SRC_ROOT, + 'third_party/android_tools/sdk/platform-tools/adb') +ANDROID_PACKAGE = "org.domokit.sky.demo" +ANDROID_COMPONENT = '%s/%s.SkyDemoActivity' % (ANDROID_PACKAGE, ANDROID_PACKAGE) +SHA1_PATH = '/sdcard/%s/%s.sha1' % (ANDROID_PACKAGE, APK_NAME) + +PID_FILE_PATH = "/tmp/skydemo.pids" +PID_FILE_KEYS = frozenset([ + 'remote_sky_server_port', + 'sky_server_pid', + 'sky_server_port', + 'sky_server_root', + 'build_dir', + 'sky_shell_pid', + 'remote_gdbserver_port', +]) + +SYSTEM_LIBS_ROOT_PATH = '/tmp/device_libs' + +# This 'strict dictionary' approach is useful for catching typos. +class Pids(object): + def __init__(self, known_keys, contents=None): + self._known_keys = known_keys + self._dict = contents if contents is not None else {} + + def __len__(self): + return len(self._dict) + + def get(self, key, default=None): + assert key in self._known_keys, '%s not in known_keys' % key + return self._dict.get(key, default) + + def __getitem__(self, key): + assert key in self._known_keys, '%s not in known_keys' % key + return self._dict[key] + + def __setitem__(self, key, value): + assert key in self._known_keys, '%s not in known_keys' % key + self._dict[key] = value + + def __delitem__(self, key): + assert key in self._known_keys, '%s not in known_keys' % key + del self._dict[key] + + def __iter__(self): + return iter(self._dict) + + def __contains__(self, key): + assert key in self._known_keys, '%s not in allowed_keys' % key + return key in self._dict + + def clear(self): + self._dict = {} + + def pop(self, key, default=None): + assert key in self._known_keys, '%s not in allowed_keys' % key + return self._dict.pop(key, default) + + @classmethod + def read_from(cls, path, known_keys): + contents = {} + try: + with open(path, 'r') as pid_file: + contents = json.load(pid_file) + except: + if os.path.exists(path): + logging.warn('Failed to read pid file: %s' % path) + return cls(known_keys, contents) + + def write_to(self, path): + try: + with open(path, 'w') as pid_file: + json.dump(self._dict, pid_file, indent=2, sort_keys=True) + except: + logging.warn('Failed to write pid file: %s' % path) + + +# A free function for possible future sharing with a 'load' command. +def _url_from_args(args, pids): + if urlparse.urlparse(args.url_or_path).scheme: + return args.url_or_path + # The load happens on the remote device, use the remote port. + remote_sky_server_port = pids.get('remote_sky_server_port', + pids['sky_server_port']) + return SkyServer.url_for_path(remote_sky_server_port, + pids['sky_server_root'], args.url_or_path) + + +def dev_packages_root(build_dir): + return os.path.join(build_dir, 'gen', 'dart-pkg', 'packages') + + +class SetBuildDir(object): + def add_subparser(self, subparsers): + start_parser = subparsers.add_parser('set_build_dir', + help='force the build_dir to a particular value without starting Sky') + start_parser.add_argument('build_dir', type=str) + start_parser.set_defaults(func=self.run) + + def run(self, args, pids): + pids['build_dir'] = os.path.abspath(args.build_dir) + + +class StartSky(object): + def add_subparser(self, subparsers): + start_parser = subparsers.add_parser('start', + help='launch SkyShell.apk on the device') + start_parser.add_argument('build_dir', type=str) + start_parser.add_argument('--gdb', action="store_true") + start_parser.add_argument('url_or_path', nargs='?', type=str, + default=DEFAULT_URL) + start_parser.add_argument('--no_install', action="store_false", + default=True, dest="install", + help="Don't install SkyDemo.apk before starting") + start_parser.set_defaults(func=self.run) + + def _server_root_for_url(self, url_or_path): + path = os.path.abspath(url_or_path) + if os.path.commonprefix([path, SRC_ROOT]) == SRC_ROOT: + server_root = SRC_ROOT + else: + server_root = os.path.dirname(path) + logging.warn( + '%s is outside of mojo root, using %s as server root' % + (path, server_root)) + return server_root + + def _sky_server_for_args(self, args, packages_root): + server_root = self._server_root_for_url(args.url_or_path) + sky_server = SkyServer(SKY_SERVER_PORT, server_root, packages_root) + return sky_server + + def _find_remote_pid_for_package(self, package): + ps_output = subprocess.check_output([ADB_PATH, 'shell', 'ps']) + for line in ps_output.split('\n'): + fields = line.split() + if fields and fields[-1] == package: + return fields[1] + return None + + def _find_install_location_for_package(self, package): + pm_command = [ADB_PATH, 'shell', 'pm', 'path', package] + pm_output = subprocess.check_output(pm_command) + # e.g. package:/data/app/org.chromium.mojo.shell-1/base.apk + return pm_output.split(':')[-1] + + def run(self, args, pids): + apk_path = os.path.join(args.build_dir, 'apks', APK_NAME) + if not os.path.exists(apk_path): + print "'%s' does not exist?" % apk_path + return 2 + + StopSky().run(args, pids) + + packages_root = dev_packages_root(args.build_dir) + sky_server = self._sky_server_for_args(args, packages_root) + pids['sky_server_pid'] = sky_server.start() + pids['sky_server_port'] = sky_server.port + pids['sky_server_root'] = sky_server.root + + pids['build_dir'] = os.path.abspath(args.build_dir) + + if args.install: + # We might need to install a new APK, so check SHA1 + source_sha1 = hashlib.sha1(open(apk_path, 'rb').read()).hexdigest() + dest_sha1 = subprocess.check_output([ADB_PATH, 'shell', 'cat', SHA1_PATH]) + use_existing_apk = False + if source_sha1 == dest_sha1: + # Make sure that the APK didn't get uninstalled somehow + use_existing_apk = subprocess.check_output([ + ADB_PATH, 'shell', 'pm', 'list', 'packages', ANDROID_PACKAGE + ]) + else: + # User is telling us not to bother installing an APK + use_existing_apk = True + + if use_existing_apk: + # APK is already on the device, we only need to stop it + subprocess.check_call([ + ADB_PATH, 'shell', 'am', 'force-stop', ANDROID_PACKAGE + ]) + else: + # Slow path, need to upload a new APK to the device + # -r to replace an existing apk, -d to allow version downgrade. + subprocess.check_call([ADB_PATH, 'install', '-r', '-d', apk_path]) + # record the SHA1 of the APK we just pushed + with tempfile.NamedTemporaryFile() as fp: + fp.write(source_sha1) + fp.seek(0) + subprocess.check_call([ADB_PATH, 'push', fp.name, SHA1_PATH]) + + # Set up port forwarding for observatory + port_string = 'tcp:%s' % OBSERVATORY_PORT + subprocess.check_call([ + ADB_PATH, 'forward', port_string, port_string + ]) + + port_string = 'tcp:%s' % sky_server.port + subprocess.check_call([ + ADB_PATH, 'reverse', port_string, port_string + ]) + pids['remote_sky_server_port'] = sky_server.port + + subprocess.check_call([ADB_PATH, 'shell', + 'am', 'start', + '-a', 'android.intent.action.VIEW', + '-d', _url_from_args(args, pids), + ANDROID_COMPONENT]) + + if not args.gdb: + return + + # TODO(eseidel): am start -W does not seem to work? + pid_tries = 0 + while True: + pid = self._find_remote_pid_for_package(ANDROID_PACKAGE) + if pid or pid_tries > 3: + break + logging.debug('No pid for %s yet, waiting' % ANDROID_PACKAGE) + time.sleep(5) + pid_tries += 1 + + if not pid: + logging.error('Failed to find pid on device!') + return + + pids['sky_shell_pid'] = pid + + # We push our own copy of gdbserver with the package since + # the default gdbserver is a different version from our gdb. + package_path = \ + self._find_install_location_for_package(ANDROID_PACKAGE) + gdb_server_path = os.path.join( + os.path.dirname(package_path), 'lib/arm/gdbserver') + gdbserver_cmd = [ + ADB_PATH, 'shell', + gdb_server_path, '--attach', + ':%d' % GDB_PORT, + str(pid) + ] + print ' '.join(map(pipes.quote, gdbserver_cmd)) + subprocess.Popen(gdbserver_cmd) + + port_string = 'tcp:%d' % GDB_PORT + subprocess.check_call([ + ADB_PATH, 'forward', port_string, port_string + ]) + pids['remote_gdbserver_port'] = GDB_PORT + + +class GDBAttach(object): + def add_subparser(self, subparsers): + start_parser = subparsers.add_parser('gdb_attach', + help='attach to gdbserver running on device') + start_parser.set_defaults(func=self.run) + + def _pull_system_libraries(self, pids, system_libs_root): + # Pull down the system libraries this pid has already mapped in. + # TODO(eseidel): This does not handle dynamic loads. + library_cacher_path = os.path.join( + SKY_TOOLS_DIR, 'android_library_cacher.py') + subprocess.call([ + library_cacher_path, system_libs_root, pids['sky_shell_pid'] + ]) + + # TODO(eseidel): adb_gdb does, this, unclear why solib-absolute-prefix + # doesn't make this explicit listing not necessary? + return subprocess.check_output([ + 'find', system_libs_root, + '-mindepth', '1', + '-maxdepth', '4', + '-type', 'd', + ]).strip().split('\n') + + def run(self, args, pids): + symbol_search_paths = [ + pids['build_dir'], + ] + gdb_path = '/usr/bin/gdb' + + eval_commands = [ + 'directory %s' % SRC_ROOT, + # TODO(eseidel): What file do I point it at? The apk? + #'file %s' % self.paths.mojo_shell_path, + 'target remote localhost:%s' % GDB_PORT, + ] + + # TODO(iansf): Fix undefined behavior when you have more than one device attached. + device_id = subprocess.check_output([ADB_PATH, 'get-serialno']).strip() + device_libs_path = os.path.join(SYSTEM_LIBS_ROOT_PATH, device_id) + + system_lib_dirs = self._pull_system_libraries(pids, device_libs_path) + eval_commands.append('set solib-absolute-prefix %s' % device_libs_path) + + symbol_search_paths = system_lib_dirs + symbol_search_paths + + # TODO(eseidel): We need to look up the toolchain somehow? + if platform.system() == 'Darwin': + gdb_path = os.path.join(SRC_ROOT, 'third_party/android_tools/ndk/' + 'toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/' + 'bin/arm-linux-androideabi-gdb') + else: + gdb_path = os.path.join(SRC_ROOT, 'third_party/android_tools/ndk/' + 'toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/' + 'bin/arm-linux-androideabi-gdb') + + # Set solib-search-path after letting android modify symbol_search_paths + eval_commands.append( + 'set solib-search-path %s' % ':'.join(symbol_search_paths)) + + exec_command = [gdb_path] + for command in eval_commands: + exec_command += ['--eval-command', command] + + print " ".join(exec_command) + + # Write out our pid file before we exec ourselves. + pids.write_to(PID_FILE_PATH) + + # Exec gdb directly to avoid python intercepting symbols, etc. + os.execv(exec_command[0], exec_command) + + + +class StopSky(object): + def add_subparser(self, subparsers): + stop_parser = subparsers.add_parser('stop', + help=('kill all running SkyShell.apk processes')) + stop_parser.set_defaults(func=self.run) + + def _kill_if_exists(self, pids, key, name): + pid = pids.pop(key, None) + if not pid: + logging.info('No pid for %s, nothing to do.' % name) + return + logging.info('Killing %s (%d).' % (name, pid)) + try: + os.kill(pid, signal.SIGTERM) + except OSError: + logging.info('%s (%d) already gone.' % (name, pid)) + + def _adb_reverse_remove(self, port): + port_string = 'tcp:%s' % port + subprocess.call([ADB_PATH, 'reverse', '--remove', port_string]) + + def _adb_forward_remove(self, port): + port_string = 'tcp:%s' % port + subprocess.call([ADB_PATH, 'forward', '--remove', port_string]) + + def run(self, args, pids): + self._kill_if_exists(pids, 'sky_server_pid', 'sky_server') + + if 'remote_sky_server_port' in pids: + self._adb_reverse_remove(pids['remote_sky_server_port']) + + if 'remote_gdbserver_port' in pids: + self._adb_forward_remove(pids['remote_gdbserver_port']) + + subprocess.call([ + ADB_PATH, 'shell', 'am', 'force-stop', ANDROID_PACKAGE]) + + pids.clear() + + +class Analyze(object): + def add_subparser(self, subparsers): + analyze_parser = subparsers.add_parser('analyze', + help=('run the dart analyzer with sky url mappings')) + analyze_parser.add_argument('app_path', type=str) + analyze_parser.add_argument('--congratulate', action="store_true") + analyze_parser.set_defaults(func=self.run) + + def run(self, args, pids): + build_dir = pids.get('build_dir') + if not build_dir: + logging.fatal("pids file missing build_dir. Try 'start' first.") + return 2 + analyzer_path = os.path.join(SRC_ROOT, 'sky/tools/skyanalyzer') + analyzer_args = [ + analyzer_path, + build_dir, + args.app_path + ] + if args.congratulate: + analyzer_args.append('--congratulate') + try: + output = subprocess.check_output(analyzer_args, stderr=subprocess.STDOUT) + result = 0 + except subprocess.CalledProcessError as e: + output = e.output + result = e.returncode + lines = output.split('\n') + lines.pop() + for line in lines: + print >> sys.stderr, line + return result + + +class StartTracing(object): + def add_subparser(self, subparsers): + start_tracing_parser = subparsers.add_parser('start_tracing', + help=('start tracing a running sky instance')) + start_tracing_parser.set_defaults(func=self.run) + + def run(self, args, pids): + subprocess.check_output([ADB_PATH, 'shell', + 'am', 'broadcast', + '-a', 'org.domokit.sky.demo.TRACING_START']) + + +TRACE_COMPLETE_REGEXP = re.compile('Trace complete') +TRACE_FILE_REGEXP = re.compile(r'Saving trace to (?P\S+)') + +class StopTracing(object): + def add_subparser(self, subparsers): + stop_tracing_parser = subparsers.add_parser('stop_tracing', + help=('stop tracing a running sky instance')) + stop_tracing_parser.set_defaults(func=self.run) + + def run(self, args, pids): + subprocess.check_output([ADB_PATH, 'logcat', '-c']) + subprocess.check_output([ADB_PATH, 'shell', + 'am', 'broadcast', + '-a', 'org.domokit.sky.demo.TRACING_STOP']) + device_path = None + is_complete = False + while not is_complete: + time.sleep(0.2) + log = subprocess.check_output([ADB_PATH, 'logcat', '-d']) + if device_path is None: + result = TRACE_FILE_REGEXP.search(log) + if result: + device_path = result.group('path') + is_complete = TRACE_COMPLETE_REGEXP.search(log) is not None + + print 'Downloading trace %s ...' % os.path.basename(device_path) + + if device_path: + subprocess.check_output([ADB_PATH, 'pull', device_path]) + subprocess.check_output([ADB_PATH, 'shell', 'rm', device_path]) + + +class SkyShellRunner(object): + def main(self): + logging.basicConfig(level=logging.WARNING) + + parser = argparse.ArgumentParser(description='Sky Shell Runner') + subparsers = parser.add_subparsers(help='sub-command help') + + commands = [ + SetBuildDir(), + StartSky(), + StopSky(), + Analyze(), + GDBAttach(), + StartTracing(), + StopTracing(), + ] + + for command in commands: + command.add_subparser(subparsers) + + args = parser.parse_args() + pids = Pids.read_from(PID_FILE_PATH, PID_FILE_KEYS) + exit_code = args.func(args, pids) + # We could do this with an at-exit handler instead? + pids.write_to(PID_FILE_PATH) + sys.exit(exit_code) + + +if __name__ == '__main__': + SkyShellRunner().main() diff --git a/engine/src/flutter/sky/tools/sky_packager.py b/engine/src/flutter/sky/tools/sky_packager.py new file mode 100755 index 0000000000..7131365392 --- /dev/null +++ b/engine/src/flutter/sky/tools/sky_packager.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +# 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 argparse +import subprocess +import sys +import os + +def main(): + parser = argparse.ArgumentParser(description='Sky Packager') + parser.add_argument('executable', type=str) + parser.add_argument('main', type=str) + parser.add_argument('--package-root', type=str) + parser.add_argument('--snapshot', type=str) + parser.add_argument('-C', type=str, + help='Switch to this directory before running executable') + args = parser.parse_args() + return subprocess.check_call([ + args.executable, + args.main, + '--package-root=%s' % args.package_root, + '--snapshot=%s' % args.snapshot, + ], cwd=args.C) + +if __name__ == '__main__': + sys.exit(main()) diff --git a/engine/src/flutter/sky/tools/skyanalyzer b/engine/src/flutter/sky/tools/skyanalyzer new file mode 100755 index 0000000000..2230e72785 --- /dev/null +++ b/engine/src/flutter/sky/tools/skyanalyzer @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# Copyright 2014 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 argparse +import os +import re +import subprocess +import sys + +from skypy.url_mappings import URLMappings + +SKY_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) +SKY_ROOT = os.path.dirname(SKY_TOOLS_DIR) +SRC_ROOT = os.path.dirname(SKY_ROOT) + +_IGNORED_PATTERNS = [ + # Ignored because they're not indicative of specific errors. + re.compile(r'^$'), + re.compile(r'^Analyzing \['), + re.compile(r'^No issues found'), + re.compile(r'^[0-9]+ errors? and [0-9]+ warnings? found.'), + re.compile(r'^([0-9]+|No) (error|warning|issue)s? found.'), + + # Ignore analyzer status output. + re.compile(r'^[0-9]+ errors, [0-9]+ warnings and [0-9]+ hints found.'), + + # Ignored because they don't affect Sky code + re.compile(r'\[hint\] When compiled to JS, this test might return true when the left hand side is an int'), + + # TODO: Remove once sdk-extensions are in place + re.compile(r'^\[error\] Native functions can only be declared in'), + + # TODO: Fix all the warnings in the mojo packages + re.compile(r'.*/dart-pkg/mojom/'), + re.compile(r'.*/dart-pkg/mojo/'), + re.compile(r'.*/mojo/public/dart/'), + + # TODO: Remove this once Sky no longer generates this warning. + # dartbug.com/22836 + re.compile(r'.*cannot both be unnamed'), + + # TODO: Remove this once Sky no longer generates this warning. + # dartbug.com/23606 + re.compile(r'^\[warning] Missing concrete implementation of \'RenderObject.toString\''), +] + +def main(): + parser = argparse.ArgumentParser(description='Sky Analyzer') + parser.add_argument('--congratulate', action="store_true") + parser.add_argument('build_dir', type=str) + parser.add_argument('app_path', type=str) + + args = parser.parse_args() + build_dir = os.path.abspath(args.build_dir) + + url_mappings = URLMappings(SRC_ROOT, build_dir) + analyzer_path = os.path.join(SRC_ROOT, 'third_party/dart-sdk/dart-sdk/bin/dartanalyzer') + packages_root = os.path.join(build_dir, 'gen/dart-pkg/packages') + + analyzer_args = [ + analyzer_path, + "--package-root", packages_root, + "--package-warnings", args.app_path + ] + url_mappings.as_args + + try: + subprocess.check_output(analyzer_args, stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as e: + errors = [l for l in e.output.split('\n') + if not any(p.match(l) for p in _IGNORED_PATTERNS)] + if len(errors) > 0: + for error in errors: + print >> sys.stderr, error + # Propagate analyzer error code. + return e.returncode + # If we do not have any errors left after filtering, return 0. + if args.congratulate: + print >> sys.stdout, "No analyzer warnings!" + return 0 + +if __name__ == '__main__': + sys.exit(main()) diff --git a/engine/src/flutter/sky/tools/skydoc.py b/engine/src/flutter/sky/tools/skydoc.py new file mode 100755 index 0000000000..3ab9e55023 --- /dev/null +++ b/engine/src/flutter/sky/tools/skydoc.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# 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 argparse +import os +import subprocess +import sys + +from skypy.url_mappings import URLMappings + +SKY_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) +SKY_ROOT = os.path.dirname(SKY_TOOLS_DIR) +SRC_ROOT = os.path.dirname(SKY_ROOT) + +DARTDOC = 'dartdoc' + +def main(): + try: + subprocess.check_output([DARTDOC, '--version']) + except: + print 'Cannot find "dartdoc". Did you run `pub global activate dartdoc` ?' + return 1 + + parser = argparse.ArgumentParser(description='Sky Documentation Generator') + parser.add_argument('build_dir', type=str, help='Path to build output') + args = parser.parse_args() + + build_dir = os.path.abspath(args.build_dir) + url_mappings = URLMappings(SRC_ROOT, build_dir) + + packages_root = os.path.join(build_dir, 'gen/dart-pkg/packages') + sky_package = os.path.join(build_dir, 'gen/dart-pkg/sky') + doc_dir = os.path.join(build_dir, 'gen/dart-pkg/sky/doc') + + if not os.path.exists(packages_root): + print 'Cannot find Dart pacakges at "%s".' % packages_root + print 'Did you run `ninja -C %s sky` ?' % os.path.relpath(build_dir, os.getcwd()) + return 1 + + analyzer_args = [ + DARTDOC, + '--package-root', packages_root, + '--input', sky_package, + '--output', doc_dir, + ] + url_mappings.as_args + subprocess.check_call(analyzer_args) + +if __name__ == '__main__': + sys.exit(main()) diff --git a/engine/src/flutter/sky/tools/skygo/README.md b/engine/src/flutter/sky/tools/skygo/README.md new file mode 100644 index 0000000000..715b23994a --- /dev/null +++ b/engine/src/flutter/sky/tools/skygo/README.md @@ -0,0 +1,19 @@ +sky_server instructions +======================= + +Building locally: +1. cd sky/tools/skygo/linux64 (or your current platform) +2. go build ../sky_server.go + +Testing locally: +1. Build as per the above steps +2. Run test_sky --path-to-server /absolute/path/to/sky/tools/skygo/sky_server + +Uploading the locally built server +1. cd sky/tools/skygo/linux64 +2. upload_to_google_storage.py --bucket mojo sky_server + +upload_to_google_storage.py is in depot_tools. It will overwrite +sky_server.sha1. Include that change in your code review. + +linux64/sky_server was last built using go version go1.4.2 linux/amd64. diff --git a/engine/src/flutter/sky/tools/skygo/linux64/sky_server.sha1 b/engine/src/flutter/sky/tools/skygo/linux64/sky_server.sha1 new file mode 100644 index 0000000000..5792045c87 --- /dev/null +++ b/engine/src/flutter/sky/tools/skygo/linux64/sky_server.sha1 @@ -0,0 +1 @@ +925b384cf8e1fa916c51711fd462e85f5f4ad13d \ No newline at end of file diff --git a/engine/src/flutter/sky/tools/skygo/mac/sky_server.sha1 b/engine/src/flutter/sky/tools/skygo/mac/sky_server.sha1 new file mode 100644 index 0000000000..a9f78998be --- /dev/null +++ b/engine/src/flutter/sky/tools/skygo/mac/sky_server.sha1 @@ -0,0 +1 @@ +2c6e5b1818562f98d2697a6c27e16595c0592f41 \ No newline at end of file diff --git a/engine/src/flutter/sky/tools/skygo/sky_server.go b/engine/src/flutter/sky/tools/skygo/sky_server.go new file mode 100644 index 0000000000..3b6ac706c6 --- /dev/null +++ b/engine/src/flutter/sky/tools/skygo/sky_server.go @@ -0,0 +1,100 @@ +// Copyright (c) 2014 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. + +package main + +import ( + "flag" + "fmt" + "io/ioutil" + "net/http" + "os" + "path" + "path/filepath" + "strings" +) + +var verbose bool = false; + +type skyHandlerRoot struct { + root string +} + +func skyHandler(root string) http.Handler { + return &skyHandlerRoot{root} +} + +func (handler *skyHandlerRoot) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/.git") { + w.WriteHeader(http.StatusNotFound) + return + } + path := path.Join(handler.root, r.URL.Path) + + // Remove this one once .sky files are gone: + if strings.HasSuffix(path, ".sky") { + w.Header().Set("Content-Type", "text/sky") + } + + if strings.HasSuffix(path, ".dart") { + w.Header().Set("Content-Type", "application/dart") + } + w.Header().Set("Cache-Control", "no-cache") + http.ServeFile(w, r, path) +} + +func usage() { + fmt.Fprintf(os.Stderr, "Usage: sky_server [flags] MOJO_SRC_ROOT PACKAGE_ROOT\n") + fmt.Fprintf(os.Stderr, "Launches a basic http server with mappings into the mojo repository for framework/service paths.\n") + fmt.Fprintf(os.Stderr, "MOJO_SRC_ROOT must be the root of the Mojo repository.\n") + fmt.Fprintf(os.Stderr, "PACKAGE_ROOT must be the root of your Dart packages (e.g. out/Debug/gen/dart-pkg/packages/).\n") + flag.PrintDefaults() + os.Exit(2) +} + +func addMapping(from_path string, to_path string) { + if (verbose) { + fmt.Fprintf(os.Stderr, " %s -> %s\n", from_path, to_path) + } + http.Handle(from_path, http.StripPrefix(from_path, skyHandler(to_path))) +} + +func setupMappings(mojoRoot string, packageRoot string, port int) { + if (verbose) { + fmt.Fprintf(os.Stderr, "Mappings for localhost:%v:\n", port) + fmt.Fprintf(os.Stderr, " / -> %s\n", mojoRoot) + } + http.Handle("/", skyHandler(mojoRoot)) + + if (verbose) { + fmt.Fprintf(os.Stderr, " /echo_post -> custom echo handler\n") + } + http.HandleFunc("/echo_post", func(w http.ResponseWriter, r *http.Request) { + defer r.Body.Close() + body, _ := ioutil.ReadAll(r.Body) + w.Write(body) + }) + + addMapping("/packages/", packageRoot) +} + +func main() { + var portPtr = flag.Int("p", 8000, "The HTTP port") + var verbosePtr = flag.Bool("v", false, "Verbose mode. Without this flag, the default behaviour only reports errors.") + flag.Parse() + flag.Usage = usage + if flag.NArg() != 2 { + usage() + } + + var port int = *portPtr; + verbose = *verbosePtr; + + root, _ := filepath.Abs(flag.Arg(0)) + packageRoot := flag.Arg(1) + + setupMappings(root, packageRoot, port); + + http.ListenAndServe(fmt.Sprintf(":%v", port), nil) +} diff --git a/engine/src/flutter/sky/tools/skypy/__init__.py b/engine/src/flutter/sky/tools/skypy/__init__.py new file mode 100644 index 0000000000..4d6aabb953 --- /dev/null +++ b/engine/src/flutter/sky/tools/skypy/__init__.py @@ -0,0 +1,3 @@ +# Copyright 2014 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. diff --git a/engine/src/flutter/sky/tools/skypy/configuration.py b/engine/src/flutter/sky/tools/skypy/configuration.py new file mode 100644 index 0000000000..a361d360e8 --- /dev/null +++ b/engine/src/flutter/sky/tools/skypy/configuration.py @@ -0,0 +1,15 @@ +# Copyright 2014 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 optparse + + +def add_arguments(parser): + parser.add_argument("-t", "--target", dest="configuration", + help="Specify the target configuration to use (Debug/Release)", default='Release') + parser.add_argument('--debug', action='store_const', const='Debug', dest="configuration", + help='Set the configuration to Debug') + parser.add_argument('--release', action='store_const', const='Release', dest="configuration", + help='Set the configuration to Release') + diff --git a/engine/src/flutter/sky/tools/skypy/find_tests.py b/engine/src/flutter/sky/tools/skypy/find_tests.py new file mode 100644 index 0000000000..7ea9367c12 --- /dev/null +++ b/engine/src/flutter/sky/tools/skypy/find_tests.py @@ -0,0 +1,20 @@ +# Copyright 2014 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 os + + +IGNORED_DIRECTORIES = ['resources'] +TEST_EXTENSIONS = ['sky'] + + +def find_tests(directory): + for root, dirs, files in os.walk(directory): + for file_name in files: + extension = os.path.splitext(file_name)[1] + if extension.lstrip('.') in TEST_EXTENSIONS: + yield os.path.join(root, file_name) + for ignored_directory in IGNORED_DIRECTORIES: + if ignored_directory in dirs: + dirs.remove(ignored_directory) diff --git a/engine/src/flutter/sky/tools/skypy/paths.py b/engine/src/flutter/sky/tools/skypy/paths.py new file mode 100644 index 0000000000..81b7e99397 --- /dev/null +++ b/engine/src/flutter/sky/tools/skypy/paths.py @@ -0,0 +1,16 @@ +# Copyright 2014 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 os + +# FIXME: All callers should use mopy/paths.py instead! +class Paths(object): + def __init__(self, build_directory): + self.src_root = os.path.abspath(os.path.join(__file__, + os.pardir, os.pardir, os.pardir, os.pardir)) + self.sky_root = os.path.join(self.src_root, 'sky') + self.build_dir = os.path.join(self.src_root, build_directory) + self.gen_root = os.path.join(self.build_dir, 'gen') + self.sky_tools_directory = os.path.join(self.src_root, 'sky', 'tools') + self.mojo_shell_path = os.path.join(self.src_root, build_directory, 'mojo_shell') diff --git a/engine/src/flutter/sky/tools/skypy/skyserver.py b/engine/src/flutter/sky/tools/skypy/skyserver.py new file mode 100644 index 0000000000..499d334dbf --- /dev/null +++ b/engine/src/flutter/sky/tools/skypy/skyserver.py @@ -0,0 +1,79 @@ +# Copyright 2014 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 socket +import subprocess +import logging +import os.path +import stat +import platform + +SKYPY_PATH = os.path.dirname(os.path.abspath(__file__)) +SKY_TOOLS_PATH = os.path.dirname(SKYPY_PATH) +SKYGO_PATH = os.path.join(SKY_TOOLS_PATH, 'skygo') +SKY_ROOT = os.path.dirname(SKY_TOOLS_PATH) +SRC_ROOT = os.path.dirname(SKY_ROOT) + +class SkyServer(object): + def __init__(self, port, root, package_root): + self.port = port + self.root = root + self.package_root = package_root + self.server = None + + @staticmethod + def _port_in_use(port): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + return sock.connect_ex(('localhost', port)) == 0 + + @staticmethod + def sky_server_path(): + + if platform.system() == 'Linux': + platform_dir = 'linux64' + elif platform.system() == 'Darwin': + platform_dir = 'mac' + else: + assert False, 'No sky_server binary for this platform: ' + platform.system() + + return os.path.join(SKYGO_PATH, platform_dir, 'sky_server') + + def start(self): + if self._port_in_use(self.port): + logging.warn( + 'Port %s already in use, assuming custom sky_server started.' % + self.port) + return + + server_path = self.sky_server_path() + st = os.stat(self.sky_server_path()) + if not (stat.S_IXUSR & st[stat.ST_MODE]): + logging.warn('Changing the permissions of %s to be executable.', self.sky_server_path()) + os.chmod(self.sky_server_path(), st[stat.ST_MODE] | stat.S_IEXEC) + server_command = [ + server_path, + '-p', str(self.port), + self.root, + self.package_root, + ] + self.server = subprocess.Popen(server_command) + return self.server.pid + + def stop(self): + if self.server: + self.server.terminate() + + def __enter__(self): + self.start() + + def __exit__(self, exc_type, exc_value, traceback): + self.stop() + + def path_as_url(self, path): + return self.url_for_path(self.port, self.root, path) + + @staticmethod + def url_for_path(port, root, path): + relative_path = os.path.relpath(path, root) + return 'http://localhost:%s/%s' % (port, relative_path) diff --git a/engine/src/flutter/sky/tools/skypy/url_mappings.py b/engine/src/flutter/sky/tools/skypy/url_mappings.py new file mode 100644 index 0000000000..47c48bac86 --- /dev/null +++ b/engine/src/flutter/sky/tools/skypy/url_mappings.py @@ -0,0 +1,20 @@ +# Copyright 2014 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 os + +class URLMappings(object): + def __init__(self, src_root, build_dir): + self.mappings = { + 'dart:mojo.internal': os.path.join(src_root, 'mojo/public/dart/sdk_ext/internal.dart'), + 'dart:sky': os.path.join(build_dir, 'gen/sky/bindings/dart_sky.dart'), + 'dart:sky.internals': os.path.join(src_root, 'sky/engine/bindings/sky_internals.dart'), + 'dart:sky_builtin_natives': os.path.join(src_root, 'sky/engine/bindings/builtin_natives.dart'), + } + self.packages_root = os.path.join(build_dir, 'gen/dart-pkg/packages') + + @property + def as_args(self): + return map(lambda item: '--url-mapping=%s,%s' % item, self.mappings.items()) + \ No newline at end of file diff --git a/engine/src/flutter/sky/tools/skyx.py b/engine/src/flutter/sky/tools/skyx.py new file mode 100755 index 0000000000..07fb84fd7f --- /dev/null +++ b/engine/src/flutter/sky/tools/skyx.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# 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 argparse +import os +import subprocess +import sys + +SKY_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) +SRC_ROOT = os.path.dirname(os.path.dirname(SKY_TOOLS_DIR)) +DART_SDK = os.path.join(SRC_ROOT, 'third_party', 'dart-sdk', 'dart-sdk', 'bin') + +def main(): + parser = argparse.ArgumentParser(description='Packaging tool for Sky apps') + parser.add_argument('--package-root', type=str) + parser.add_argument('--manifest', type=str) + parser.add_argument('--asset-base', type=str) + parser.add_argument('--snapshot', type=str) + parser.add_argument('-o', '--output-file', type=str) + args = parser.parse_args() + + command = [ + os.path.join(DART_SDK, 'dart'), + '--package-root=%s' % args.package_root, + os.path.join(SKY_TOOLS_DIR, 'skyx', 'bin', 'skyx.dart'), + '--asset-base', args.asset_base, + '--snapshot', args.snapshot, + '--output-file', args.output_file, + ] + + if args.manifest: + command += ['--manifest', args.manifest] + + subprocess.check_call(command) + +if __name__ == '__main__': + sys.exit(main()) diff --git a/engine/src/flutter/sky/tools/skyx/.gitignore b/engine/src/flutter/sky/tools/skyx/.gitignore new file mode 100644 index 0000000000..dc1c66d64b --- /dev/null +++ b/engine/src/flutter/sky/tools/skyx/.gitignore @@ -0,0 +1,2 @@ +packages +bin/packages diff --git a/engine/src/flutter/sky/tools/skyx/LICENSE b/engine/src/flutter/sky/tools/skyx/LICENSE new file mode 100644 index 0000000000..972bb2edb0 --- /dev/null +++ b/engine/src/flutter/sky/tools/skyx/LICENSE @@ -0,0 +1,27 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/engine/src/flutter/sky/tools/skyx/bin/skyx.dart b/engine/src/flutter/sky/tools/skyx/bin/skyx.dart new file mode 100644 index 0000000000..897e11ce47 --- /dev/null +++ b/engine/src/flutter/sky/tools/skyx/bin/skyx.dart @@ -0,0 +1,134 @@ +// 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:io'; +import 'dart:async'; + +import 'package:archive/archive.dart'; +import 'package:args/args.dart'; +import 'package:yaml/yaml.dart'; + +const String kSnapshotKey = 'snapshot_blob.bin'; +const List kDensities = const ['drawable-xxhdpi']; +const List kThemes = const ['white', 'black']; +const List kSizes = const [24]; + +class Asset { + final String base; + final String key; + + Asset({ this.base, this.key }); +} + +Iterable parseAssets(Map manifestDescriptor, String manifestPath) sync* { + if (manifestDescriptor == null || !manifestDescriptor.containsKey('assets')) + return; + String basePath = new File(manifestPath).parent.path; + for (String asset in manifestDescriptor['assets']) + yield new Asset(base: basePath, key: asset); +} + +class MaterialAsset { + final String name; + final String density; + final String theme; + final int size; + + MaterialAsset(Map descriptor) + : name = descriptor['name'], + density = descriptor['density'], + theme = descriptor['theme'], + size = descriptor['size']; + + String get key { + List parts = name.split('/'); + String category = parts[0]; + String subtype = parts[1]; + return '$category/$density/ic_${subtype}_${theme}_${size}dp.png'; + } +} + +List generateValues(Map assetDescriptor, String key, List defaults) { + if (assetDescriptor.containsKey(key)) + return [assetDescriptor[key]]; + return defaults; +} + +Iterable generateMaterialAssets(Map assetDescriptor) sync* { + Map currentAssetDescriptor = new Map.from(assetDescriptor); + for (String density in generateValues(assetDescriptor, 'density', kDensities)) { + currentAssetDescriptor['density'] = density; + for (String theme in generateValues(assetDescriptor, 'theme', kThemes)) { + currentAssetDescriptor['theme'] = theme; + for (String size in generateValues(assetDescriptor, 'size', kSizes)) { + currentAssetDescriptor['size'] = size; + yield new MaterialAsset(currentAssetDescriptor); + } + } + } +} + +Iterable parseMaterialAssets(Map manifestDescriptor) sync* { + if (manifestDescriptor == null || !manifestDescriptor.containsKey('material-design-icons')) + return; + for (Map assetDescriptor in manifestDescriptor['material-design-icons']) { + for (MaterialAsset asset in generateMaterialAssets(assetDescriptor)) { + yield asset; + } + } +} + +Future loadManifest(String manifestPath) async { + if (manifestPath == null) + return null; + String manifestDescriptor = await new File(manifestPath).readAsString(); + return loadYaml(manifestDescriptor); +} + +Future createFile(String key, String assetBase) async { + File file = new File('${assetBase}/${key}'); + List content = await file.readAsBytes(); + return new ArchiveFile.noCompress(key, content.length, content); +} + +Future createSnapshotFile(String snapshotPath) async { + File file = new File(snapshotPath); + List content = await file.readAsBytes(); + return new ArchiveFile(kSnapshotKey, content.length, content); +} + +main(List argv) async { + ArgParser parser = new ArgParser(); + parser.addFlag('help', abbr: 'h', negatable: false); + parser.addOption('asset-base'); + parser.addOption('manifest'); + parser.addOption('output-file', abbr: 'o'); + parser.addOption('snapshot'); + + ArgResults args = parser.parse(argv); + if (args['help']) { + print(parser.usage); + return; + } + + String manifestPath = args['manifest']; + Map manifestDescriptor = await loadManifest(manifestPath); + Iterable assets = parseAssets(manifestDescriptor, manifestPath); + Iterable materialAssets = parseMaterialAssets(manifestDescriptor); + + Archive archive = new Archive(); + + String snapshot = args['snapshot']; + if (snapshot != null) + archive.addFile(await createSnapshotFile(snapshot)); + + for (Asset asset in assets) + archive.addFile(await createFile(asset.key, asset.base)); + + for (MaterialAsset asset in materialAssets) + archive.addFile(await createFile(asset.key, args['asset-base'])); + + File outputFile = new File(args['output-file']); + await outputFile.writeAsBytes(new ZipEncoder().encode(archive)); +} diff --git a/engine/src/flutter/sky/tools/skyx/pubspec.yaml b/engine/src/flutter/sky/tools/skyx/pubspec.yaml new file mode 100644 index 0000000000..56c168dcbe --- /dev/null +++ b/engine/src/flutter/sky/tools/skyx/pubspec.yaml @@ -0,0 +1,9 @@ +author: Chromium Authors +dependencies: + archive: '>=1.0.20 <2.0.0' + args: '>=0.13.0 <1.0.0' + yaml: '>=2.1.3 <3.0.0' +description: Developer tool for packaging Sky applications +homepage: https://github.com/domokit/mojo/tree/master/sky/tools/skyx +name: skyx +version: 0.0.1 diff --git a/engine/src/flutter/sky/tools/staticdirindex.py b/engine/src/flutter/sky/tools/staticdirindex.py new file mode 100644 index 0000000000..35eded7fbf --- /dev/null +++ b/engine/src/flutter/sky/tools/staticdirindex.py @@ -0,0 +1,120 @@ +# From http://tools.cherrypy.org/wiki/staticdirindex +# CherryPy code is covered under a BSD License: +# https://bitbucket.org/cherrypy/cherrypy/src/697c7af588b8/cherrypy/LICENSE.txt + +import os +import re +import stat +import urllib +import cherrypy +from cherrypy.lib import cptools, http + +# Undercover kludge to wrap staticdir +from cherrypy.lib.static import staticdir + +def staticdirindex(section, dir, root="", match="", content_types=None, + index="", indexlistermatch="", indexlister=None, **kwargs): + """Serve a directory index listing for a dir. + + Compatibility alert: staticdirindex is built on and is dependent on + staticdir and its configurations. staticdirindex only works effectively + in locations where staticdir is also configured. staticdirindex is + coded to allow easy integration with staticdir, if demand warrants. + + indexlister must be configured, or no function is performed. + indexlister should be a callable that accepts the following parameters: + section: same as for staticdir (and implicitly calculated for it) + dir: same as for staticdir, but already combined with root + path: combination of section and dir + + Other parameters that are configured for staticdirindex will be passed + on to indexlister. + + Should use priorty > than that of staticdir, so that only directories not + served by staticdir, call staticdirindex. + +""" + # first call old staticdir, and see if it does anything + sdret = staticdir( section, dir, root, match, content_types, index ) + if sdret: + return True + + # if not, then see if we are configured to do anything + if indexlister is None: + return False + + req = cherrypy.request + response = cherrypy.response + + match = indexlistermatch + + # N.B. filename ending in a slash or not does not imply a directory + # the following block of code directly copied from static.py staticdir + if match and not re.search(match, cherrypy.request.path_info): + return False + + # Allow the use of '~' to refer to a user's home directory. + dir = os.path.expanduser(dir) + + # If dir is relative, make absolute using "root". + if not os.path.isabs(dir): + if not root: + msg = "Static dir requires an absolute dir (or root)." + raise ValueError(msg) + dir = os.path.join(root, dir) + + # Determine where we are in the object tree relative to 'section' + # (where the static tool was defined). + if section == 'global': + section = "/" + section = section.rstrip(r"\/") + branch = cherrypy.request.path_info[len(section) + 1:] + branch = urllib.unquote(branch.lstrip(r"\/")) + + # If branch is "", filename will end in a slash + filename = os.path.join(dir, branch) + + # There's a chance that the branch pulled from the URL might + # have ".." or similar uplevel attacks in it. Check that the final + # filename is a child of dir. + if not os.path.normpath(filename).startswith(os.path.normpath(dir)): + raise cherrypy.HTTPError(403) # Forbidden + # the above block of code directly copied from static.py staticdir + # N.B. filename ending in a slash or not does not imply a directory + + # Check if path is a directory. + + path = filename + # The following block of code copied from static.py serve_file + + # If path is relative, users should fix it by making path absolute. + # That is, CherryPy should not guess where the application root is. + # It certainly should *not* use cwd (since CP may be invoked from a + # variety of paths). If using tools.static, you can make your relative + # paths become absolute by supplying a value for "tools.static.root". + if not os.path.isabs(path): + raise ValueError("'%s' is not an absolute path." % path) + + try: + st = os.stat(path) + except OSError: + # The above block of code copied from static.py serve_file + + return False + + if stat.S_ISDIR(st.st_mode): + + # Set the Last-Modified response header, so that + # modified-since validation code can work. + response.headers['Last-Modified'] = http.HTTPDate(st.st_mtime) + cptools.validate_since() + response.body = indexlister( section=section, dir=dir, path=path, + **kwargs ) + response.headers['Content-Type'] = 'text/html' + req.is_index = True + return True + + return False + +# Replace the real staticdir with our version +cherrypy.tools.staticdir = cherrypy._cptools.HandlerTool( staticdirindex ) diff --git a/engine/src/flutter/sky/tools/test_bindings b/engine/src/flutter/sky/tools/test_bindings new file mode 100755 index 0000000000..1cba1c0c1a --- /dev/null +++ b/engine/src/flutter/sky/tools/test_bindings @@ -0,0 +1,50 @@ +#!/usr/bin/python +# Copyright (C) 2010 Google Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY +# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +import sys + +from webkitpy.bindings.main import run_bindings_tests + +def main(argv): + """Runs Blink bindings IDL compiler on test IDL files and compares the + results with reference files. + + Please execute the script whenever changes are made to the compiler + (this is automatically done as a presubmit script), + and submit changes to the test results in the same patch. + This makes it easier to track and review changes in generated code. + + Options: + --reset-results: Overwrites reference files with the generated results. + --verbose: Show output on success and logging messages (not just failure) + """ + reset_results = '--reset-results' in argv + verbose = '--verbose' in argv + + return run_bindings_tests(reset_results, verbose) + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/engine/src/flutter/sky/tools/test_perf b/engine/src/flutter/sky/tools/test_perf new file mode 100755 index 0000000000..ad38475da0 --- /dev/null +++ b/engine/src/flutter/sky/tools/test_perf @@ -0,0 +1,130 @@ +#!/usr/bin/env python +# Copyright 2014 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. + +from skypy.find_tests import find_tests +from skypy.paths import Paths +import argparse +import os +import re +import requests +import skypy.configuration as configuration +import skypy.skyserver +import subprocess + + +SUPPORTED_MIME_TYPES = [ + 'text/sky', + 'application/dart', +] +HTTP_PORT = 9999 +URL_ROOT = 'http://localhost:%s/' % HTTP_PORT +DASHBOARD_URL = 'https://chromeperf.appspot.com/add_point' +BENCHMARKS_DIR = 'benchmarks' + + +def values_from_output(output): + # Parse out the raw values from the PerfRunner output: + # values 90, 89, 93 ms + # We'll probably need a fancier parser at some point. + match = re.search(r'values (.+) ms', output, flags=re.MULTILINE) + return map(float, match.group(1).split(', ')) + + +def create_json_blob(values): + revision = subprocess.check_output(["git", "show-ref", "HEAD", "-s"]).strip() + return { + "master": "master.mojo.perf", + "bot": "sky-release", + "point_id": 123456, # FIXME: We need to generate a monotonicly increasing number somehow. + "versions": { + "mojo": revision + }, + "chart_data": { + "format_version": "1.0", + "benchmark_name": "layout.simple-blocks", + "charts": { + "warm_times": { + "traces": { + "layout.simple-blocks": { + "type": "list_of_scalar_values", + "values": values, + }, + } + } + } + } + } + + +def send_json_to_dashboard(json): + requests.post(DASHBOARD_URL, params={ 'data': json }) + + +class PerfHarness(object): + def __init__(self, args): + self._sky_server = None + self.paths = Paths(os.path.join('out', 'Debug')) + self.args = args + + def _start_server(self): + # TODO(eseidel): Shouldn't this just use skyserver.py? + return subprocess.Popen([ + SkyServer.sky_server_path(), + self.paths.src_root, + str(HTTP_PORT), + '-t', self.args.configuration + ]) + + def _sky_tester_command(self, url): + content_handlers = ['%s,%s' % (mime_type, 'mojo:sky_viewer') + for mime_type in SUPPORTED_MIME_TYPES] + return [ + self.paths.mojo_shell_path, + '--args-for=mojo:native_viewport_service --use-headless-config --use-osmesa', + '--args-for=mojo:window_manager %s' % url, + '--content-handlers=%s' % ','.join(content_handlers), + '--url-mappings=mojo:window_manager=mojo:sky_tester', + 'mojo:window_manager', + ] + + def _url_for_path(self, path): + return URL_ROOT + os.path.relpath(path, self.paths.src_root) + + def _run_tests(self, path): + url = self._url_for_path(path) + output = subprocess.check_output( + self._sky_tester_command(url), + stderr=subprocess.STDOUT) + values = values_from_output(output) + print os.path.basename(path), "=>", values + # FIXME: Upload JSON blob to results server: + # json = create_json_blob(values) + # send_json_to_dashboard(json) + + def main(self): + self._start_server() + map(self._run_tests, find_tests(os.path.join(self.paths.sky_root, BENCHMARKS_DIR))) + + def shutdown(self): + if self._sky_server: + self._sky_server.terminate() + + +def main(): + parser = argparse.ArgumentParser(description='Sky performance tester') + configuration.add_arguments(parser) + args = parser.parse_args() + + harness = PerfHarness(args) + try: + harness.main() + except (KeyboardInterrupt, SystemExit): + pass + finally: + harness.shutdown() + + +if __name__ == '__main__': + main() diff --git a/engine/src/flutter/sky/tools/test_sky b/engine/src/flutter/sky/tools/test_sky new file mode 100755 index 0000000000..4d6826e8f0 --- /dev/null +++ b/engine/src/flutter/sky/tools/test_sky @@ -0,0 +1,33 @@ +#!/usr/bin/env python +# Copyright (C) 2012 Google Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Wrapper around webkitpy/layout_tests/run_webkit_tests.py""" +from webkitpy.common import multiprocessing_bootstrap + +multiprocessing_bootstrap.run('webkitpy', 'layout_tests', 'run_webkit_tests.py') diff --git a/engine/src/flutter/sky/tools/test_webkitpy b/engine/src/flutter/sky/tools/test_webkitpy new file mode 100755 index 0000000000..ee682cccf0 --- /dev/null +++ b/engine/src/flutter/sky/tools/test_webkitpy @@ -0,0 +1,32 @@ +#!/usr/bin/env python +# Copyright (c) 2011 Google Inc. All rights reserved. +# Copyright (C) 2010 Chris Jerdonek (cjerdonek@webkit.org) +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +from webkitpy.common import multiprocessing_bootstrap + +multiprocessing_bootstrap.run('webkitpy', 'test', 'main.py') diff --git a/engine/src/flutter/sky/tools/third_party/PrettyPatch/PrettyPatch.rb b/engine/src/flutter/sky/tools/third_party/PrettyPatch/PrettyPatch.rb new file mode 100644 index 0000000000..ee3543eecb --- /dev/null +++ b/engine/src/flutter/sky/tools/third_party/PrettyPatch/PrettyPatch.rb @@ -0,0 +1,1005 @@ +require 'cgi' +require 'diff' +require 'open3' +require 'open-uri' +require 'pp' +require 'set' +require 'tempfile' + +module PrettyPatch + +public + + GIT_PATH = "git" + + def self.prettify(string) + $last_prettify_file_count = -1 + $last_prettify_part_count = { "remove" => 0, "add" => 0, "shared" => 0, "binary" => 0, "extract-error" => 0 } + string = normalize_line_ending(string) + str = "#{HEADER}\n" + + # Just look at the first line to see if it is an SVN revision number as added + # by webkit-patch for git checkouts. + $svn_revision = 0 + string.each_line do |line| + match = /^Subversion\ Revision: (\d*)$/.match(line) + unless match.nil? + str << "#{match[1]}\n" + $svn_revision = match[1].to_i; + end + break + end + + fileDiffs = FileDiff.parse(string) + + $last_prettify_file_count = fileDiffs.length + str << fileDiffs.collect{ |diff| diff.to_html }.join + str << "" + end + + def self.filename_from_diff_header(line) + DIFF_HEADER_FORMATS.each do |format| + match = format.match(line) + return match[1] unless match.nil? + end + nil + end + + def self.diff_header?(line) + RELAXED_DIFF_HEADER_FORMATS.any? { |format| line =~ format } + end + +private + DIFF_HEADER_FORMATS = [ + /^Index: (.*)\r?$/, + /^diff --git "?a\/.+"? "?b\/(.+)"?\r?$/, + /^\+\+\+ ([^\t]+)(\t.*)?\r?$/ + ] + + RELAXED_DIFF_HEADER_FORMATS = [ + /^Index:/, + /^diff/ + ] + + BINARY_FILE_MARKER_FORMAT = /^Cannot display: file marked as a binary type.$/ + + IMAGE_FILE_MARKER_FORMAT = /^svn:mime-type = image\/png$/ + + GIT_INDEX_MARKER_FORMAT = /^index ([0-9a-f]{40})\.\.([0-9a-f]{40})/ + + GIT_BINARY_FILE_MARKER_FORMAT = /^GIT binary patch$/ + + GIT_BINARY_PATCH_FORMAT = /^(literal|delta) \d+$/ + + GIT_LITERAL_FORMAT = /^literal \d+$/ + + GIT_DELTA_FORMAT = /^delta \d+$/ + + START_OF_BINARY_DATA_FORMAT = /^[0-9a-zA-Z\+\/=]{20,}/ # Assume 20 chars without a space is base64 binary data. + + START_OF_SECTION_FORMAT = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@\s*(.*)/ + + START_OF_EXTENT_STRING = "%c" % 0 + END_OF_EXTENT_STRING = "%c" % 1 + + # We won't search for intra-line diffs in lines longer than this length, to avoid hangs. See . + MAXIMUM_INTRALINE_DIFF_LINE_LENGTH = 10000 + + SMALLEST_EQUAL_OPERATION = 3 + + OPENSOURCE_URL = "http://src.chromium.org/viewvc/blink/" + + OPENSOURCE_DIRS = Set.new %w[ + tests + PerformanceTests + engine + Tools + ] + + IMAGE_CHECKSUM_ERROR = "INVALID: Image lacks a checksum. This will fail with a MISSING error in run-webkit-tests. Always generate new png files using run-webkit-tests." + + def self.normalize_line_ending(s) + if RUBY_VERSION >= "1.9" + # Transliteration table from http://stackoverflow.com/a/6609998 + transliteration_table = { '\xc2\x82' => ',', # High code comma + '\xc2\x84' => ',,', # High code double comma + '\xc2\x85' => '...', # Tripple dot + '\xc2\x88' => '^', # High carat + '\xc2\x91' => '\x27', # Forward single quote + '\xc2\x92' => '\x27', # Reverse single quote + '\xc2\x93' => '\x22', # Forward double quote + '\xc2\x94' => '\x22', # Reverse double quote + '\xc2\x95' => ' ', + '\xc2\x96' => '-', # High hyphen + '\xc2\x97' => '--', # Double hyphen + '\xc2\x99' => ' ', + '\xc2\xa0' => ' ', + '\xc2\xa6' => '|', # Split vertical bar + '\xc2\xab' => '<<', # Double less than + '\xc2\xbb' => '>>', # Double greater than + '\xc2\xbc' => '1/4', # one quarter + '\xc2\xbd' => '1/2', # one half + '\xc2\xbe' => '3/4', # three quarters + '\xca\xbf' => '\x27', # c-single quote + '\xcc\xa8' => '', # modifier - under curve + '\xcc\xb1' => '' # modifier - under line + } + encoded_string = s.force_encoding('UTF-8').encode('UTF-16', :invalid => :replace, :replace => '', :fallback => transliteration_table).encode('UTF-8') + encoded_string.gsub /\r\n?/, "\n" + else + s.gsub /\r\n?/, "\n" + end + end + + def self.find_url_and_path(file_path) + # Search file_path from the bottom up, at each level checking whether + # we've found a directory we know exists in the source tree. + + dirname, basename = File.split(file_path) + dirname.split(/\//).reverse.inject(basename) do |path, directory| + path = directory + "/" + path + + return [OPENSOURCE_URL, path] if OPENSOURCE_DIRS.include?(directory) + + path + end + + [nil, file_path] + end + + def self.linkifyFilename(filename) + url, pathBeneathTrunk = find_url_and_path(filename) + + url.nil? ? filename : "#{filename}" + end + + + HEADER =< + + + +EOF + + def self.revisionOrDescription(string) + case string + when /\(revision \d+\)/ + /\(revision (\d+)\)/.match(string)[1] + when /\(.*\)/ + /\((.*)\)/.match(string)[1] + end + end + + def self.has_image_suffix(filename) + filename =~ /\.(png|jpg|gif)$/ + end + + class FileDiff + def initialize(lines) + @filename = PrettyPatch.filename_from_diff_header(lines[0].chomp) + startOfSections = 1 + for i in 0...lines.length + case lines[i] + when /^--- / + @from = PrettyPatch.revisionOrDescription(lines[i]) + when /^\+\+\+ / + @filename = PrettyPatch.filename_from_diff_header(lines[i].chomp) if @filename.nil? + @to = PrettyPatch.revisionOrDescription(lines[i]) + startOfSections = i + 1 + break + when BINARY_FILE_MARKER_FORMAT + @binary = true + if (IMAGE_FILE_MARKER_FORMAT.match(lines[i + 1]) or PrettyPatch.has_image_suffix(@filename)) then + @image = true + startOfSections = i + 2 + for x in startOfSections...lines.length + # Binary diffs often have property changes listed before the actual binary data. Skip them. + if START_OF_BINARY_DATA_FORMAT.match(lines[x]) then + startOfSections = x + break + end + end + end + break + when GIT_INDEX_MARKER_FORMAT + @git_indexes = [$1, $2] + when GIT_BINARY_FILE_MARKER_FORMAT + @binary = true + if (GIT_BINARY_PATCH_FORMAT.match(lines[i + 1]) and PrettyPatch.has_image_suffix(@filename)) then + @git_image = true + startOfSections = i + 1 + end + break + end + end + lines_with_contents = lines[startOfSections...lines.length] + @sections = DiffSection.parse(lines_with_contents) unless @binary + if @image and not lines_with_contents.empty? + @image_url = "data:image/png;base64," + lines_with_contents.join + @image_checksum = FileDiff.read_checksum_from_png(lines_with_contents.join.unpack("m").join) + elsif @git_image + begin + raise "index line is missing" unless @git_indexes + + chunks = nil + for i in 0...lines_with_contents.length + if lines_with_contents[i] =~ /^$/ + chunks = [lines_with_contents[i + 1 .. -1], lines_with_contents[0 .. i]] + break + end + end + + raise "no binary chunks" unless chunks + + from_filepath = FileDiff.extract_contents_of_from_revision(@filename, chunks[0], @git_indexes[0]) + to_filepath = FileDiff.extract_contents_of_to_revision(@filename, chunks[1], @git_indexes[1], from_filepath, @git_indexes[0]) + filepaths = from_filepath, to_filepath + + binary_contents = filepaths.collect { |filepath| File.exists?(filepath) ? File.read(filepath) : nil } + @image_urls = binary_contents.collect { |content| (content and not content.empty?) ? "data:image/png;base64," + [content].pack("m") : nil } + @image_checksums = binary_contents.collect { |content| FileDiff.read_checksum_from_png(content) } + rescue + $last_prettify_part_count["extract-error"] += 1 + @image_error = "Exception raised during decoding git binary patch:
#{CGI.escapeHTML($!.to_s + "\n" + $!.backtrace.join("\n"))}
" + ensure + File.unlink(from_filepath) if (from_filepath and File.exists?(from_filepath)) + File.unlink(to_filepath) if (to_filepath and File.exists?(to_filepath)) + end + end + nil + end + + def image_to_html + if not @image_url then + return "Image file removed" + end + + image_checksum = "" + if @image_checksum + image_checksum = @image_checksum + elsif @filename.include? "-expected.png" and @image_url + image_checksum = IMAGE_CHECKSUM_ERROR + end + + return "

" + image_checksum + "

" + end + + def to_html + str = "
\n" + str += "

#{PrettyPatch.linkifyFilename(@filename)}

\n" + if @image then + str += self.image_to_html + elsif @git_image then + if @image_error + str += @image_error + else + for i in (0...2) + image_url = @image_urls[i] + image_checksum = @image_checksums[i] + + style = ["remove", "add"][i] + str += "

" + + if image_checksum + str += image_checksum + elsif @filename.include? "-expected.png" and image_url + str += IMAGE_CHECKSUM_ERROR + end + + str += "
" + + if image_url + str += "" + else + str += ["

Added", "

Removed"][i] + end + end + end + elsif @binary then + $last_prettify_part_count["binary"] += 1 + str += "Binary file, nothing to see here" + else + str += @sections.collect{ |section| section.to_html }.join("
\n") unless @sections.nil? + end + + if @from then + str += "" + @from + "" + end + + str += "
\n" + end + + def self.parse(string) + haveSeenDiffHeader = false + linesForDiffs = [] + string.each_line do |line| + if (PrettyPatch.diff_header?(line)) + linesForDiffs << [] + haveSeenDiffHeader = true + elsif (!haveSeenDiffHeader && line =~ /^--- /) + linesForDiffs << [] + haveSeenDiffHeader = false + end + linesForDiffs.last << line unless linesForDiffs.last.nil? + end + + linesForDiffs.collect { |lines| FileDiff.new(lines) } + end + + def self.read_checksum_from_png(png_bytes) + # Ruby 1.9 added the concept of string encodings, so to avoid treating binary data as UTF-8, + # we can force the encoding to binary at this point. + if RUBY_VERSION >= "1.9" + png_bytes.force_encoding('binary') + end + match = png_bytes && png_bytes.match(/tEXtchecksum\0([a-fA-F0-9]{32})/) + match ? match[1] : nil + end + + def self.git_new_file_binary_patch(filename, encoded_chunk, git_index) + return <= 1 or raise "DiffSection.parse only received %d lines" % lines.length + + matches = START_OF_SECTION_FORMAT.match(lines[0]) + + if matches + from, to = [matches[1].to_i, matches[3].to_i] + if matches[2] and matches[4] + from_end = from + matches[2].to_i + to_end = to + matches[4].to_i + end + end + + @blocks = [] + diff_block = nil + diff_block_part = nil + + for line in lines[1...lines.length] + startOfLine = line =~ /^[-\+ ]/ ? 1 : 0 + text = line[startOfLine...line.length].chomp + case line[0] + when ?- + if (diff_block_part.nil? or diff_block_part.className != 'remove') + diff_block = DiffBlock.new(@blocks) + diff_block_part = DiffBlockPart.new('remove', diff_block) + end + + diff_block_part.lines << CodeLine.new(from, nil, text) + from += 1 unless from.nil? + when ?+ + if (diff_block_part.nil? or diff_block_part.className != 'add') + # Put add lines that immediately follow remove lines into the same DiffBlock. + if (diff_block.nil? or diff_block_part.className != 'remove') + diff_block = DiffBlock.new(@blocks) + end + + diff_block_part = DiffBlockPart.new('add', diff_block) + end + + diff_block_part.lines << CodeLine.new(nil, to, text) + to += 1 unless to.nil? + else + if (diff_block_part.nil? or diff_block_part.className != 'shared') + diff_block = DiffBlock.new(@blocks) + diff_block_part = DiffBlockPart.new('shared', diff_block) + end + + diff_block_part.lines << CodeLine.new(from, to, text) + from += 1 unless from.nil? + to += 1 unless to.nil? + end + + break if from_end and to_end and from == from_end and to == to_end + end + + changes = [ [ [], [] ] ] + for block in @blocks + for block_part in block.parts + for line in block_part.lines + if (!line.fromLineNumber.nil? and !line.toLineNumber.nil?) then + changes << [ [], [] ] + next + end + changes.last.first << line if line.toLineNumber.nil? + changes.last.last << line if line.fromLineNumber.nil? + end + end + end + + for change in changes + next unless change.first.length == change.last.length + for i in (0...change.first.length) + from_text = change.first[i].text + to_text = change.last[i].text + next if from_text.length > MAXIMUM_INTRALINE_DIFF_LINE_LENGTH or to_text.length > MAXIMUM_INTRALINE_DIFF_LINE_LENGTH + raw_operations = HTMLDiff::DiffBuilder.new(from_text, to_text).operations + operations = [] + back = 0 + raw_operations.each_with_index do |operation, j| + if operation.action == :equal and j < raw_operations.length - 1 + length = operation.end_in_new - operation.start_in_new + if length < SMALLEST_EQUAL_OPERATION + back = length + next + end + end + operation.start_in_old -= back + operation.start_in_new -= back + back = 0 + operations << operation + end + change.first[i].operations = operations + change.last[i].operations = operations + end + end + + @blocks.unshift(ContextLine.new(matches[5])) unless matches.nil? || matches[5].empty? + end + + def to_html + str = "
\n" + str += @blocks.collect{ |block| block.to_html }.join + str += "
\n" + end + + def self.parse(lines) + linesForSections = lines.inject([[]]) do |sections, line| + sections << [] if line =~ /^@@/ + sections.last << line + sections + end + + linesForSections.delete_if { |lines| lines.nil? or lines.empty? } + linesForSections.collect { |lines| DiffSection.new(lines) } + end + end + + class Line + attr_reader :fromLineNumber + attr_reader :toLineNumber + attr_reader :text + + def initialize(from, to, text) + @fromLineNumber = from + @toLineNumber = to + @text = text + end + + def text_as_html + CGI.escapeHTML(text) + end + + def classes + lineClasses = ["Line", "LineContainer"] + lineClasses << ["add"] unless @toLineNumber.nil? or !@fromLineNumber.nil? + lineClasses << ["remove"] unless @fromLineNumber.nil? or !@toLineNumber.nil? + lineClasses + end + + def to_html + markedUpText = self.text_as_html + str = "
\n" % self.classes.join(' ') + str += "%s%s" % + [@fromLineNumber.nil? ? ' ' : @fromLineNumber, + @toLineNumber.nil? ? ' ' : @toLineNumber] unless @fromLineNumber.nil? and @toLineNumber.nil? + str += "%s\n" % markedUpText + str += "
\n" + end + end + + class CodeLine < Line + attr :operations, true + + def text_as_html + html = [] + tag = @fromLineNumber.nil? ? "ins" : "del" + if @operations.nil? or @operations.empty? + return CGI.escapeHTML(@text) + end + @operations.each do |operation| + start = @fromLineNumber.nil? ? operation.start_in_new : operation.start_in_old + eend = @fromLineNumber.nil? ? operation.end_in_new : operation.end_in_old + escaped_text = CGI.escapeHTML(@text[start...eend]) + if eend - start === 0 or operation.action === :equal + html << escaped_text + else + html << "<#{tag}>#{escaped_text}" + end + end + html.join + end + end + + class ContextLine < Line + def initialize(context) + super("@", "@", context) + end + + def classes + super << "context" + end + end +end diff --git a/engine/src/flutter/sky/tools/third_party/PrettyPatch/PrettyPatch_test.rb b/engine/src/flutter/sky/tools/third_party/PrettyPatch/PrettyPatch_test.rb new file mode 100755 index 0000000000..0d5f94395a --- /dev/null +++ b/engine/src/flutter/sky/tools/third_party/PrettyPatch/PrettyPatch_test.rb @@ -0,0 +1,99 @@ +#!/usr/bin/ruby + +require 'test/unit' +require 'open-uri' +require 'PrettyPatch' + +# Note: internet connection is needed to run this test suite. + +class PrettyPatch_test < Test::Unit::TestCase + class Info + TITLE = 0 + FILE = 1 + ADD = 2 + REMOVE = 3 + SHARED = 4 + end + + PATCHES = { + 20510 => ["Single change", 1, 1, 0, 2], + 20528 => ["No 'Index' or 'diff' in patch header", 1, 4, 3, 7], + 21151 => ["Leading '/' in the path of files", 4, 9, 1, 16], + # Binary files use shared blocks, there are three in 30488. + 30488 => ["Quoted filenames in git diff", 23, 28, 25, 64 + 3], + 23920 => ["Mac line ending", 3, 3, 0, 5], + 39615 => ["Git signature", 2, 2, 0, 3], + 80852 => ["Changes one line plus ChangeLog", 2, 2, 1, 4], + 83127 => ["Only add stuff", 2, 2, 0, 3], + 85071 => ["Adds and removes from a file plus git signature", 2, 5, 3, 9], + 106368 => ["Images with git delta binary patch", 69, 8, 23, 10], + } + + def get_patch_uri(id) + "https://bugs.webkit.org/attachment.cgi?id=" + id.to_s + end + + def get_patch(id) + result = nil + patch_uri = get_patch_uri(id) + begin + result = open(patch_uri) { |f| result = f.read } + rescue => exception + assert(false, "Fail to get patch " + patch_uri) + end + result + end + + def check_one_patch(id, info) + patch = get_patch(id) + description = get_patch_uri(id) + description += " (" + info[Info::TITLE] + ")" unless info[Info::TITLE].nil? + puts "Testing " + description + pretty = nil + assert_nothing_raised("Crash while prettifying " + description) { + pretty = PrettyPatch.prettify(patch) + } + assert(pretty, "Empty result while prettifying " + description) + assert_equal(info[Info::FILE], $last_prettify_file_count, "Wrong number of files changed in " + description) + assert_equal(info[Info::ADD], $last_prettify_part_count["add"], "Wrong number of 'add' parts in " + description) + assert_equal(info[Info::REMOVE], $last_prettify_part_count["remove"], "Wrong number of 'remove' parts in " + description) + assert_equal(info[Info::SHARED], $last_prettify_part_count["shared"], "Wrong number of 'shared' parts in " + description) + assert_equal(0, $last_prettify_part_count["binary"], "Wrong number of 'binary' parts in " + description) + assert_equal(0, $last_prettify_part_count["extract-error"], "Wrong number of 'extract-error' parts in " + description) + return pretty + end + + def test_patches + PATCHES.each { |id, info| check_one_patch(id, info) } + end + + def test_images_without_checksum + pretty = check_one_patch(144064, ["Images without checksums", 10, 5, 4, 8]) + matches = pretty.match("INVALID: Image lacks a checksum.") + # FIXME: This should match, but there's a bug when running the tests where the image data + # doesn't get properly written out to the temp files, so there is no image and we don't print + # the warning that the image is missing its checksum. + assert(!matches, "Should have invalid checksums") + # FIXME: This should only have 4 invalid images, but due to the above tempfile issue, there are 0. + assert_equal(0, pretty.scan(/INVALID\: Image lacks a checksum\./).size) + end + + def test_new_image + pretty = check_one_patch(145881, ["New image", 19, 36, 19, 56]) + matches = pretty.match("INVALID: Image lacks a checksum.") + assert(!matches, "Should not have invalid checksums") + end + + def test_images_correctly_without_checksum_git + pretty = check_one_patch(101620, ["Images correctly without checksums git", 7, 15, 10, 26]) + matches = pretty.match("INVALID: Image lacks a checksum.") + assert(!matches, "Png should lack a checksum without an error.") + end + + def test_images_correctly_without_checksum_svn + pretty = check_one_patch(31202, ["Images correctly without checksums svn", 4, 4, 1, 4]) + matches = pretty.match("INVALID: Image lacks a checksum.") + assert(!matches, "Png should lack a checksum without an error.") + end + +end diff --git a/engine/src/flutter/sky/tools/third_party/PrettyPatch/diff.rb b/engine/src/flutter/sky/tools/third_party/PrettyPatch/diff.rb new file mode 100644 index 0000000000..e5c154a616 --- /dev/null +++ b/engine/src/flutter/sky/tools/third_party/PrettyPatch/diff.rb @@ -0,0 +1,164 @@ +module HTMLDiff + + Match = Struct.new(:start_in_old, :start_in_new, :size) + class Match + def end_in_old + self.start_in_old + self.size + end + + def end_in_new + self.start_in_new + self.size + end + end + + Operation = Struct.new(:action, :start_in_old, :end_in_old, :start_in_new, :end_in_new) + + class DiffBuilder + + def initialize(old_version, new_version) + @old_version, @new_version = old_version, new_version + split_inputs_to_words + index_new_words + end + + def split_inputs_to_words + @old_words = explode(@old_version) + @new_words = explode(@new_version) + end + + def index_new_words + @word_indices = Hash.new { |h, word| h[word] = [] } + @new_words.each_with_index { |word, i| @word_indices[word] << i } + end + + def operations + position_in_old = position_in_new = 0 + operations = [] + + matches = matching_blocks + # an empty match at the end forces the loop below to handle the unmatched tails + # I'm sure it can be done more gracefully, but not at 23:52 + matches << Match.new(@old_words.length, @new_words.length, 0) + + matches.each_with_index do |match, i| + match_starts_at_current_position_in_old = (position_in_old == match.start_in_old) + match_starts_at_current_position_in_new = (position_in_new == match.start_in_new) + + action_upto_match_positions = + case [match_starts_at_current_position_in_old, match_starts_at_current_position_in_new] + when [false, false] + :replace + when [true, false] + :insert + when [false, true] + :delete + else + # this happens if the first few words are same in both versions + :none + end + + if action_upto_match_positions != :none + operation_upto_match_positions = + Operation.new(action_upto_match_positions, + position_in_old, match.start_in_old, + position_in_new, match.start_in_new) + operations << operation_upto_match_positions + end + if match.size != 0 + match_operation = Operation.new(:equal, + match.start_in_old, match.end_in_old, + match.start_in_new, match.end_in_new) + operations << match_operation + end + + position_in_old = match.end_in_old + position_in_new = match.end_in_new + end + + operations + end + + def matching_blocks + matching_blocks = [] + recursively_find_matching_blocks(0, @old_words.size, 0, @new_words.size, matching_blocks) + matching_blocks + end + + def recursively_find_matching_blocks(start_in_old, end_in_old, start_in_new, end_in_new, matching_blocks) + match = find_match(start_in_old, end_in_old, start_in_new, end_in_new) + if match + if start_in_old < match.start_in_old and start_in_new < match.start_in_new + recursively_find_matching_blocks( + start_in_old, match.start_in_old, start_in_new, match.start_in_new, matching_blocks) + end + matching_blocks << match + if match.end_in_old < end_in_old and match.end_in_new < end_in_new + recursively_find_matching_blocks( + match.end_in_old, end_in_old, match.end_in_new, end_in_new, matching_blocks) + end + end + end + + def find_match(start_in_old, end_in_old, start_in_new, end_in_new) + + best_match_in_old = start_in_old + best_match_in_new = start_in_new + best_match_size = 0 + + match_length_at = Hash.new { |h, index| h[index] = 0 } + + start_in_old.upto(end_in_old - 1) do |index_in_old| + + new_match_length_at = Hash.new { |h, index| h[index] = 0 } + + @word_indices[@old_words[index_in_old]].each do |index_in_new| + next if index_in_new < start_in_new + break if index_in_new >= end_in_new + + new_match_length = match_length_at[index_in_new - 1] + 1 + new_match_length_at[index_in_new] = new_match_length + + if new_match_length > best_match_size + best_match_in_old = index_in_old - new_match_length + 1 + best_match_in_new = index_in_new - new_match_length + 1 + best_match_size = new_match_length + end + end + match_length_at = new_match_length_at + end + +# best_match_in_old, best_match_in_new, best_match_size = add_matching_words_left( +# best_match_in_old, best_match_in_new, best_match_size, start_in_old, start_in_new) +# best_match_in_old, best_match_in_new, match_size = add_matching_words_right( +# best_match_in_old, best_match_in_new, best_match_size, end_in_old, end_in_new) + + return (best_match_size != 0 ? Match.new(best_match_in_old, best_match_in_new, best_match_size) : nil) + end + + def add_matching_words_left(match_in_old, match_in_new, match_size, start_in_old, start_in_new) + while match_in_old > start_in_old and + match_in_new > start_in_new and + @old_words[match_in_old - 1] == @new_words[match_in_new - 1] + match_in_old -= 1 + match_in_new -= 1 + match_size += 1 + end + [match_in_old, match_in_new, match_size] + end + + def add_matching_words_right(match_in_old, match_in_new, match_size, end_in_old, end_in_new) + while match_in_old + match_size < end_in_old and + match_in_new + match_size < end_in_new and + @old_words[match_in_old + match_size] == @new_words[match_in_new + match_size] + match_size += 1 + end + [match_in_old, match_in_new, match_size] + end + + def explode(sequence) + sequence.is_a?(String) ? sequence.split(//) : sequence + end + + end # of class Diff Builder + +end diff --git a/engine/src/flutter/sky/tools/third_party/PrettyPatch/prettify.rb b/engine/src/flutter/sky/tools/third_party/PrettyPatch/prettify.rb new file mode 100755 index 0000000000..a9c211fbe1 --- /dev/null +++ b/engine/src/flutter/sky/tools/third_party/PrettyPatch/prettify.rb @@ -0,0 +1,37 @@ +#!/usr/bin/env ruby + +require 'optparse' +require 'pathname' +require 'webrick/htmlutils' + +$LOAD_PATH << Pathname.new(__FILE__).dirname.realpath.to_s + +require 'PrettyPatch' + +BACKTRACE_SEPARATOR = "\n\tfrom " + +options = { :html_exceptions => false } +OptionParser.new do |opts| + opts.banner = "Usage: #{File.basename($0)} [options] [patch-file]" + + opts.separator "" + + opts.on("--html-exceptions", "Print exceptions to stdout as HTML") { |h| options[:html_exceptions] = h } +end.parse! + +patch_data = nil +if ARGV.length == 0 || ARGV[0] == '-' then + patch_data = $stdin.read +else + File.open(ARGV[0]) { |file| patch_data = file.read } +end + +begin + puts PrettyPatch.prettify(patch_data) +rescue => exception + raise unless options[:html_exceptions] + + backtrace = exception.backtrace + backtrace[0] += ": " + exception + " (" + exception.class.to_s + ")" + print "
\n", WEBrick::HTMLUtils::escape(backtrace.join(BACKTRACE_SEPARATOR)), "\n
\n" +end