diff --git a/DEPS b/DEPS index def57b9..736f989c 100644 --- a/DEPS +++ b/DEPS
@@ -40,11 +40,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '42102420c02a525f57264c124ef941882d22c5a1', + 'skia_revision': 'e3e9628ecf863f433f26bf6107d6a39ced57fe30', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '4b582195168e4b62ea38c88c206c664a06fb4b2a', + 'v8_revision': 'c6e2620a1e12dbc25f4ebce8725f781c75ace75d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -64,7 +64,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': '3a4ebcc7c490eba0c22892ab04d1730c350fd0c0', + 'pdfium_revision': 'f768baf129fcafc4342193477e0c41c082ef5ca5', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling openmax_dl # and whatever else without interference from each other. @@ -407,7 +407,7 @@ # For Linux and Chromium OS. 'src/third_party/cros_system_api': - Var('chromium_git') + '/chromiumos/platform/system_api.git' + '@' + '137ec42a355f7800bb02739cb49a64e0c5e19f54', + Var('chromium_git') + '/chromiumos/platform/system_api.git' + '@' + '69b19fbcbec5fa8f5933b9c3f3375052b0059980', # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite':
diff --git a/android_webview/test/BUILD.gn b/android_webview/test/BUILD.gn index 0a0b40e0..b660f60 100644 --- a/android_webview/test/BUILD.gn +++ b/android_webview/test/BUILD.gn
@@ -54,6 +54,8 @@ native_lib_version_arg = "@FileArg($_native_lib_file:full-quoted)" enable_multidex = true + + command_line_flags_file = "android-webview-command-line" } android_resources("android_webview_apk_resources") {
diff --git a/base/memory/weak_ptr.cc b/base/memory/weak_ptr.cc index 8879651..1e9403e7 100644 --- a/base/memory/weak_ptr.cc +++ b/base/memory/weak_ptr.cc
@@ -4,50 +4,71 @@ #include "base/memory/weak_ptr.h" +#include "base/debug/leak_annotations.h" + namespace base { namespace internal { -WeakReference::Flag::Flag() : is_valid_(true) { +static constexpr uintptr_t kTrueMask = ~static_cast<uintptr_t>(0); + +WeakReference::Flag::Flag() : is_valid_(kTrueMask) { +#if DCHECK_IS_ON() // Flags only become bound when checked for validity, or invalidated, // so that we can check that later validity/invalidation operations on // the same Flag take place on the same sequenced thread. sequence_checker_.DetachFromSequence(); +#endif +} + +WeakReference::Flag::Flag(WeakReference::Flag::NullFlagTag) : is_valid_(false) { + // There is no need for sequence_checker_.DetachFromSequence() because the + // null flag doesn't participate in the sequence checks. See DCHECK in + // Invalidate() and IsValid(). + + // Keep the object alive perpetually, even when there are no references to it. + AddRef(); +} + +WeakReference::Flag* WeakReference::Flag::NullFlag() { + ANNOTATE_SCOPED_MEMORY_LEAK; + static Flag* g_null_flag = new Flag(kNullFlagTag); + return g_null_flag; } void WeakReference::Flag::Invalidate() { +#if DCHECK_IS_ON() + if (this == NullFlag()) { + // The Null Flag does not participate in the sequence checks below. + // Since its state never changes, it can be accessed from any thread. + DCHECK(!is_valid_); + return; + } // The flag being invalidated with a single ref implies that there are no - // weak pointers in existence. Allow deletion on other thread in this case. + // weak pointers in existence. Allow deletion on other thread in this + // case. DCHECK(sequence_checker_.CalledOnValidSequence() || HasOneRef()) << "WeakPtrs must be invalidated on the same sequenced thread."; - is_valid_ = false; +#endif + is_valid_ = 0; } -bool WeakReference::Flag::IsValid() const { - DCHECK(sequence_checker_.CalledOnValidSequence()) - << "WeakPtrs must be checked on the same sequenced thread."; - return is_valid_; -} +WeakReference::Flag::~Flag() {} -WeakReference::Flag::~Flag() { -} +WeakReference::WeakReference() : flag_(Flag::NullFlag()) {} -WeakReference::WeakReference() { -} +WeakReference::~WeakReference() {} -WeakReference::WeakReference(const Flag* flag) : flag_(flag) { -} +WeakReference::WeakReference(const Flag* flag) : flag_(flag) {} -WeakReference::~WeakReference() { +WeakReference::WeakReference(WeakReference&& other) + : flag_(std::move(other.flag_)) { + other.flag_ = Flag::NullFlag(); } -WeakReference::WeakReference(WeakReference&& other) = default; - WeakReference::WeakReference(const WeakReference& other) = default; -bool WeakReference::is_valid() const { return flag_.get() && flag_->IsValid(); } - -WeakReferenceOwner::WeakReferenceOwner() { -} +WeakReferenceOwner::WeakReferenceOwner() + : flag_(WeakReference::Flag::NullFlag()) {} WeakReferenceOwner::~WeakReferenceOwner() { Invalidate(); @@ -62,9 +83,9 @@ } void WeakReferenceOwner::Invalidate() { - if (flag_.get()) { + if (flag_ != WeakReference::Flag::NullFlag()) { flag_->Invalidate(); - flag_ = NULL; + flag_ = WeakReference::Flag::NullFlag(); } }
diff --git a/base/memory/weak_ptr.h b/base/memory/weak_ptr.h index 5c9ed54..bda05a99 100644 --- a/base/memory/weak_ptr.h +++ b/base/memory/weak_ptr.h
@@ -96,16 +96,44 @@ public: Flag(); + // Get a pointer to the "Null Flag", a sentinel object used by WeakReference + // objects that don't point to a valid Flag, either because they're default + // constructed or because they have been invalidated. This can be used like + // any other Flag object, but it is invalidated already from the start, and + // its refcount will never reach zero. + static Flag* NullFlag(); + void Invalidate(); - bool IsValid() const; + + // Returns a pointer-sized bitmask of all 1s if valid or all 0s otherwise. + uintptr_t IsValid() const { +#if DCHECK_IS_ON() + if (this == NullFlag()) { + // The Null Flag does not participate in the sequence checks below. + // Since its state never changes, it can be accessed from any thread. + DCHECK(!is_valid_); + return 0; + } + DCHECK(sequence_checker_.CalledOnValidSequence()) + << "WeakPtrs must be checked on the same sequenced thread."; +#endif + return is_valid_; + } private: friend class base::RefCountedThreadSafe<Flag>; + enum NullFlagTag { kNullFlagTag }; + Flag(NullFlagTag); + ~Flag(); + uintptr_t is_valid_; +#if DCHECK_IS_ON() + // Even if SequenceChecker is an empty class in non-dcheck builds, it still + // takes up space in the class. SequenceChecker sequence_checker_; - bool is_valid_; +#endif }; WeakReference(); @@ -117,9 +145,11 @@ WeakReference& operator=(WeakReference&& other) = default; WeakReference& operator=(const WeakReference& other) = default; - bool is_valid() const; + uintptr_t is_valid() const { return flag_->IsValid(); } private: + // Note: To avoid null-checks, flag_ always points to either Flag::NullFlag() + // or some other object. scoped_refptr<const Flag> flag_; }; @@ -131,7 +161,7 @@ WeakReference GetRef() const; bool HasRefs() const { - return flag_.get() && !flag_->HasOneRef(); + return flag_ != WeakReference::Flag::NullFlag() && !flag_->HasOneRef(); } void Invalidate(); @@ -236,7 +266,10 @@ } T* get() const { - return ref_.is_valid() ? reinterpret_cast<T*>(ptr_) : nullptr; + // Intentionally bitwise and; see command on Flag::IsValid(). This provides + // a fast way of conditionally retrieving the pointer, and conveniently sets + // EFLAGS for any null-check performed by the caller. + return reinterpret_cast<T*>(ref_.is_valid() & ptr_); } T& operator*() const {
diff --git a/base/message_loop/message_loop_test.cc b/base/message_loop/message_loop_test.cc index de607002..b764596 100644 --- a/base/message_loop/message_loop_test.cc +++ b/base/message_loop/message_loop_test.cc
@@ -368,7 +368,7 @@ std::unique_ptr<MessagePump> pump(factory()); MessageLoop loop(std::move(pump)); - int depth = 100; + int depth = 50; ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, BindOnce(&NestingFunc, &depth)); RunLoop().Run();
diff --git a/base/profiler/native_stack_sampler_mac.cc b/base/profiler/native_stack_sampler_mac.cc index 4e5108e..c4982cc 100644 --- a/base/profiler/native_stack_sampler_mac.cc +++ b/base/profiler/native_stack_sampler_mac.cc
@@ -8,6 +8,7 @@ #include <libkern/OSByteOrder.h> #include <libunwind.h> #include <mach-o/compact_unwind_encoding.h> +#include <mach-o/getsect.h> #include <mach-o/swap.h> #include <mach/kern_return.h> #include <mach/mach.h> @@ -30,6 +31,19 @@ namespace { +// Maps a module's address range (half-open) in memory to an index in a separate +// data structure. +struct ModuleIndex { + ModuleIndex(uintptr_t start, uintptr_t end, size_t idx) + : base_address(start), end_address(end), index(idx){}; + // Base address of the represented module. + uintptr_t base_address; + // First address off the end of the represented module. + uintptr_t end_address; + // An index to the represented module in a separate container. + size_t index; +}; + // Stack walking -------------------------------------------------------------- // Fills |state| with |target_thread|'s context. @@ -269,23 +283,38 @@ // determined for |module|. size_t GetModuleIndex(const uintptr_t instruction_pointer, std::vector<StackSamplingProfiler::Module>* modules, - std::map<const void*, size_t>* profile_module_index) { + std::vector<ModuleIndex>* profile_module_index) { + // Check if |instruction_pointer| is in the address range of a module we've + // already seen. + auto module_index = + std::find_if(profile_module_index->begin(), profile_module_index->end(), + [instruction_pointer](const ModuleIndex& index) { + return instruction_pointer >= index.base_address && + instruction_pointer < index.end_address; + }); + if (module_index != profile_module_index->end()) { + return module_index->index; + } Dl_info inf; if (!dladdr(reinterpret_cast<const void*>(instruction_pointer), &inf)) return StackSamplingProfiler::Frame::kUnknownModuleIndex; - auto module_index = profile_module_index->find(inf.dli_fbase); - if (module_index == profile_module_index->end()) { - StackSamplingProfiler::Module module( - reinterpret_cast<uintptr_t>(inf.dli_fbase), GetUniqueId(inf.dli_fbase), - base::FilePath(inf.dli_fname)); - modules->push_back(module); - module_index = - profile_module_index - ->insert(std::make_pair(inf.dli_fbase, modules->size() - 1)) - .first; - } - return module_index->second; + StackSamplingProfiler::Module module( + reinterpret_cast<uintptr_t>(inf.dli_fbase), GetUniqueId(inf.dli_fbase), + base::FilePath(inf.dli_fname)); + modules->push_back(module); + + const mach_header_64* mach_header = + reinterpret_cast<const mach_header_64*>(inf.dli_fbase); + DCHECK_EQ(MH_MAGIC_64, mach_header->magic); + + unsigned long module_size; + getsegmentdata(mach_header, SEG_TEXT, &module_size); + uintptr_t base_module_address = reinterpret_cast<uintptr_t>(mach_header); + size_t index = modules->size() - 1; + profile_module_index->emplace_back(base_module_address, + base_module_address + module_size, index); + return index; } // ScopedSuspendThread -------------------------------------------------------- @@ -350,9 +379,9 @@ // between ProfileRecordingStarting() and ProfileRecordingStopped(). std::vector<StackSamplingProfiler::Module>* current_modules_ = nullptr; - // Maps a module's base address to the corresponding Module's index within + // Maps a module's address range to the corresponding Module's index within // current_modules_. - std::map<const void*, size_t> profile_module_index_; + std::vector<ModuleIndex> profile_module_index_; DISALLOW_COPY_AND_ASSIGN(NativeStackSamplerMac); };
diff --git a/build/android/apk_operations.py b/build/android/apk_operations.py new file mode 100755 index 0000000..5c4156cd --- /dev/null +++ b/build/android/apk_operations.py
@@ -0,0 +1,356 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 imp +import logging +import os +import pipes +import shlex +import sys + +import devil_chromium +from devil.android import apk_helper +from devil.android import device_utils +from devil.android import flag_changer +from devil.android.sdk import intent +from devil.android.sdk import adb_wrapper +from devil.utils import run_tests_helper + +from pylib import constants + + +def _InstallApk(install_incremental, inc_install_script, devices_obj, + apk_to_install): + if install_incremental: + helper = apk_helper.ApkHelper(apk_to_install) + try: + install_wrapper = imp.load_source('install_wrapper', inc_install_script) + except IOError: + raise Exception('Incremental install script not found: %s\n' % + inc_install_script) + params = install_wrapper.GetInstallParameters() + + def install_incremental_apk(device): + from incremental_install import installer + installer.Install(device, helper, split_globs=params['splits'], + native_libs=params['native_libs'], + permissions=None) + devices_obj.pMap(install_incremental_apk) + return + # Install the regular apk on devices. + def install(device): + device.Install(apk_to_install) + devices_obj.pMap(install) + + +def _UninstallApk(install_incremental, devices_obj, apk_package): + if install_incremental: + def uninstall_incremental_apk(device): + from incremental_install import installer + installer.Uninstall(device, apk_package) + devices_obj.pMap(uninstall_incremental_apk) + return + # Uninstall the regular apk on devices. + def uninstall(device): + device.Uninstall(apk_package) + devices_obj.pMap(uninstall) + + +def _LaunchUrl(devices_obj, input_args, device_args_file, url, apk_package): + if input_args and device_args_file is None: + raise Exception("This apk does not support any flags.") + def launch(device): + # The flags are first updated with input args. + changer = flag_changer.FlagChanger(device, device_args_file) + flags = [] + if input_args: + flags = shlex.split(input_args) + changer.ReplaceFlags(flags) + # Then launch the apk. + if url is None: + # Simulate app icon click if no url is present. + cmd = ['monkey', '-p', apk_package, '-c', + 'android.intent.category.LAUNCHER', '1'] + device.RunShellCommand(cmd, check_return=True) + else: + launch_intent = intent.Intent( + action='android.intent.action.VIEW', package=apk_package, data=url) + device.StartActivity(launch_intent) + devices_obj.pMap(launch) + + +def _ChangeFlags(devices, devices_obj, input_args, device_args_file): + if input_args is None: + _DisplayArgs(devices, device_args_file) + else: + flags = shlex.split(input_args) + def update(device): + flag_changer.FlagChanger(device, device_args_file).ReplaceFlags(flags) + devices_obj.pMap(update) + + +# TODO(Yipengw):add "--all" in the MultipleDevicesError message and use it here. +def _GenerateMissingAllFlagMessage(devices, devices_obj): + descriptions = devices_obj.pMap(lambda d: d.build_description).pGet(None) + msg = ('More than one device available. Use --all to select all devices, ' + 'or use --device to select a device by serial.\n\nAvailable ' + 'devices:\n') + for d, desc in zip(devices, descriptions): + msg += ' %s (%s)\n' % (d, desc) + return msg + + +def _DisplayArgs(devices, device_args_file): + print 'Current flags (in {%s}):' % device_args_file + for d in devices: + changer = flag_changer.FlagChanger(d, device_args_file) + flags = changer.GetCurrentFlags() + if flags: + quoted_flags = ' '.join(pipes.quote(f) for f in flags) + else: + quoted_flags = '( empty )' + print ' %s (%s): %s' % (d, d.build_description, quoted_flags) + + +def _AddCommonOptions(parser): + parser.add_argument('--all', + action='store_true', + default=False, + help='Operate on all connected devices.',) + parser.add_argument('--device', + action='append', + default=[], + dest='devices', + help='Target device for script to work on. Enter ' + 'multiple times for multiple devices.') + parser.add_argument('--incremental', + action='store_true', + default=False, + help='Always install an incremental apk.') + parser.add_argument('--non-incremental', + action='store_true', + default=False, + help='Always install a non-incremental apk.') + parser.add_argument('-v', + '--verbose', + action='count', + default=0, + dest='verbose_count', + help='Verbose level (multiple times for more)') + + +def _AddLaunchOptions(parser): + parser = parser.add_argument_group("launch arguments") + parser.add_argument('url', + nargs='?', + help='The URL this command launches.') + + +def _AddArgsOptions(parser): + parser = parser.add_argument_group("argv arguments") + parser.add_argument('--args', + help='The flags set by the user.') + + +def _DeviceCachePath(device): + file_name = 'device_cache_%s.json' % device.adb.GetDeviceSerial() + return os.path.join(constants.GetOutDirectory(), file_name) + + +def main(): + # This is used to parse args passed by the gn template. + gn_parser = argparse.ArgumentParser() + gn_parser.add_argument('--apk-path', + help='The path to the apk.') + gn_parser.add_argument('--inc-apk-path', + help='The path to the incremental apk.') + gn_parser.add_argument('--inc-install-script', + help='The path to the incremental install script.') + gn_parser.add_argument('--output-directory', required=True, + help='Path to the directory where build files are.') + gn_parser.add_argument('--command-line-flags-file', + help='The file storing flags on the device.') + + gn_args, sub_argv = gn_parser.parse_known_args() + constants.SetOutputDirectory(gn_args.output_directory) + + parser = argparse.ArgumentParser() + command_parsers = parser.add_subparsers(title='Apk operations', + dest='command') + subp = command_parsers.add_parser('install', help='Install the apk.') + _AddCommonOptions(subp) + + subp = command_parsers.add_parser('uninstall', help='Uninstall the apk.') + _AddCommonOptions(subp) + + subp = command_parsers.add_parser('launch', + help='Launches the apk with the given ' + 'command-line flags, and optionally the ' + 'given URL') + _AddCommonOptions(subp) + _AddLaunchOptions(subp) + _AddArgsOptions(subp) + + subp = command_parsers.add_parser('run', help='Install and launch.') + _AddCommonOptions(subp) + _AddLaunchOptions(subp) + _AddArgsOptions(subp) + + subp = command_parsers.add_parser('stop', help='Stop apks on all devices') + _AddCommonOptions(subp) + + subp = command_parsers.add_parser('clear-data', + help='Clear states for the given package') + _AddCommonOptions(subp) + + subp = command_parsers.add_parser('argv', + help='Display and update flags on devices.') + _AddCommonOptions(subp) + _AddArgsOptions(subp) + + subp = command_parsers.add_parser('gdb', + help='Run build/android/adb_gdb script.') + _AddCommonOptions(subp) + _AddArgsOptions(subp) + + subp = command_parsers.add_parser('logcat', + help='Run the shell command "adb logcat".') + _AddCommonOptions(subp) + + args = parser.parse_args(sub_argv) + run_tests_helper.SetLogLevel(args.verbose_count) + command = args.command + devices = [] + devices_obj = None + + devil_chromium.Initialize() + + # HealthyDevices causes the cmd of "adb devices" output more instances, which + # leads to an issue of adb_gdb cmd. + if command != 'gdb': + devices = device_utils.DeviceUtils.HealthyDevices(device_arg=args.devices, + default_retries=0) + devices_obj = device_utils.DeviceUtils.parallel(devices) + + if command in {'argv', 'stop', 'clear-data'} or len(args.devices) > 0: + args.all = True + if len(devices) > 1 and not args.all: + raise Exception(_GenerateMissingAllFlagMessage(devices, devices_obj)) + + if args.incremental and args.non_incremental: + raise Exception('--incremental and --non-incremental cannot be set at the ' + 'same time.') + install_incremental = False + active_apk = None + apk_package = None + apk_path = gn_args.apk_path + if apk_path and not os.path.exists(apk_path): + apk_path = None + + if args.non_incremental: + if apk_path: + active_apk = apk_path + logging.info('Use the non-incremental apk.') + else: + raise Exception("No regular apk is available.") + + inc_apk_path = gn_args.inc_apk_path + if inc_apk_path and not os.path.exists(inc_apk_path): + inc_apk_path = None + inc_install_script = gn_args.inc_install_script + + if args.incremental: + if inc_apk_path: + active_apk = inc_apk_path + install_incremental = True + logging.info('Use the incremental apk.') + else: + raise Exception("No incremental apk is available.") + + if not args.incremental and not args.non_incremental and command != 'argv': + if apk_path and inc_apk_path: + raise Exception('Both incremental and non-incremental apks exist, please ' + 'use --incremental or --non-incremental to select one.') + if not apk_path and not inc_apk_path: + raise Exception('Neither incremental nor non-incremental apk is ' + 'available.') + if apk_path: + active_apk = apk_path + logging.info('Use the non-incremental apk.') + else: + active_apk = inc_apk_path + install_incremental = True + logging.info('Use the incremental apk.') + if active_apk is not None: + apk_package = apk_helper.GetPackageName(active_apk) + + # Use the cache if possible. + use_cache = True + if command in {'gdb', 'logcat'}: + # Only the current data is needed for these cmds. + use_cache = False + if use_cache: + for d in devices: + cache_path = _DeviceCachePath(d) + if os.path.exists(cache_path): + logging.info('Using device cache: %s', cache_path) + with open(cache_path) as f: + d.LoadCacheData(f.read()) + # Delete the cached file so that any exceptions cause it to be cleared. + os.unlink(cache_path) + else: + logging.info('No cache present for device: %s', d) + + if command == 'install': + _InstallApk(install_incremental, inc_install_script, devices_obj, + active_apk) + elif command == 'uninstall': + _UninstallApk(install_incremental, devices_obj, apk_package) + elif command == 'launch': + _LaunchUrl(devices_obj, args.args, gn_args.command_line_flags_file, + args.url, apk_package) + elif command == 'run': + _InstallApk(install_incremental, inc_install_script, devices_obj, + active_apk) + _LaunchUrl(devices_obj, args.args, gn_args.command_line_flags_file, + args.url, apk_package) + elif command == 'stop': + devices_obj.ForceStop(apk_package) + elif command == 'clear-data': + devices_obj.ClearApplicationState(apk_package) + elif command == 'argv': + _ChangeFlags(devices, devices_obj, args.args, + gn_args.command_line_flags_file) + elif command == 'gdb': + gdb_script_path = os.path.dirname(__file__) + '/adb_gdb' + base_name = os.path.basename(gn_args.apk_path) + program_name = '--program-name=%s' % os.path.splitext(base_name)[0] + package_name = '--package-name=%s' % apk_package + # The output directory is the one including lib* files. + output_dir = '--output-directory=%s' % os.path.abspath( + os.path.join(gn_args.output_directory, os.pardir)) + flags = [gdb_script_path, program_name, package_name, output_dir] + if args.args: + flags += shlex.split(args.args) + os.execv(gdb_script_path, flags) + elif command == 'logcat': + adb_path = adb_wrapper.AdbWrapper.GetAdbPath() + args = [adb_path, 'logcat'] + os.execv(adb_path, args) + + + # Save back to the cache. + if use_cache: + for d in devices: + cache_path = _DeviceCachePath(d) + with open(cache_path, 'w') as f: + f.write(d.DumpCacheData()) + logging.info('Wrote device cache: %s', cache_path) + + +if __name__ == '__main__': + sys.exit(main())
diff --git a/build/android/gyp/apk_install.py b/build/android/gyp/apk_install.py deleted file mode 100755 index f43b0a1..0000000 --- a/build/android/gyp/apk_install.py +++ /dev/null
@@ -1,115 +0,0 @@ -#!/usr/bin/env python -# -# 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. - -"""Installs an APK. - -""" - -import optparse -import os -import sys - -from util import build_device -from util import build_utils -from util import md5_check - -BUILD_ANDROID_DIR = os.path.abspath( - os.path.join(os.path.dirname(__file__), '..')) -sys.path.append(BUILD_ANDROID_DIR) - -import devil_chromium -from devil.android import apk_helper -from pylib import constants - - -def HasInstallMetadataChanged(device, apk_package, metadata_path): - """Checks if the metadata on the device for apk_package has changed.""" - if not os.path.exists(metadata_path): - return True - - try: - expected_metadata = build_utils.ReadJson(metadata_path) - except ValueError: # File is not json encoded. - return True - - return expected_metadata != device.GetInstallMetadata(apk_package) - - -def RecordInstallMetadata(device, apk_package, metadata_path): - """Records the metadata from the device for apk_package.""" - metadata = device.GetInstallMetadata(apk_package, refresh=True) - if not metadata: - raise Exception('APK install failed unexpectedly.') - - build_utils.WriteJson(metadata, metadata_path) - - -def main(): - parser = optparse.OptionParser() - parser.add_option('--apk-path', - help='Path to .apk to install.') - parser.add_option('--split-apk-path', - help='Path to .apk splits (can specify multiple times, causes ' - '--install-multiple to be used.', - action='append') - parser.add_option('--android-sdk-tools', - help='Path to the Android SDK build tools folder. ' + - 'Required when using --split-apk-path.') - parser.add_option('--install-record', - help='Path to install record (touched only when APK is installed).') - parser.add_option('--build-device-configuration', - help='Path to build device configuration.') - parser.add_option('--stamp', - help='Path to touch on success.') - parser.add_option('--configuration-name', - help='The build CONFIGURATION_NAME') - parser.add_option('--output-directory', - help='The output directory.') - options, _ = parser.parse_args() - - constants.SetBuildType(options.configuration_name) - - devil_chromium.Initialize( - output_directory=os.path.abspath(options.output_directory)) - - device = build_device.GetBuildDeviceFromPath( - options.build_device_configuration) - if not device: - return - - serial_number = device.GetSerialNumber() - apk_package = apk_helper.GetPackageName(options.apk_path) - - metadata_path = '%s.%s.device.time.stamp' % (options.apk_path, serial_number) - - # If the APK on the device does not match the one that was last installed by - # the build, then the APK has to be installed (regardless of the md5 record). - force_install = HasInstallMetadataChanged(device, apk_package, metadata_path) - - - def Install(): - if options.split_apk_path: - device.InstallSplitApk(options.apk_path, options.split_apk_path) - else: - device.Install(options.apk_path, reinstall=True) - - RecordInstallMetadata(device, apk_package, metadata_path) - build_utils.Touch(options.install_record) - - - record_path = '%s.%s.md5.stamp' % (options.apk_path, serial_number) - md5_check.CallAndRecordIfStale( - Install, - record_path=record_path, - input_paths=[options.apk_path], - force=force_install) - - if options.stamp: - build_utils.Touch(options.stamp) - - -if __name__ == '__main__': - sys.exit(main())
diff --git a/build/android/gyp/create_apk_operations_script.py b/build/android/gyp/create_apk_operations_script.py new file mode 100755 index 0000000..d82ef07 --- /dev/null +++ b/build/android/gyp/create_apk_operations_script.py
@@ -0,0 +1,78 @@ +#!/usr/bin/env python +# Copyright 2017 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 string +import sys + + +SCRIPT_TEMPLATE = string.Template("""\ +#!/usr/bin/env python +# +# This file was generated by build/android/gyp/create_apk_operations_script.py + +import os +import sys + +def main(args): + script_directory = os.path.dirname(__file__) + resolve = lambda p: os.path.abspath(os.path.join(script_directory, p)) + apk_operations_path = resolve(${APK_OPERATIONS_PATH}) + apk_operations_args = [] + path_args = ${PATH_ARGS} + other_args = ${OTHER_ARGS} + for arg, path in path_args: + apk_operations_args.extend([arg, resolve(path)]) + apk_operations_args.extend(other_args) + apk_operations_cmd = [apk_operations_path] + apk_operations_args + args + os.execv(apk_operations_path, apk_operations_cmd) + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) +""") + + +def main(args): + parser = argparse.ArgumentParser() + parser.add_argument('--script-output-path', + help='Output path for executable script.') + parser.add_argument('--apk-path') + parser.add_argument('--incremental-apk-path') + parser.add_argument('--incremental-install-script') + parser.add_argument('--command-line-flags-file') + args = parser.parse_args(args) + + def relativize(path): + """Returns the path relative to the output script directory.""" + return os.path.relpath(path, os.path.dirname(args.script_output_path)) + + apk_operations_path = os.path.join( + os.path.dirname(__file__), os.path.pardir, 'apk_operations.py') + apk_operations_path = relativize(apk_operations_path) + path_args = [('--output-directory', '.')] + if args.apk_path: + path_args.append(('--apk-path', relativize(args.apk_path))) + if args.incremental_apk_path: + path_args.append( + ('--inc-apk-path', relativize(args.incremental_apk_path))) + path_args.append( + ('--inc-install-script', relativize( + args.incremental_install_script))) + other_args = ['--command-line-flags-file', args.command_line_flags_file] + with open(args.script_output_path, 'w') as script: + script_dict = { + 'APK_OPERATIONS_PATH': repr(apk_operations_path), + 'PATH_ARGS': repr(path_args), + 'OTHER_ARGS': repr(other_args), + } + script.write(SCRIPT_TEMPLATE.substitute(script_dict)) + os.chmod(args.script_output_path, 0750) + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:]))
diff --git a/build/config/android/rules.gni b/build/config/android/rules.gni index e7a2c5b..6c7fb50 100644 --- a/build/config/android/rules.gni +++ b/build/config/android/rules.gni
@@ -2443,6 +2443,49 @@ } } + _apk_operations = [] + _incremental_apk_operations = [] + + # Generate apk opeartion related script. + if (!defined(invoker.create_apk_script) || invoker.create_apk_script) { + _apk_operations_target_name = "${target_name}__apk_operations" + action(_apk_operations_target_name) { + _generated_script = "$root_build_dir/bin/${invoker.target_name}" + script = "//build/android/gyp/create_apk_operations_script.py" + outputs = [ + _generated_script, + ] + args = [ + "--script-output-path", + rebase_path(_generated_script, root_build_dir), + ] + if (defined(invoker.command_line_flags_file)) { + args += [ + "--command-line-flags-file", + invoker.command_line_flags_file, + ] + } + + if (_incremental_allowed) { + args += [ + "--incremental-apk-path", + rebase_path("${_final_apk_path_no_ext}_incremental.apk", + root_build_dir), + "--incremental-install-script", + rebase_path(_incremental_install_script_path, root_build_dir), + ] + } + if (!incremental_apk_by_default) { + args += [ + "--apk-path", + rebase_path(_final_apk_path, root_build_dir), + ] + } + } + _apk_operations += [ ":$_apk_operations_target_name" ] + _incremental_apk_operations += [ ":$_apk_operations_target_name" ] + } + group(target_name) { if (_incremental_allowed && incremental_apk_by_default) { deps = [ @@ -2456,6 +2499,9 @@ ]) public_deps = _final_deps + # Generate apk related operations at runtime. + public_deps += _apk_operations + # Make the proguard .mapping file easy to find by putting it beside the .apk. if (_proguard_enabled) { deps = [ @@ -2488,6 +2534,9 @@ ":${_template_name}__create_incremental", ":${java_target}", ] + + # Generate incremental apk related operations at runtime. + public_deps += _incremental_apk_operations } } } @@ -2615,6 +2664,7 @@ run_findbugs_override = invoker.run_findbugs_override && defined(invoker.java_files) } + create_apk_script = false } group(target_name) { @@ -2703,6 +2753,7 @@ deps = [] forward_variables_from(invoker, "*") testonly = true + create_apk_script = false assert(!defined(invoker.proguard_enabled) || !invoker.proguard_enabled || invoker.proguard_configs != [])
diff --git a/build/config/jumbo.gni b/build/config/jumbo.gni index 06aa8749f..a16795a 100644 --- a/build/config/jumbo.gni +++ b/build/config/jumbo.gni
@@ -25,8 +25,8 @@ jumbo_file_merge_limit = 200 } -# Use this to generate a target which merges sources if possible to -# compile much faster. +# Use one of the targets jumbo_target or jumbo_component to generate a +# target which merges sources if possible to compile much faster. # # Special values. # @@ -46,7 +46,7 @@ # If set to a list of files, those files will not be merged with # the rest. This can be necessary if merging the files causes # compilation issues and fixing the issues is impractical. -template("jumbo_target") { +template("internal_jumbo_target") { use_jumbo_build_for_target = use_jumbo_build if (defined(invoker.always_build_jumbo) && invoker.always_build_jumbo) { use_jumbo_build_for_target = true @@ -177,9 +177,37 @@ } } +# See documentation above by "internal_jumbo_target". +template("jumbo_target") { + internal_jumbo_target(target_name) { + forward_variables_from(invoker, "*") + } +} + set_defaults("jumbo_target") { # This sets the default list of configs when the content_source_set target # is defined. The default_compiler_configs comes from BUILDCONFIG.gn and # is the list normally applied to static libraries and source sets. configs = default_compiler_configs } + +# See documentation above by "internal_jumbo_target". +template("jumbo_component") { + internal_jumbo_target(target_name) { + forward_variables_from(invoker, "*") + } +} + +set_defaults("jumbo_component") { + # This sets the default list of configs when the content_source_set + # target is defined. This code is a clone of set_defaults for the + # ordinary "component" template. + if (is_component_build) { + configs = default_shared_library_configs + if (is_android) { + configs -= [ "//build/config/android:hide_all_but_jni_onload" ] + } + } else { + configs = default_compiler_configs + } +}
diff --git a/cc/layers/layer_impl.cc b/cc/layers/layer_impl.cc index 245b929..90915577b 100644 --- a/cc/layers/layer_impl.cc +++ b/cc/layers/layer_impl.cc
@@ -326,7 +326,8 @@ layer->scroll_tree_index_ = scroll_tree_index_; layer->has_will_change_transform_hint_ = has_will_change_transform_hint_; layer->scrollbars_hidden_ = scrollbars_hidden_; - layer->needs_show_scrollbars_ = needs_show_scrollbars_; + if (needs_show_scrollbars_) + layer->needs_show_scrollbars_ = needs_show_scrollbars_; if (layer_property_changed_) { layer->layer_tree_impl()->set_needs_update_draw_properties();
diff --git a/cc/layers/scrollbar_layer_unittest.cc b/cc/layers/scrollbar_layer_unittest.cc index 32c0f39..400d3f0 100644 --- a/cc/layers/scrollbar_layer_unittest.cc +++ b/cc/layers/scrollbar_layer_unittest.cc
@@ -100,13 +100,13 @@ int total_ui_resource_deleted_; }; -class ScrollbarLayerTest : public testing::Test { +class BaseScrollbarLayerTest : public testing::Test { public: - ScrollbarLayerTest() { + explicit BaseScrollbarLayerTest( + LayerTreeSettings::ScrollbarAnimator animator) { layer_tree_settings_.single_thread_proxy_scheduler = false; layer_tree_settings_.use_zero_copy = true; - layer_tree_settings_.scrollbar_animator = - LayerTreeSettings::ANDROID_OVERLAY; + layer_tree_settings_.scrollbar_animator = animator; layer_tree_settings_.scrollbar_fade_delay = base::TimeDelta::FromMilliseconds(20); layer_tree_settings_.scrollbar_fade_duration = @@ -175,6 +175,18 @@ int scrollbar_layer_id_; }; +class ScrollbarLayerTest : public BaseScrollbarLayerTest { + public: + ScrollbarLayerTest() + : BaseScrollbarLayerTest(LayerTreeSettings::ANDROID_OVERLAY) {} +}; + +class AuraScrollbarLayerTest : public BaseScrollbarLayerTest { + public: + AuraScrollbarLayerTest() + : BaseScrollbarLayerTest(LayerTreeSettings::AURA_OVERLAY) {} +}; + class FakePaintedOverlayScrollbar : public FakeScrollbar { public: FakePaintedOverlayScrollbar() : FakeScrollbar(true, true, true) {} @@ -856,6 +868,55 @@ !impl.host_impl()->active_tree()->ScrollbarGeometriesNeedUpdate()); } +TEST_F(AuraScrollbarLayerTest, ScrollbarLayerCreateAfterSetScrollable) { + // Scrollbar Layer can be created after SetScrollable is called and in a + // separate commit. Ensure we do not missing the DidRequestShowFromMainThread + // call. + const int kThumbThickness = 3; + const int kTrackStart = 0; + + scoped_refptr<Layer> layer_tree_root = Layer::Create(); + scoped_refptr<Layer> scroll_layer = Layer::Create(); + scroll_layer->SetElementId(LayerIdToElementIdForTesting(scroll_layer->id())); + scoped_refptr<Layer> child1 = Layer::Create(); + const bool kIsLeftSideVerticalScrollbar = false; + + scroll_layer->AddChild(child1); + layer_tree_root->AddChild(scroll_layer); + layer_tree_host_->SetRootLayer(layer_tree_root); + + layer_tree_root->SetBounds(gfx::Size(2, 2)); + scroll_layer->SetBounds(gfx::Size(10, 10)); + scroll_layer->SetScrollable(layer_tree_root->bounds()); + layer_tree_host_->UpdateLayers(); + LayerTreeHostImpl* host_impl = layer_tree_host_->host_impl(); + host_impl->CreatePendingTree(); + layer_tree_host_->CommitAndCreatePendingTree(); + host_impl->ActivateSyncTree(); + + LayerImpl* scroll_layer_impl = + host_impl->active_tree()->LayerByElementId(scroll_layer->element_id()); + EXPECT_TRUE(scroll_layer_impl->needs_show_scrollbars()); + + std::unique_ptr<Scrollbar> scrollbar(new FakeScrollbar(false, true, true)); + scoped_refptr<Layer> scrollbar_layer = SolidColorScrollbarLayer::Create( + scrollbar->Orientation(), kThumbThickness, kTrackStart, + kIsLeftSideVerticalScrollbar, scroll_layer->element_id()); + scroll_layer->InsertChild(scrollbar_layer, 1); + + layer_tree_host_->UpdateLayers(); + host_impl->CreatePendingTree(); + layer_tree_host_->CommitAndCreatePendingTree(); + host_impl->ActivateSyncTree(); + + EXPECT_TRUE(host_impl->ScrollbarAnimationControllerForElementId( + scroll_layer->element_id())); + EffectNode* node = + host_impl->active_tree()->property_trees()->effect_tree.Node( + scrollbar_layer->effect_tree_index()); + EXPECT_EQ(node->opacity, 1.f); +} + class ScrollbarLayerSolidColorThumbTest : public testing::Test { public: ScrollbarLayerSolidColorThumbTest() {
diff --git a/cc/trees/layer_tree_impl.cc b/cc/trees/layer_tree_impl.cc index 2c4aa5b..2041e09 100644 --- a/cc/trees/layer_tree_impl.cc +++ b/cc/trees/layer_tree_impl.cc
@@ -1656,20 +1656,15 @@ return; auto& scrollbar_ids = element_id_to_scrollbar_layer_ids_[scroll_element_id]; - int& scrollbar_layer_id = scrollbar_layer->orientation() == HORIZONTAL - ? scrollbar_ids.horizontal - : scrollbar_ids.vertical; - - // We used to DCHECK this was not the case but this can occur on Android: as - // the visual viewport supplies scrollbars for the outer viewport, if the - // outer viewport is changed, we race between updating the visual viewport - // scrollbars and registering new scrollbars on the old outer viewport. It'd - // be nice if we could fix this to be cleaner but its harmless to just - // unregister here. - if (scrollbar_layer_id != Layer::INVALID_ID) - UnregisterScrollbar(scrollbar_layer); - - scrollbar_layer_id = scrollbar_layer->id(); + if (scrollbar_layer->orientation() == HORIZONTAL) { + DCHECK_EQ(scrollbar_ids.horizontal, Layer::INVALID_ID) + << "Existing scrollbar should have been unregistered."; + scrollbar_ids.horizontal = scrollbar_layer->id(); + } else { + DCHECK_EQ(scrollbar_ids.vertical, Layer::INVALID_ID) + << "Existing scrollbar should have been unregistered."; + scrollbar_ids.vertical = scrollbar_layer->id(); + } if (IsActiveTree() && scrollbar_layer->is_overlay_scrollbar() && scrollbar_layer->GetScrollbarAnimator() !=
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 9bdf03fa..1f83caa 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -199,7 +199,6 @@ "//components/payments/content/android:java", "//components/payments/mojom:mojom_parser_java", "//components/policy/android:policy_java", - "//components/precache/android:precache_java", "//components/safe_browsing_db/android:safe_browsing_java", "//components/safe_json/android:safe_json_java", "//components/signin/core/browser/android:java", @@ -474,8 +473,6 @@ "//components/payments/mojom:mojom_parser_java", "//components/policy/android:policy_java", "//components/policy/android:policy_java_test_support", - "//components/precache/android:precache_java", - "//components/precache/android:precache_javatests", "//components/signin/core/browser/android:java", "//components/signin/core/browser/android:javatests", "//components/signin/core/browser/android:signin_java_test_support",
diff --git a/chrome/android/chrome_public_apk_tmpl.gni b/chrome/android/chrome_public_apk_tmpl.gni index 037d16b3..695309b6 100644 --- a/chrome/android/chrome_public_apk_tmpl.gni +++ b/chrome/android/chrome_public_apk_tmpl.gni
@@ -91,6 +91,7 @@ enable_relocation_packing = chrome_public_apk_use_relocation_packer } } + command_line_flags_file = "chrome-command-line" } }
diff --git a/chrome/android/java/DEPS b/chrome/android/java/DEPS index eb8364f..d26401f9 100644 --- a/chrome/android/java/DEPS +++ b/chrome/android/java/DEPS
@@ -12,7 +12,6 @@ "+components/navigation_interception", "+components/offline_items_collection/core/android/java", "+components/payments/content/android/java/src/org/chromium/components/payments", - "+components/precache/android/java", "+components/safe_json/android/java", "+components/sync/android/java/src/org/chromium/components/sync", "+components/web_contents_delegate_android",
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/precache/FailureReason.java b/chrome/android/java/src/org/chromium/chrome/browser/precache/FailureReason.java deleted file mode 100644 index fee4722..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/precache/FailureReason.java +++ /dev/null
@@ -1,49 +0,0 @@ -// 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. - -package org.chromium.chrome.browser.precache; - -import java.util.EnumSet; - -/** A reason why prefetching failed to start. */ -enum FailureReason { - /** PrecacheLauncher.updatePrecachingEnabled() has not yet been called. */ - UPDATE_PRECACHING_ENABLED_NEVER_CALLED(0), - - /** The sync backend is not yet initialized. */ - SYNC_NOT_INITIALIZED(1), - - /** PrivacyPreferencesManager#shouldPrerender() returns false. */ - PRERENDER_PRIVACY_PREFERENCE_NOT_ENABLED(2), - - /** PrecacheLauncher#nativeShouldRun() returns false. */ - NATIVE_SHOULD_RUN_IS_FALSE(3), - - /** DeviceState#isPowerConnected() returns false. */ - NO_POWER(4), - - /** DeviceState#isWifiAvailable() returns false. */ - NO_WIFI(5), - - // Deprecated: SCREEN_ON(6). - - // Deprecated: NOT_ENOUGH_TIME_SINCE_LAST_PRECACHE(7), - - /** PrecacheController#isPrecaching() returns true. */ - CURRENTLY_PRECACHING(8); - - /** Returns the set of reasons as a bit vector. */ - static int bitValue(EnumSet<FailureReason> reasons) { - int value = 0; - for (FailureReason reason : reasons) value |= 1 << reason.mPosition; - return value; - } - - FailureReason(int position) { - this.mPosition = position; - } - - /** The bit position, to be set when computing the bit vector. */ - private final int mPosition; -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/precache/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/precache/OWNERS deleted file mode 100644 index f24d985..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/precache/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -file://components/precache/OWNERS \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheController.java b/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheController.java deleted file mode 100644 index fca02499..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheController.java +++ /dev/null
@@ -1,572 +0,0 @@ -// 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. - -package org.chromium.chrome.browser.precache; - -import android.annotation.SuppressLint; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.net.ConnectivityManager; -import android.os.Handler; -import android.os.Looper; -import android.os.PowerManager; -import android.os.PowerManager.WakeLock; - -import com.google.android.gms.gcm.GcmNetworkManager; -import com.google.android.gms.gcm.OneoffTask; -import com.google.android.gms.gcm.PeriodicTask; - -import org.chromium.base.ContextUtils; -import org.chromium.base.Log; -import org.chromium.base.NonThreadSafe; -import org.chromium.base.VisibleForTesting; -import org.chromium.base.library_loader.LibraryLoader; -import org.chromium.base.metrics.RecordHistogram; -import org.chromium.base.metrics.RecordUserAction; -import org.chromium.chrome.browser.ChromeBackgroundService; -import org.chromium.chrome.browser.ChromeVersionInfo; -import org.chromium.components.precache.DeviceState; -import org.chromium.components.sync.ModelType; - -import java.util.ArrayDeque; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Queue; -import java.util.Set; - -/** - * Singleton responsible for starting and stopping a precache session. - * Precaching occurs only when the device is connected to power and an - * un-metered network connection. It holds a wake lock while running. It stops - * running when power or the un-metered network is disconnected, - * MAX_PRECACHE_DURATION_SECONDS elapse, or there are no more resources to - * precache. - */ -public class PrecacheController { - private static final String TAG = "Precache"; - - /** - * ID of the periodic task. Used here and by - * {@link ChromeBackgroundService} for dispatch. - */ - public static final String PERIODIC_TASK_TAG = "precache"; - - @VisibleForTesting - static final String PREF_IS_PRECACHING_ENABLED = "precache.is_precaching_enabled"; - - /** - * ID of the continuation task. Used here and by - * {@link ChromeBackgroundService} for dispatch. - */ - public static final String CONTINUATION_TASK_TAG = "precache-continuation"; - - static final int WAIT_UNTIL_NEXT_PRECACHE_SECONDS = 6 * 60 * 60; // 6 hours. - static final int COMPLETION_TASK_MIN_DELAY_SECONDS = 5 * 60; // 5 minutes. - static final int COMPLETION_TASK_MAX_DELAY_SECONDS = 60 * 60; // 1 hour. - static final int MAX_SYNC_SERVICE_INIT_TIMOUT_MS = 5 * 60 * 1000; // 5 minutes - static final int MAX_PRECACHE_DURATION_SECONDS = 30 * 60; // 30 minutes. - static final Set<Integer> SYNC_SERVICE_CONFIGURED_DATATYPES = - Collections.unmodifiableSet(new HashSet<Integer>(Arrays.asList(ModelType.SESSIONS))); - - private static final String PREF_PRECACHE_PERIODIC_TASK_START_TIME_MS = - "precache.periodic_task_start_time_ms"; - - /** - * Singleton instance of the PrecacheController. PrecacheController is a - * singleton so that there is a single handle by which to determine if - * precaching is underway, and to cancel it if necessary. - */ - @SuppressLint("StaticFieldLeak") - private static PrecacheController sInstance; - - /** - * The default task scheduler. Overridden for tests. - */ - private static PrecacheTaskScheduler sTaskScheduler = new PrecacheTaskScheduler(); - - /** - * Listener for syncservice backend. - */ - SyncServiceInitializedNotifier mSyncServiceNotifier; - - /** True if a precache session is in progress. Threadsafe. */ - private boolean mIsPrecaching; - - /** Wakelock that is held while precaching is in progress. */ - private WakeLock mPrecachingWakeLock; - - private Context mAppContext; - private Queue<Integer> mFailureReasonsToRecord = new ArrayDeque<Integer>(); - private DeviceState mDeviceState = DeviceState.getInstance(); - - /** Receiver that will be notified when conditions become wrong for precaching. */ - private final BroadcastReceiver mDeviceStateReceiver = new BroadcastReceiver() { - @Override - public void onReceive(final Context context, Intent intent) { - runOnInstanceThread(new Runnable() { - @Override - public void run() { - Log.v(TAG, "conditions changed: precaching(%s), powered(%s), unmetered(%s)", - isPrecaching(), mDeviceState.isPowerConnected(context), - mDeviceState.isUnmeteredNetworkAvailable(context)); - if (isPrecaching() - && ((ChromeVersionInfo.isStableBuild() - && !mDeviceState.isPowerConnected(context)) - || !mDeviceState.isUnmeteredNetworkAvailable(context))) { - recordFailureReasons(context); - cancelPrecaching(!mDeviceState.isUnmeteredNetworkAvailable(context) - ? PrecacheUMA.Event.PRECACHE_CANCEL_NO_UNMETERED_NETWORK - : PrecacheUMA.Event.PRECACHE_CANCEL_NO_POWER); - } - } - }); - } - }; - - Handler mHandler; - Runnable mTimeoutRunnable = new Runnable() { - @Override - public void run() { - Log.v(TAG, "precache session timed out"); - cancelPrecaching(PrecacheUMA.Event.PRECACHE_SESSION_TIMEOUT); - } - }; - - /** - * Used to ensure this class is always used on the thread on which it - * is instantiated. - */ - private final NonThreadSafe mNonThreadSafe; - - /** - * Returns the singleton PrecacheController instance. Should only be called - * from the UI thread. - */ - public static PrecacheController get(Context context) { - if (sInstance == null) { - sInstance = new PrecacheController(context); - } - return sInstance; - } - - /** - * Returns true if the PrecacheController singleton has already been - * created. - */ - public static boolean hasInstance() { - return sInstance != null; - } - - /** - * Schedules a periodic task to precache resources. - * @param context The application context. - * @return false if the task cannot be scheduled. - */ - private static boolean schedulePeriodicPrecacheTask(Context context) { - PeriodicTask task = new PeriodicTask.Builder() - .setPeriod(WAIT_UNTIL_NEXT_PRECACHE_SECONDS) - .setPersisted(true) - .setRequiredNetwork(PeriodicTask.NETWORK_STATE_UNMETERED) - .setRequiresCharging(ChromeVersionInfo.isStableBuild()) - .setService(ChromeBackgroundService.class) - .setTag(PERIODIC_TASK_TAG) - .build(); - return sTaskScheduler.scheduleTask(context, task); - } - - private static void cancelPeriodicPrecacheTask(Context context) { - Log.v(TAG, "canceling a periodic precache task"); - sTaskScheduler.cancelTask(context, PERIODIC_TASK_TAG); - } - - /** - * Schedules a one-off task to finish precaching the resources that were - * still outstanding when the last task was interrupted. Interrupting such - * a one-off task will result in scheduling a new one. - * @param context The application context. - */ - private static void schedulePrecacheCompletionTask(Context context) { - Log.v(TAG, "scheduling a precache completion task"); - OneoffTask task = new OneoffTask.Builder() - .setExecutionWindow(COMPLETION_TASK_MIN_DELAY_SECONDS, - COMPLETION_TASK_MAX_DELAY_SECONDS) - .setPersisted(true) - .setRequiredNetwork(OneoffTask.NETWORK_STATE_UNMETERED) - .setRequiresCharging(ChromeVersionInfo.isStableBuild()) - .setService(ChromeBackgroundService.class) - .setTag(CONTINUATION_TASK_TAG) - .setUpdateCurrent(true) - .build(); - if (sTaskScheduler.scheduleTask(context, task)) { - PrecacheUMA.record(PrecacheUMA.Event.ONEOFF_TASK_SCHEDULE); - } else { - PrecacheUMA.record(PrecacheUMA.Event.ONEOFF_TASK_SCHEDULE_FAIL); - } - } - - private static void cancelPrecacheCompletionTask(Context context) { - Log.v(TAG, "canceling a precache completion task"); - sTaskScheduler.cancelTask(context, CONTINUATION_TASK_TAG); - } - - /** - * Called when Chrome package is upgraded to reschedule the precache periodic task. - * @param context The application context. - */ - public static void rescheduleTasksOnUpgrade(Context context) { - // Reschedule the periodic task if precache was enabled previously. - SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences(); - if (sharedPreferences.getBoolean(PREF_IS_PRECACHING_ENABLED, false) - && !schedulePeriodicPrecacheTask(context)) { - // Clear the preference, for the task to be scheduled next time. - sharedPreferences.edit().putBoolean(PREF_IS_PRECACHING_ENABLED, false).apply(); - PrecacheUMA.record(PrecacheUMA.Event.PERIODIC_TASK_SCHEDULE_UPGRADE_FAIL); - } else { - PrecacheUMA.record(PrecacheUMA.Event.PERIODIC_TASK_SCHEDULE_UPGRADE); - } - } - - @VisibleForTesting - PrecacheController(Context context) { - mNonThreadSafe = new NonThreadSafe(); - mAppContext = context.getApplicationContext(); - mHandler = new Handler(Looper.myLooper()); - } - - /** Returns true if precaching is able to run. */ - @VisibleForTesting - boolean isPrecachingEnabled() { - assert mNonThreadSafe.calledOnValidThread(); - SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); - return prefs.getBoolean(PREF_IS_PRECACHING_ENABLED, false); - } - - private void runOnInstanceThread(final Runnable r) { - if (mHandler.getLooper() == Looper.myLooper()) { - r.run(); - } else { - mHandler.post(r); - } - } - - /** - * Sets whether or not precaching is enabled. If precaching is enabled, a - * periodic precaching task will be scheduled to run. If disabled, any - * running precache session will be stopped, and all tasks canceled. - */ - public static void setIsPrecachingEnabled(Context context, boolean enabled) { - boolean cancelRequired = !enabled && PrecacheController.hasInstance(); - Context appContext = context.getApplicationContext(); - - SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences(); - if (sharedPreferences.getBoolean(PREF_IS_PRECACHING_ENABLED, !enabled) == enabled) { - return; - } - - Log.v(TAG, "setting precache enabled to %s", enabled); - sharedPreferences.edit().putBoolean(PREF_IS_PRECACHING_ENABLED, enabled).apply(); - - if (enabled) { - if (!schedulePeriodicPrecacheTask(appContext)) { - // Clear the preference, for the task to be scheduled next time. - sharedPreferences.edit().putBoolean(PREF_IS_PRECACHING_ENABLED, false).apply(); - PrecacheUMA.record(PrecacheUMA.Event.PERIODIC_TASK_SCHEDULE_STARTUP_FAIL); - } else { - PrecacheUMA.record(PrecacheUMA.Event.PERIODIC_TASK_SCHEDULE_STARTUP); - } - } else { - // If precaching, stop. - cancelPeriodicPrecacheTask(appContext); - cancelPrecacheCompletionTask(appContext); - } - if (cancelRequired) { - sInstance.cancelPrecaching(PrecacheUMA.Event.PRECACHE_CANCEL_DISABLED_PREF); - } - } - - /** Returns true if the precache session in progress. */ - public boolean isPrecaching() { - assert mNonThreadSafe.calledOnValidThread(); - return mIsPrecaching; - } - - /** - * Sets whether or not the precache session is in progress. - * @return True if this state changed. - */ - @VisibleForTesting - boolean setIsPrecaching(boolean isPrecaching) { - assert mNonThreadSafe.calledOnValidThread(); - if (mIsPrecaching != isPrecaching) { - mIsPrecaching = isPrecaching; - return true; - } - return false; - } - - /** Overrides the default DeviceState object, e.g., with a mock for tests. */ - @VisibleForTesting - void setDeviceState(DeviceState deviceState) { - assert mNonThreadSafe.calledOnValidThread(); - mDeviceState = deviceState; - } - - @VisibleForTesting - Runnable getTimeoutRunnable() { - assert mNonThreadSafe.calledOnValidThread(); - return mTimeoutRunnable; - } - - @VisibleForTesting - BroadcastReceiver getDeviceStateReceiver() { - assert mNonThreadSafe.calledOnValidThread(); - return mDeviceStateReceiver; - } - - /** - * Ends a precache session. - * @param precachingIncomplete True if the session was interrupted. - */ - void handlePrecacheCompleted(boolean precachingIncomplete) { - assert mNonThreadSafe.calledOnValidThread(); - if (setIsPrecaching(false)) { - shutdownPrecaching(precachingIncomplete); - } - PrecacheUMA.record(precachingIncomplete ? PrecacheUMA.Event.PRECACHE_SESSION_INCOMPLETE - : PrecacheUMA.Event.PRECACHE_SESSION_COMPLETE); - } - - /** {@link PrecacheLauncher} used to run a precache session. */ - private PrecacheLauncher mPrecacheLauncher = new PrecacheLauncher() { - @Override - protected void onPrecacheCompleted(boolean tryAgainSoon) { - Log.v(TAG, "precache session completed"); - handlePrecacheCompleted(tryAgainSoon); - } - }; - - /** - * Called by {@link ChromeBackgroundService} when a precache task is ready - * to run. - */ - public int precache(String tag) { - assert mNonThreadSafe.calledOnValidThread(); - PrecacheUMA.record(PERIODIC_TASK_TAG.equals(tag) - ? PrecacheUMA.Event.PRECACHE_TASK_STARTED_PERIODIC - : PrecacheUMA.Event.PRECACHE_TASK_STARTED_ONEOFF); - Log.v(TAG, "precache task (%s) started", tag); - if (!isPrecachingEnabled()) { - Log.v(TAG, "precaching isn't enabled"); - cancelPeriodicPrecacheTask(mAppContext); - cancelPrecacheCompletionTask(mAppContext); - PrecacheUMA.record(PrecacheUMA.Event.DISABLED_IN_PRECACHE_PREF); - return GcmNetworkManager.RESULT_SUCCESS; - } - if (setIsPrecaching(true)) { - if (PERIODIC_TASK_TAG.equals(tag)) { - recordPeriodicTaskIntervalHistogram(); - cancelPrecacheCompletionTask(mAppContext); - } - recordBatteryLevelAtStart(); - registerDeviceStateReceiver(); - acquirePrecachingWakeLock(); - startPrecachingAfterSyncInit(); - return GcmNetworkManager.RESULT_SUCCESS; - } - Log.v(TAG, "precache session was already running"); - PrecacheUMA.record(PrecacheUMA.Event.PRECACHE_TASK_STARTED_DUPLICATE); - return GcmNetworkManager.RESULT_FAILURE; - } - - @VisibleForTesting - void startPrecachingAfterSyncInit() { - mSyncServiceNotifier = new SyncServiceInitializedNotifier( - SYNC_SERVICE_CONFIGURED_DATATYPES, new SyncServiceInitializedNotifier.Listener() { - @Override - public void onDataTypesActive() { - startPrecaching(); - } - - @Override - public void onFailureOrTimedOut() { - cancelPrecaching(PrecacheUMA.Event.SYNC_SERVICE_TIMEOUT); - } - }, MAX_SYNC_SERVICE_INIT_TIMOUT_MS); - } - - /** Begins a precache session. */ - @VisibleForTesting - void startPrecaching() { - Log.v(TAG, "precache session has started"); - - mHandler.postDelayed(mTimeoutRunnable, MAX_PRECACHE_DURATION_SECONDS * 1000); - PrecacheUMA.record(PrecacheUMA.Event.PRECACHE_SESSION_STARTED); - - // In certain cases, the PrecacheLauncher will skip precaching entirely and call - // finishPrecaching() before this call to mPrecacheLauncher.start() returns, so the call to - // mPrecacheLauncher.start() must happen after acquiring the wake lock to ensure that the - // wake lock is released properly. - mPrecacheLauncher.start(); - } - - /** - * Cancels the current precache session. - * @param event the failure reason. - */ - private void cancelPrecaching(final int event) { - // cancelPrecaching() could be called from PrecacheManager::Shutdown(), precache GCM task, - // etc., where it could be a different thread. - runOnInstanceThread(new Runnable() { - @Override - public void run() { - Log.v(TAG, "canceling precache session"); - if (setIsPrecaching(false)) { - mPrecacheLauncher.cancel(); - shutdownPrecaching(true); - } - PrecacheUMA.record(event); - } - }); - } - - /** - * Updates state to indicate that the precache session is no longer in - * progress, and stops the service. - */ - private void shutdownPrecaching(boolean precachingIncomplete) { - Log.v(TAG, "shutting down precache session"); - if (precachingIncomplete) { - schedulePrecacheCompletionTask(mAppContext); - } - recordBatteryLevelAtEnd(); - mHandler.removeCallbacks(mTimeoutRunnable); - mAppContext.unregisterReceiver(mDeviceStateReceiver); - releasePrecachingWakeLock(); - } - - /** - * Registers a BroadcastReceiver to detect when conditions become wrong - * for precaching. - */ - private void registerDeviceStateReceiver() { - Log.v(TAG, "registered device state receiver"); - IntentFilter filter = new IntentFilter(); - if (ChromeVersionInfo.isStableBuild()) { - // Power requirement for precache is only for stable channel. - filter.addAction(Intent.ACTION_POWER_DISCONNECTED); - } - filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); - mAppContext.registerReceiver(mDeviceStateReceiver, filter); - } - - /** Acquires the precaching {@link WakeLock}. */ - @VisibleForTesting - void acquirePrecachingWakeLock() { - assert mNonThreadSafe.calledOnValidThread(); - Log.v(TAG, "acquiring wake lock"); - if (mPrecachingWakeLock == null) { - PowerManager pm = (PowerManager) mAppContext.getSystemService(Context.POWER_SERVICE); - mPrecachingWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); - } - mPrecachingWakeLock.acquire(); - } - - /** Releases the precaching {@link WakeLock} if it is held. */ - @VisibleForTesting - void releasePrecachingWakeLock() { - assert mNonThreadSafe.calledOnValidThread(); - Log.v(TAG, "releasing wake lock"); - if (mPrecachingWakeLock != null && mPrecachingWakeLock.isHeld()) { - mPrecachingWakeLock.release(); - } - } - - /** - * Returns the set of reasons that the last prefetch attempt failed to start. - * - * @param context the context passed to onReceive() - */ - @VisibleForTesting - EnumSet<FailureReason> interruptionReasons(Context context) { - assert mNonThreadSafe.calledOnValidThread(); - EnumSet<FailureReason> reasons = EnumSet.noneOf(FailureReason.class); - reasons.addAll(mPrecacheLauncher.failureReasons()); - if (!mDeviceState.isPowerConnected(context)) reasons.add(FailureReason.NO_POWER); - if (!mDeviceState.isUnmeteredNetworkAvailable(context)) reasons.add(FailureReason.NO_WIFI); - if (isPrecaching()) reasons.add(FailureReason.CURRENTLY_PRECACHING); - return reasons; - } - - /** - * Tries to record a histogram enumerating all of the return value of failureReasons(). - * - * If the native libraries are not already loaded, no histogram is recorded. - * - * @param context the context passed to onReceive() - */ - @VisibleForTesting - void recordFailureReasons(Context context) { - assert mNonThreadSafe.calledOnValidThread(); - int reasons = FailureReason.bitValue(interruptionReasons(context)); - // Queue up this failure reason, for the next time we are able to record it in UMA. - mFailureReasonsToRecord.add(reasons); - // If native libraries are loaded, then we are able to flush our queue to UMA. - if (LibraryLoader.isInitialized()) { - Integer reasonsToRecord; - while ((reasonsToRecord = mFailureReasonsToRecord.poll()) != null) { - RecordHistogram.recordSparseSlowlyHistogram( - "Precache.Fetch.FailureReasons", reasonsToRecord); - RecordUserAction.record("Precache.Fetch.IntentReceived"); - } - } - } - - @VisibleForTesting - void setPrecacheLauncher(PrecacheLauncher precacheLauncher) { - assert mNonThreadSafe.calledOnValidThread(); - mPrecacheLauncher = precacheLauncher; - } - - @VisibleForTesting - static void setTaskScheduler(PrecacheTaskScheduler taskScheduler) { - PrecacheController.sTaskScheduler = taskScheduler; - } - - private static void recordPeriodicTaskIntervalHistogram() { - SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); - long previous_start_time_ms = prefs.getLong(PREF_PRECACHE_PERIODIC_TASK_START_TIME_MS, 0); - long current_start_time_ms = System.currentTimeMillis(); - if (previous_start_time_ms > 0 && current_start_time_ms > previous_start_time_ms) { - int interval_mins = - (int) ((current_start_time_ms - previous_start_time_ms) / (1000 * 60)); - RecordHistogram.recordCustomCountHistogram( - "Precache.PeriodicTaskInterval", interval_mins, 1, 10000, 50); - } - prefs.edit() - .putLong(PREF_PRECACHE_PERIODIC_TASK_START_TIME_MS, current_start_time_ms) - .apply(); - } - - private void recordBatteryLevelAtStart() { - mDeviceState.saveCurrentBatteryPercentage(mAppContext); - - // Report battery percentage. - RecordHistogram.recordPercentageHistogram( - "Precache.BatteryPercentage.Start", mDeviceState.getSavedBatteryPercentage()); - } - - private void recordBatteryLevelAtEnd() { - int delta_percentage = mDeviceState.getCurrentBatteryPercentage(mAppContext) - - mDeviceState.getSavedBatteryPercentage(); - if (delta_percentage >= 0) { - RecordHistogram.recordPercentageHistogram( - "Precache.BatteryPercentageDiff.End", delta_percentage); - } - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheLauncher.java b/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheLauncher.java deleted file mode 100644 index 0ef82a5..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheLauncher.java +++ /dev/null
@@ -1,196 +0,0 @@ -// 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. - -package org.chromium.chrome.browser.precache; - -import android.content.Context; - -import org.chromium.base.Log; -import org.chromium.base.ThreadUtils; -import org.chromium.base.VisibleForTesting; -import org.chromium.base.annotations.CalledByNative; -import org.chromium.chrome.browser.preferences.privacy.PrivacyPreferencesManager; -import org.chromium.chrome.browser.sync.ProfileSyncService; - -import java.util.EnumSet; - -/** Class that interacts with the PrecacheManager to control precache cycles. */ -public abstract class PrecacheLauncher { - private static final String TAG = "Precache"; - - private static final PrecacheLauncher sInstance = new PrecacheLauncher() { - /** A null implementation, as it is not needed by clients of sInstance. */ - @Override - protected void onPrecacheCompleted(boolean tryAgainSoon) {} - }; - - /** Returns the singleton instance of PrecacheLauncher. */ - public static PrecacheLauncher get() { - return sInstance; - } - - /** Pointer to the native PrecacheLauncher object. Set to 0 when uninitialized. */ - private long mNativePrecacheLauncher; - - /** - * Initialized by updateEnabled to call updateEnabledSync when the sync backend is initialized. - * Only accessed on the UI thread. - */ - private ProfileSyncService.SyncStateChangedListener mListener; - - /** - * Boolean failure indicators, reflecting the state of the last call to updatePrecachingEnabled. - * Access must occur on the UI thread. Values default to false -- so if mCalled is false, the - * value of the other booleans is not necessarily valid. - */ - private boolean mCalled; - private boolean mSyncInitialized; - private boolean mPrerenderEnabled; - private boolean mShouldRun; - - /** Destroy the native PrecacheLauncher, releasing the memory that it was using. */ - public void destroy() { - if (mNativePrecacheLauncher != 0) { - nativeDestroy(mNativePrecacheLauncher); - mNativePrecacheLauncher = 0; - } - } - - /** Starts a precache cycle. */ - public void start() { - // Lazily initialize the native PrecacheLauncher. - if (mNativePrecacheLauncher == 0) { - mNativePrecacheLauncher = nativeInit(); - } - nativeStart(mNativePrecacheLauncher); - } - - /** Cancel the precache cycle if one is ongoing. */ - public void cancel() { - // Lazily initialize the native PrecacheLauncher. - if (mNativePrecacheLauncher == 0) { - mNativePrecacheLauncher = nativeInit(); - } - nativeCancel(mNativePrecacheLauncher); - } - - /** - * Called when a precache cycle completes. - * - * @param tryAgainSoon true iff the precache failed to start due to a transient error and should - * be attempted again soon - */ - protected abstract void onPrecacheCompleted(boolean tryAgainSoon); - - /** - * Called by native code when the precache cycle completes. This method exists because an - * abstract method cannot be directly called from native. - * - * @param tryAgainSoon true iff the precache failed to start due to a transient error and should - * be attempted again soon - */ - @CalledByNative - private void onPrecacheCompletedCallback(boolean tryAgainSoon) { - onPrecacheCompleted(tryAgainSoon); - } - - /** - * Updates the PrecacheController with whether conditions are right for precaching. All of - * the following must be true: - * - * <ul> - * <li>The predictive network actions preference is enabled.</li> - * <li>Sync is enabled for sessions and it is not encrypted with a secondary passphrase.</li> - * <li>Either the Precache field trial or the precache commandline flag is enabled.</li> - * </ul> - * - * This should be called only after the sync backend has been initialized. Must be called on the - * UI thread. - * - * @param context any context within the application - */ - private void updateEnabledSync(Context context) { - // PrefServiceBridge.getInstance() and nativeShouldRun() can only be executed on the UI - // thread. - ThreadUtils.assertOnUiThread(); - - boolean prerenderEnabled = PrivacyPreferencesManager.getInstance().shouldPrerender(); - boolean shouldRun = nativeShouldRun(); - - mPrerenderEnabled = prerenderEnabled; - mShouldRun = shouldRun; - - PrecacheController.setIsPrecachingEnabled(context, prerenderEnabled && shouldRun); - Log.v(TAG, "updateEnabledSync complete"); - } - - /** - * If precaching is enabled, then allow the PrecacheController to be launched and signal Chrome - * when conditions are right to start precaching. If precaching is disabled, prevent the - * PrecacheController from ever starting. - * - * @param context any context within the application - */ - @VisibleForTesting - void updateEnabled(final Context context) { - Log.v(TAG, "updateEnabled starting"); - ThreadUtils.postOnUiThread(new Runnable() { - @Override - public void run() { - mCalled = true; - final ProfileSyncService sync = ProfileSyncService.get(); - - if (mListener == null && sync != null) { - mListener = new ProfileSyncService.SyncStateChangedListener() { - @Override - public void syncStateChanged() { - if (sync.isEngineInitialized()) { - mSyncInitialized = true; - updateEnabledSync(context); - } - } - }; - sync.addSyncStateChangedListener(mListener); - } - - if (mListener != null) { - // Call the listener once, in case the sync engine is already initialized. - mListener.syncStateChanged(); - } - Log.v(TAG, "updateEnabled complete"); - } - }); - } - - /** - * If precaching is enabled, then allow the PrecacheController to be launched and signal Chrome - * when conditions are right to start precaching. If precaching is disabled, prevent the - * PrecacheController from ever starting. - * - * @param context any context within the application - */ - public static void updatePrecachingEnabled(final Context context) { - sInstance.updateEnabled(context); - } - - /** Returns the set of reasons that the "precache.is_precaching_enabled" pref is false. */ - public EnumSet<FailureReason> failureReasons() { - ThreadUtils.assertOnUiThread(); - EnumSet<FailureReason> reasons = EnumSet.noneOf(FailureReason.class); - if (!mCalled) reasons.add(FailureReason.UPDATE_PRECACHING_ENABLED_NEVER_CALLED); - if (!mSyncInitialized) reasons.add(FailureReason.SYNC_NOT_INITIALIZED); - if (!mPrerenderEnabled) { - reasons.add(FailureReason.PRERENDER_PRIVACY_PREFERENCE_NOT_ENABLED); - } - if (!mShouldRun) reasons.add(FailureReason.NATIVE_SHOULD_RUN_IS_FALSE); - return reasons; - } - - private native long nativeInit(); - private native void nativeDestroy(long nativePrecacheLauncher); - private native void nativeStart(long nativePrecacheLauncher); - private native void nativeCancel(long nativePrecacheLauncher); - - @VisibleForTesting native boolean nativeShouldRun(); -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheTaskScheduler.java b/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheTaskScheduler.java deleted file mode 100644 index 0922c6b..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheTaskScheduler.java +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.precache; - -import android.content.Context; - -import com.google.android.gms.common.ConnectionResult; -import com.google.android.gms.common.GoogleApiAvailability; -import com.google.android.gms.gcm.GcmNetworkManager; -import com.google.android.gms.gcm.Task; - -import org.chromium.chrome.browser.ChromeBackgroundService; - -class PrecacheTaskScheduler { - boolean canScheduleTasks(Context context) { - if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) - != ConnectionResult.SUCCESS) { - return false; - } - return true; - } - - boolean scheduleTask(Context context, Task task) { - if (!canScheduleTasks(context)) { - return false; - } - try { - GcmNetworkManager.getInstance(context).schedule(task); - } catch (IllegalArgumentException e) { - return false; - } - return true; - } - - boolean cancelTask(Context context, String tag) { - if (!canScheduleTasks(context)) { - return false; - } - try { - GcmNetworkManager.getInstance(context).cancelTask(tag, ChromeBackgroundService.class); - } catch (IllegalArgumentException e) { - return false; - } - return true; - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheUMA.java b/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheUMA.java deleted file mode 100644 index d6f3015..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheUMA.java +++ /dev/null
@@ -1,142 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.precache; - -import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; - -import org.chromium.base.ContextUtils; -import org.chromium.base.VisibleForTesting; -import org.chromium.base.library_loader.LibraryLoader; -import org.chromium.base.metrics.RecordHistogram; - -import java.util.Arrays; - -/** - * Enumerates the various failure reasons and events of interest for precaching. When the library is - * loaded, the events are logged as UMA metrics. Otherwise the events are persisted in shared - * preferences until the library loads in future. When the library is not loaded, only single - * occurrence of an event is recorded, duplicate occurrence of the same event is not persisted. - */ -public class PrecacheUMA { - /** - * The events should not be renumbered or reused since these are used in a histogram. - * This must remain in sync with Precache.Events in tools/metrics/histograms/histograms.xml. - */ - public static class Event { - /** - * Indicates that the precache scheduled task has started. The task can be periodic or - * one-off completion task. - */ - public static final int PRECACHE_TASK_STARTED_PERIODIC = 0; - public static final int PRECACHE_TASK_STARTED_ONEOFF = 1; - // Duplicate GCM task was started while precache was running. - public static final int PRECACHE_TASK_STARTED_DUPLICATE = 2; - - /** - * The native library failed to load, during the run of a precache scheduled task. - */ - public static final int PRECACHE_TASK_LOAD_LIBRARY_FAIL = 3; - - /** - * Various failure reasons due to which precache task was cancelled. - */ - public static final int PRECACHE_CANCEL_NO_UNMETERED_NETWORK = 4; - public static final int PRECACHE_CANCEL_NO_POWER = 5; - public static final int PRECACHE_CANCEL_DISABLED_PREF = 6; - public static final int DISABLED_IN_PRECACHE_PREF = 7; - public static final int SYNC_SERVICE_TIMEOUT = 8; - public static final int PRECACHE_SESSION_TIMEOUT = 9; - - /** - * Precache session started. - */ - public static final int PRECACHE_SESSION_STARTED = 10; - - /** - * Precache task was scheduled. The task can be periodic or one-off completion task. The - * result of scheduling can be success or failure. The periodic task can be scheduled due to - * Chrome upgrade or at startup. - */ - public static final int PERIODIC_TASK_SCHEDULE_STARTUP = 11; - public static final int PERIODIC_TASK_SCHEDULE_STARTUP_FAIL = 12; - public static final int PERIODIC_TASK_SCHEDULE_UPGRADE = 13; - public static final int PERIODIC_TASK_SCHEDULE_UPGRADE_FAIL = 14; - public static final int ONEOFF_TASK_SCHEDULE = 15; - public static final int ONEOFF_TASK_SCHEDULE_FAIL = 16; - - /** - * Precache session completed successfully or unsuccessfully. - */ - public static final int PRECACHE_SESSION_COMPLETE = 17; - public static final int PRECACHE_SESSION_INCOMPLETE = 18; - - /** - * Limit of the events. - */ - public static final int EVENT_START = 0; - public static final int EVENT_END = 19; - - @VisibleForTesting - static int getBitPosition(int event) { - assert (event >= EVENT_START) && (event < EVENT_END); - return event; - } - - @VisibleForTesting - static long getBitMask(int event) { - assert (event >= EVENT_START) && (event < EVENT_END); - return 1L << event; - } - - @VisibleForTesting - static int[] getEventsFromBitMask(long bitmask) { - int[] events = new int[EVENT_END]; - int filledEvents = 0; - for (int event = EVENT_START; event < EVENT_END; ++event) { - if ((getBitMask(event) & bitmask) != 0L) { - events[filledEvents] = event; - ++filledEvents; - } - } - return Arrays.copyOf(events, filledEvents); - } - - @VisibleForTesting - static long addEventToBitMask(long bitmask, int event) { - return bitmask | getBitMask(event); - } - } - - static final String PREF_PERSISTENCE_METRICS = "precache.persistent_metrics"; - static final String EVENTS_HISTOGRAM = "Precache.Events"; - - /** - * Record the precache event. The event is persisted in shared preferences if the native library - * is not loaded. If library is loaded, the event will be recorded as UMA metric, and any prior - * persisted events are recorded to UMA as well. - * @param event the precache event. - */ - public static void record(int event) { - SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences(); - long persistent_metric = sharedPreferences.getLong(PREF_PERSISTENCE_METRICS, 0); - Editor preferencesEditor = sharedPreferences.edit(); - - if (LibraryLoader.isInitialized()) { - RecordHistogram.recordEnumeratedHistogram( - EVENTS_HISTOGRAM, Event.getBitPosition(event), Event.EVENT_END); - for (int e : Event.getEventsFromBitMask(persistent_metric)) { - RecordHistogram.recordEnumeratedHistogram( - EVENTS_HISTOGRAM, Event.getBitPosition(e), Event.EVENT_END); - } - preferencesEditor.remove(PREF_PERSISTENCE_METRICS); - } else { - // Save the metric in preferences. - persistent_metric = Event.addEventToBitMask(persistent_metric, event); - preferencesEditor.putLong(PREF_PERSISTENCE_METRICS, persistent_metric); - } - preferencesEditor.apply(); - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/precache/SyncServiceInitializedNotifier.java b/chrome/android/java/src/org/chromium/chrome/browser/precache/SyncServiceInitializedNotifier.java deleted file mode 100644 index a96ee34d..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/precache/SyncServiceInitializedNotifier.java +++ /dev/null
@@ -1,85 +0,0 @@ -// 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. -package org.chromium.chrome.browser.precache; - -import org.chromium.base.ThreadUtils; -import org.chromium.chrome.browser.sync.ProfileSyncService; - -import java.util.Set; -import java.util.concurrent.FutureTask; - -/** - * Provides a timeoutable interface to wait for ProfileSyncService backend initialization and - * configuration of a set of sync datatypes. If the sync service backend state successfully - * initializes and configuration is complete for all the given sync datatypes, onDataTypesActive() - * will be called. Otherwise onFailureOrTimedOut() will be invoked after a specified timeout. - * - * Objects of this class should be created and used only in the UI thread. - */ -public class SyncServiceInitializedNotifier implements ProfileSyncService.SyncStateChangedListener { - /** - * Listener for the sync service backend initialization or timeout. - */ - public interface Listener { - // Invoked when the backend is initialized, and configuration done for the datatypes. - public void onDataTypesActive(); - - // Invoked when timed-out. - public void onFailureOrTimedOut(); - } - - private ProfileSyncService mSyncService; - private Set<Integer> mActiveDataTypes; - private Listener mListener; - private FutureTask<?> mTimeoutTask; - - public SyncServiceInitializedNotifier( - Set<Integer> activeDataTypes, Listener listener, long timeoutMillis) { - assert listener != null; - ThreadUtils.assertOnUiThread(); - mListener = listener; - mActiveDataTypes = activeDataTypes; - - mSyncService = ProfileSyncService.get(); - if (mSyncService == null) { - onFailureOrTimedOut(); - return; - } - mSyncService.addSyncStateChangedListener(this); - mTimeoutTask = new FutureTask<Void>(new Runnable() { - @Override - public void run() { - onFailureOrTimedOut(); - } - }, null); - ThreadUtils.postOnUiThreadDelayed(mTimeoutTask, timeoutMillis); - // Call the listener once, in case the sync service configuration is already done. - syncStateChanged(); - } - - @Override - public void syncStateChanged() { - ThreadUtils.assertOnUiThread(); - assert mSyncService != null; - if (mSyncService.isSyncActive() - && mSyncService.getActiveDataTypes().containsAll(mActiveDataTypes)) { - onDataTypesActive(); - } - } - - private void onDataTypesActive() { - mSyncService.removeSyncStateChangedListener(this); - if (!mTimeoutTask.isDone()) { - mTimeoutTask.cancel(false); - } - mListener.onDataTypesActive(); - } - - private void onFailureOrTimedOut() { - if (mSyncService != null) { - mSyncService.removeSyncStateChangedListener(this); - } - mListener.onFailureOrTimedOut(); - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappActivity.java index 278044d..9d77a15 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappActivity.java
@@ -127,11 +127,9 @@ protected void initializeUI(Bundle savedInstanceState) { // We do not load URL when restoring from saved instance states. - if (savedInstanceState == null && mWebappInfo.isInitialized()) { - if (TextUtils.isEmpty(getActivityTab().getUrl())) { - getActivityTab().loadUrl(new LoadUrlParams( - mWebappInfo.uri().toString(), PageTransition.AUTO_TOPLEVEL)); - } + if (savedInstanceState == null) { + getActivityTab().loadUrl( + new LoadUrlParams(mWebappInfo.uri().toString(), PageTransition.AUTO_TOPLEVEL)); } else { if (NetworkChangeNotifier.isOnline()) getActivityTab().reloadIgnoringCache(); }
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index a407dd6..a040b801 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -842,12 +842,6 @@ "java/src/org/chromium/chrome/browser/physicalweb/UrlManager.java", "java/src/org/chromium/chrome/browser/physicalweb/Utils.java", "java/src/org/chromium/chrome/browser/policy/PolicyAuditor.java", - "java/src/org/chromium/chrome/browser/precache/FailureReason.java", - "java/src/org/chromium/chrome/browser/precache/PrecacheController.java", - "java/src/org/chromium/chrome/browser/precache/PrecacheLauncher.java", - "java/src/org/chromium/chrome/browser/precache/PrecacheTaskScheduler.java", - "java/src/org/chromium/chrome/browser/precache/PrecacheUMA.java", - "java/src/org/chromium/chrome/browser/precache/SyncServiceInitializedNotifier.java", "java/src/org/chromium/chrome/browser/preferences/AboutChromePreferences.java", "java/src/org/chromium/chrome/browser/preferences/AccessibilityPreferences.java", "java/src/org/chromium/chrome/browser/preferences/ButtonPreference.java", @@ -1597,10 +1591,6 @@ "javatests/src/org/chromium/chrome/browser/permissions/PermissionNavigationTest.java", "javatests/src/org/chromium/chrome/browser/permissions/PermissionTestCaseBase.java", "javatests/src/org/chromium/chrome/browser/permissions/QuotaTest.java", - "javatests/src/org/chromium/chrome/browser/precache/MockPrecacheController.java", - "javatests/src/org/chromium/chrome/browser/precache/PrecacheLauncherTest.java", - "javatests/src/org/chromium/chrome/browser/precache/PrecacheControllerTest.java", - "javatests/src/org/chromium/chrome/browser/precache/PrecacheUMATest.java", "javatests/src/org/chromium/chrome/browser/preferences/PasswordViewingTypeTest.java", "javatests/src/org/chromium/chrome/browser/preferences/PreferencesTest.java", "javatests/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionPromoUtilsTest.java", @@ -1690,7 +1680,6 @@ "javatests/src/org/chromium/chrome/browser/webapps/WebappAuthenticatorTest.java", "javatests/src/org/chromium/chrome/browser/webapps/WebappDeferredStartupTest.java", "javatests/src/org/chromium/chrome/browser/webapps/WebappDirectoryManagerTest.java", - "javatests/src/org/chromium/chrome/browser/webapps/WebappInfoTest.java", "javatests/src/org/chromium/chrome/browser/webapps/WebappModeTest.java", "javatests/src/org/chromium/chrome/browser/webapps/WebappNavigationTest.java", "javatests/src/org/chromium/chrome/browser/webapps/WebappSplashScreenBackgroundColorTest.java", @@ -1824,6 +1813,7 @@ "junit/src/org/chromium/chrome/browser/tabstate/TabStateUnitTest.java", "junit/src/org/chromium/chrome/browser/webapps/WebappDataStorageTest.java", "junit/src/org/chromium/chrome/browser/webapps/WebappRegistryTest.java", + "junit/src/org/chromium/chrome/browser/webapps/WebappInfoTest.java", "junit/src/org/chromium/chrome/browser/webapps/WebApkInfoTest.java", "junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerTest.java", "junit/src/org/chromium/chrome/browser/widget/selection/SelectionDelegateTest.java",
diff --git a/chrome/android/javatests/DEPS b/chrome/android/javatests/DEPS index 9e458c7f..40bc3b5 100644 --- a/chrome/android/javatests/DEPS +++ b/chrome/android/javatests/DEPS
@@ -10,7 +10,6 @@ "+components/navigation_interception", "+components/offline_items_collection/core/android/java", "+components/payments/content/android/java/src/org/chromium/components/payments", - "+components/precache/android/javatests", "+components/sync/android/java/src/org/chromium/components/sync", # We should only depend on the util package of something that lives in # javatests.
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/precache/MockPrecacheController.java b/chrome/android/javatests/src/org/chromium/chrome/browser/precache/MockPrecacheController.java deleted file mode 100644 index bf6fd56..0000000 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/precache/MockPrecacheController.java +++ /dev/null
@@ -1,44 +0,0 @@ -// 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. - -package org.chromium.chrome.browser.precache; - -import android.content.Context; - -import java.util.EnumSet; - -/** - * PrecacheController class with wakelocks mocked out. - */ -public class MockPrecacheController extends PrecacheController { - public int acquiredLockCnt = 0; - public int releasedLockCnt = 0; - - MockPrecacheController(Context context) { - super(context); - } - - @Override - void startPrecachingAfterSyncInit() { - super.startPrecaching(); - } - - @Override - void acquirePrecachingWakeLock() { - acquiredLockCnt++; - } - - @Override - void releasePrecachingWakeLock() { - releasedLockCnt++; - } - - @Override - EnumSet<FailureReason> interruptionReasons(Context context) { - return null; - } - - @Override - void recordFailureReasons(Context context) {} -}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/precache/OWNERS b/chrome/android/javatests/src/org/chromium/chrome/browser/precache/OWNERS deleted file mode 100644 index f24d985..0000000 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/precache/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -file://components/precache/OWNERS \ No newline at end of file
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheControllerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheControllerTest.java deleted file mode 100644 index 2d37fe6..0000000 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheControllerTest.java +++ /dev/null
@@ -1,322 +0,0 @@ -// 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. - -package org.chromium.chrome.browser.precache; - -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences.Editor; -import android.support.test.InstrumentationRegistry; -import android.support.test.annotation.UiThreadTest; -import android.support.test.filters.SmallTest; -import android.support.test.rule.UiThreadTestRule; - -import com.google.android.gms.gcm.GcmNetworkManager; -import com.google.android.gms.gcm.Task; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.chromium.base.ContextUtils; -import org.chromium.base.metrics.RecordHistogram; -import org.chromium.base.test.util.AdvancedMockContext; -import org.chromium.base.test.util.Feature; -import org.chromium.base.test.util.RetryOnFailure; -import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.components.precache.MockDeviceState; - -/** - * Tests of {@link PrecacheController}. - */ -@RunWith(ChromeJUnit4ClassRunner.class) -public class PrecacheControllerTest { - private Context mContext; - private MockPrecacheLauncher mPrecacheLauncher; - private MockPrecacheController mPrecacheController; - private MockPrecacheTaskScheduler mPrecacheTaskScheduler; - - @Rule - public UiThreadTestRule mRule = new UiThreadTestRule(); - - /** - * Mock of the {@link PrecacheLauncher}. - */ - static class MockPrecacheLauncher extends PrecacheLauncher { - - private MockPrecacheController mController; - - public int destroyCnt = 0; - public int startCnt = 0; - public int cancelCnt = 0; - - public void setController(MockPrecacheController controller) { - mController = controller; - } - - @Override - public void destroy() { - destroyCnt++; - } - - @Override - public void start() { - startCnt++; - } - - @Override - public void cancel() { - cancelCnt++; - } - - @Override - protected void onPrecacheCompleted(boolean precacheStarted) { - mController.handlePrecacheCompleted(precacheStarted); - } - } - - static class MockPrecacheTaskScheduler extends PrecacheTaskScheduler { - public int schedulePeriodicCnt = 0; - public int scheduleContinuationCnt = 0; - public int cancelPeriodicCnt = 0; - public int cancelContinuationCnt = 0; - - @Override - boolean canScheduleTasks(Context context) { - return false; - } - - @Override - boolean scheduleTask(Context context, Task task) { - if (!canScheduleTasks(context)) return true; - if (PrecacheController.PERIODIC_TASK_TAG.equals(task.getTag())) { - schedulePeriodicCnt++; - } else if (PrecacheController.CONTINUATION_TASK_TAG.equals(task.getTag())) { - scheduleContinuationCnt++; - } - return true; - } - - @Override - boolean cancelTask(Context context, String tag) { - if (PrecacheController.PERIODIC_TASK_TAG.equals(tag)) { - cancelPeriodicCnt++; - } else if (PrecacheController.CONTINUATION_TASK_TAG.equals(tag)) { - cancelContinuationCnt++; - } - return true; - } - } - - @Before - public void setUp() throws Exception { - mContext = new AdvancedMockContext( - InstrumentationRegistry.getInstrumentation().getTargetContext()); - mPrecacheLauncher = new MockPrecacheLauncher(); - mPrecacheController = new MockPrecacheController(mContext); - mPrecacheTaskScheduler = new MockPrecacheTaskScheduler(); - mPrecacheLauncher.setController(mPrecacheController); - mPrecacheController.setPrecacheLauncher(mPrecacheLauncher); - PrecacheController.setTaskScheduler(mPrecacheTaskScheduler); - RecordHistogram.setDisabledForTests(true); - Editor editor = ContextUtils.getAppSharedPreferences().edit(); - editor.putBoolean(PrecacheController.PREF_IS_PRECACHING_ENABLED, false); - editor.apply(); - } - - @After - public void tearDown() throws Exception { - RecordHistogram.setDisabledForTests(false); - } - - protected void verifyScheduledAndCanceledCounts( - int expectedPeriodicScheduled, int expectedContinuationScheduled, - int expectedPeriodicCanceled, int expectedContinuationCanceled) { - if (!mPrecacheTaskScheduler.canScheduleTasks(mContext)) { - expectedPeriodicScheduled = 0; - expectedContinuationScheduled = 0; - } - Assert.assertEquals(expectedPeriodicScheduled, mPrecacheTaskScheduler.schedulePeriodicCnt); - Assert.assertEquals( - expectedContinuationScheduled, mPrecacheTaskScheduler.scheduleContinuationCnt); - Assert.assertEquals(expectedPeriodicCanceled, mPrecacheTaskScheduler.cancelPeriodicCnt); - Assert.assertEquals( - expectedContinuationCanceled, mPrecacheTaskScheduler.cancelContinuationCnt); - } - - protected void verifyLockCounts(int expectedAcquired, int expectedReleased) { - Assert.assertEquals(expectedAcquired, mPrecacheController.acquiredLockCnt); - Assert.assertEquals(expectedReleased, mPrecacheController.releasedLockCnt); - } - - protected void verifyBeginPrecaching() { - PrecacheController.setIsPrecachingEnabled(mContext, true); - Assert.assertEquals(GcmNetworkManager.RESULT_SUCCESS, - mPrecacheController.precache(PrecacheController.PERIODIC_TASK_TAG)); - Assert.assertTrue(mPrecacheController.isPrecaching()); - verifyLockCounts(1, 0); - // Any existing completion tasks are canceled. - verifyScheduledAndCanceledCounts(1, 0, 0, 1); - Assert.assertEquals(1, mPrecacheLauncher.startCnt); - } - - protected void verifyContinuationGetsPreemptedByPeriodicTask() { - PrecacheController.setIsPrecachingEnabled(mContext, true); - Assert.assertEquals(GcmNetworkManager.RESULT_SUCCESS, - mPrecacheController.precache(PrecacheController.CONTINUATION_TASK_TAG)); - Assert.assertTrue(mPrecacheController.isPrecaching()); - verifyLockCounts(1, 0); - // Any existing completion tasks are canceled. - verifyScheduledAndCanceledCounts(1, 0, 0, 1); - Assert.assertEquals(1, mPrecacheLauncher.startCnt); - } - - @Test - @SmallTest - @Feature({"Precache"}) - @UiThreadTest - public void testStartPrecachingNotEnabled() { - PrecacheController.setIsPrecachingEnabled(mContext, false); - verifyScheduledAndCanceledCounts(0, 0, 0, 0); - Assert.assertEquals(0, mPrecacheLauncher.startCnt); - Assert.assertTrue(mPrecacheController.precache(PrecacheController.PERIODIC_TASK_TAG) - == GcmNetworkManager.RESULT_SUCCESS); - Assert.assertFalse(mPrecacheController.isPrecaching()); - verifyLockCounts(0, 0); - // All tasks are canceled. - verifyScheduledAndCanceledCounts(0, 0, 1, 1); - Assert.assertEquals(0, mPrecacheLauncher.startCnt); - } - - @Test - @SmallTest - @Feature({"Precache"}) - @UiThreadTest - public void testStartPrecachingEnabled() { - verifyBeginPrecaching(); - - mPrecacheLauncher.onPrecacheCompleted(true); - Assert.assertFalse(mPrecacheController.isPrecaching()); - // A continuation task is scheduled. - verifyScheduledAndCanceledCounts(1, 1, 0, 1); - verifyLockCounts(1, 1); - } - - @Test - @SmallTest - @Feature({"Precache"}) - @UiThreadTest - @RetryOnFailure - public void testStartWhenAlreadyStarted() { - verifyBeginPrecaching(); - - Assert.assertEquals(GcmNetworkManager.RESULT_FAILURE, - mPrecacheController.precache(PrecacheController.PERIODIC_TASK_TAG)); - Assert.assertTrue(mPrecacheController.isPrecaching()); - // No additional tasks are scheduled or canceled. - verifyScheduledAndCanceledCounts(1, 0, 0, 1); - verifyLockCounts(1, 0); - } - - @Test - @SmallTest - @Feature({"Precache"}) - @UiThreadTest - @RetryOnFailure - public void testDeviceStateChangeCancels() { - verifyBeginPrecaching(); - - mPrecacheController.setDeviceState(new MockDeviceState(0, true, false)); - mPrecacheController.getDeviceStateReceiver().onReceive(mContext, new Intent()); - Assert.assertFalse(mPrecacheController.isPrecaching()); - // A continuation task is scheduled. - verifyScheduledAndCanceledCounts(1, 1, 0, 1); - verifyLockCounts(1, 1); - } - - @Test - @SmallTest - @Feature({"Precache"}) - @UiThreadTest - public void testDeviceStateChangeDoesNotCancel() { - verifyBeginPrecaching(); - - mPrecacheController.setDeviceState(new MockDeviceState(0, true, true)); - mPrecacheController.getDeviceStateReceiver().onReceive(mContext, new Intent()); - Assert.assertTrue(mPrecacheController.isPrecaching()); - // No additional tasks are scheduled or canceled. - verifyScheduledAndCanceledCounts(1, 0, 0, 1); - verifyLockCounts(1, 0); - } - - @Test - @SmallTest - @Feature({"Precache"}) - @UiThreadTest - @RetryOnFailure - public void testDeviceStateChangeWhenNotPrecaching() { - Assert.assertFalse(mPrecacheController.isPrecaching()); - mPrecacheController.setDeviceState(new MockDeviceState(0, false, true)); - mPrecacheController.getDeviceStateReceiver().onReceive(mContext, new Intent()); - Assert.assertFalse(mPrecacheController.isPrecaching()); - // No tasks are scheduled or canceled. - verifyScheduledAndCanceledCounts(0, 0, 0, 0); - verifyLockCounts(0, 0); - // device state change when not running has no effect (maybe unregisters) - } - - @Test - @SmallTest - @Feature({"Precache"}) - @UiThreadTest - @RetryOnFailure - public void testTimeoutCancelsPrecaching() { - verifyBeginPrecaching(); - - mPrecacheController.getTimeoutRunnable().run(); - Assert.assertFalse(mPrecacheController.isPrecaching()); - // A continuation task is scheduled. - verifyScheduledAndCanceledCounts(1, 1, 0, 1); - verifyLockCounts(1, 1); - } - - @Test - @SmallTest - @Feature({"Precache"}) - @UiThreadTest - @RetryOnFailure - public void testTimeoutDoesNotCancelIfNotPrecaching() { - Assert.assertFalse(mPrecacheController.isPrecaching()); - - mPrecacheController.getTimeoutRunnable().run(); - Assert.assertFalse(mPrecacheController.isPrecaching()); - // No tasks are scheduled or canceled. - verifyScheduledAndCanceledCounts(0, 0, 0, 0); - verifyLockCounts(0, 0); - } - - @Test - @SmallTest - @Feature({"Precache"}) - @UiThreadTest - @RetryOnFailure - public void testPrecachingEnabledPreferences() { - // Initial enable will schedule a periodic task. - PrecacheController.setIsPrecachingEnabled(mContext, true); - verifyScheduledAndCanceledCounts(1, 0, 0, 0); - // Subsequent enable will not schedule or cancel tasks. - PrecacheController.setIsPrecachingEnabled(mContext, true); - verifyScheduledAndCanceledCounts(1, 0, 0, 0); - - // Disabling will cancel periodic and one-off tasks. - PrecacheController.setIsPrecachingEnabled(mContext, false); - verifyScheduledAndCanceledCounts(1, 0, 1, 1); - // Subsequent disable will not schedule or cancel tasks. - PrecacheController.setIsPrecachingEnabled(mContext, false); - verifyScheduledAndCanceledCounts(1, 0, 1, 1); - } -}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheLauncherTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheLauncherTest.java deleted file mode 100644 index 4ff10a78..0000000 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheLauncherTest.java +++ /dev/null
@@ -1,277 +0,0 @@ -// 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. - -package org.chromium.chrome.browser.precache; - -import static org.chromium.base.test.util.Restriction.RESTRICTION_TYPE_NON_LOW_END_DEVICE; - -import android.content.Context; -import android.support.test.InstrumentationRegistry; -import android.support.test.filters.SmallTest; - -import com.google.android.gms.gcm.Task; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.chromium.base.ContextUtils; -import org.chromium.base.ThreadUtils; -import org.chromium.base.test.BaseJUnit4ClassRunner; -import org.chromium.base.test.util.Feature; -import org.chromium.base.test.util.Restriction; -import org.chromium.chrome.browser.preferences.privacy.PrivacyPreferencesManager; -import org.chromium.chrome.browser.sync.ProfileSyncService; -import org.chromium.chrome.browser.test.ChromeBrowserTestRule; - -import java.util.EnumSet; -import java.util.concurrent.Callable; - -/** - * Unit tests for {@link PrecacheLauncher}. - * - * setUp/tearDown code was inspired by org.chromium.chrome.browser.sync.ui.PassphraseActivityTest. - */ -@RunWith(BaseJUnit4ClassRunner.class) -public class PrecacheLauncherTest { - @Rule - public final ChromeBrowserTestRule mBrowserTestRule = new ChromeBrowserTestRule(); - - private StubProfileSyncService mSync; - private PrecacheLauncherUnderTest mLauncher; - private MockPrecacheTaskScheduler mPrecacheTaskScheduler; - - private class PrecacheLauncherUnderTest extends PrecacheLauncher { - private boolean mShouldRun = false; - - @Override - protected void onPrecacheCompleted(boolean tryAgainSoon) {} - - @Override - boolean nativeShouldRun() { - return mShouldRun; - } - - /** - * Modify the return value of nativeShouldRun. This will notify sync state subscribers, as - * if the user changed their sync preferences. - */ - void setShouldRun(boolean shouldRun) { - mShouldRun = shouldRun; - notifySyncChanged(); - } - } - - private static class StubProfileSyncService extends ProfileSyncService { - private boolean mEngineInitialized = false; - - public StubProfileSyncService() { - super(); - } - - @Override - public boolean isEngineInitialized() { - return mEngineInitialized; - } - - public void setEngineInitialized(boolean engineInitialized) { - mEngineInitialized = engineInitialized; - syncStateChanged(); - } - } - - static class MockPrecacheTaskScheduler extends PrecacheTaskScheduler { - @Override - boolean scheduleTask(Context context, Task task) { - return true; - } - - @Override - boolean cancelTask(Context context, String tag) { - return true; - } - } - - @Before - public void setUp() throws Exception { - ContextUtils.initApplicationContext(getTargetContext().getApplicationContext()); - - // This is a PrecacheLauncher with a stubbed out nativeShouldRun so we can change that on - // the fly without needing to set up a sync engine. - mLauncher = new PrecacheLauncherUnderTest(); - - mPrecacheTaskScheduler = new MockPrecacheTaskScheduler(); - PrecacheController.setTaskScheduler(mPrecacheTaskScheduler); - - // The target context persists throughout the entire test run, and so leaks state between - // tests. We reset the is_precaching_enabled pref to false to make the test run consistent, - // in case another test class has modified this pref. - PrecacheController.setIsPrecachingEnabled(getTargetContext(), false); - - // ProfileSyncService must be initialized on the UI thread. Oddly, even though - // ThreadUtils.runningOnUiThread() is true here, it's, no, not really, no. - ThreadUtils.runOnUiThreadBlocking(new Runnable() { - @Override - public void run() { - // The StubProfileSyncService stubs out isEngineInitialized so we can change that - // on the fly. - mSync = new StubProfileSyncService(); - ProfileSyncService.overrideForTests(mSync); - // This is currently the default, but let's verify that, lest it ever change and we - // get confusing test failures later. - Assert.assertTrue(PrivacyPreferencesManager.getInstance().shouldPrerender()); - } - }); - } - - @After - public void tearDown() throws Exception { - ProfileSyncService.overrideForTests(null); - PrecacheController.setIsPrecachingEnabled(getTargetContext(), false); - } - - @Test - @SmallTest - @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) - @Feature({"Precache"}) - public void testUpdateEnabled_SyncNotReady_ThenDisabled() throws Throwable { - mLauncher.updateEnabled(getTargetContext()); - waitUntilUiThreadIdle(); - - Assert.assertEquals(false, isPrecachingEnabled()); - Assert.assertEquals(EnumSet.of(FailureReason.SYNC_NOT_INITIALIZED, - FailureReason.PRERENDER_PRIVACY_PREFERENCE_NOT_ENABLED, - FailureReason.NATIVE_SHOULD_RUN_IS_FALSE), - failureReasons()); - - setEngineInitialized(true); - Assert.assertEquals(false, isPrecachingEnabled()); - Assert.assertEquals(EnumSet.of(FailureReason.NATIVE_SHOULD_RUN_IS_FALSE), failureReasons()); - } - - @Test - @SmallTest - @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) - @Feature({"Precache"}) - public void testUpdateEnabled_SyncNotReady_ThenEnabled() throws Throwable { - mLauncher.updateEnabled(getTargetContext()); - waitUntilUiThreadIdle(); - - Assert.assertEquals(false, isPrecachingEnabled()); - Assert.assertEquals(EnumSet.of(FailureReason.SYNC_NOT_INITIALIZED, - FailureReason.PRERENDER_PRIVACY_PREFERENCE_NOT_ENABLED, - FailureReason.NATIVE_SHOULD_RUN_IS_FALSE), - failureReasons()); - - mLauncher.setShouldRun(true); - setEngineInitialized(true); - Assert.assertEquals(true, isPrecachingEnabled()); - Assert.assertEquals(EnumSet.noneOf(FailureReason.class), failureReasons()); - } - - @Test - @SmallTest - @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) - @Feature({"Precache"}) - public void testUpdateEnabled_Disabled_ThenEnabled() throws Throwable { - setEngineInitialized(true); - mLauncher.updateEnabled(getTargetContext()); - waitUntilUiThreadIdle(); - - Assert.assertEquals(false, isPrecachingEnabled()); - Assert.assertEquals(EnumSet.of(FailureReason.NATIVE_SHOULD_RUN_IS_FALSE), failureReasons()); - - mLauncher.setShouldRun(true); - Assert.assertEquals(true, isPrecachingEnabled()); - Assert.assertEquals(EnumSet.noneOf(FailureReason.class), failureReasons()); - } - - @Test - @SmallTest - @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) - @Feature({"Precache"}) - public void testUpdateEnabled_Enabled_ThenDisabled() throws Throwable { - mLauncher.setShouldRun(true); - setEngineInitialized(true); - mLauncher.updateEnabled(InstrumentationRegistry.getTargetContext()); - waitUntilUiThreadIdle(); - - Assert.assertEquals(true, isPrecachingEnabled()); - Assert.assertEquals(EnumSet.noneOf(FailureReason.class), failureReasons()); - - mLauncher.setShouldRun(false); - Assert.assertEquals(false, isPrecachingEnabled()); - Assert.assertEquals(EnumSet.of(FailureReason.NATIVE_SHOULD_RUN_IS_FALSE), failureReasons()); - } - - @Test - @SmallTest - @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) - @Feature({"Precache"}) - public void testUpdateEnabledNullProfileSyncService() throws Throwable { - ProfileSyncService.overrideForTests(null); - - mLauncher.updateEnabled(getTargetContext()); - waitUntilUiThreadIdle(); - - Assert.assertEquals(false, isPrecachingEnabled()); - Assert.assertEquals(EnumSet.of(FailureReason.SYNC_NOT_INITIALIZED, - FailureReason.PRERENDER_PRIVACY_PREFERENCE_NOT_ENABLED, - FailureReason.NATIVE_SHOULD_RUN_IS_FALSE), - failureReasons()); - } - - /** Return the Context for the Chromium app. */ - private Context getTargetContext() { - return InstrumentationRegistry.getInstrumentation().getTargetContext(); - } - - /** Block until all tasks posted to the UI thread have completed. */ - private void waitUntilUiThreadIdle() { - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); - } - - /** Return the value of the is_precaching_enabled pref, as set by updateEnabledSync. */ - private boolean isPrecachingEnabled() { - return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<Boolean>() { - @Override - public Boolean call() { - return PrecacheController.get(getTargetContext()).isPrecachingEnabled(); - } - }); - } - - /** Return the set of failure reasons for mLauncher. */ - private EnumSet<FailureReason> failureReasons() { - return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<EnumSet<FailureReason>>() { - @Override - public EnumSet<FailureReason> call() { - return mLauncher.failureReasons(); - } - }); - } - - /** Pretend the sync engine is initialized or not. */ - private void setEngineInitialized(final boolean syncInitialized) { - ThreadUtils.runOnUiThreadBlocking(new Runnable() { - @Override - public void run() { - mSync.setEngineInitialized(syncInitialized); - } - }); - } - - /** Notify listeners that sync preferences have changed. This is run by setShouldRun. */ - private void notifySyncChanged() { - ThreadUtils.runOnUiThreadBlocking(new Runnable() { - @Override - public void run() { - mSync.syncStateChanged(); - } - }); - } -}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheUMATest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheUMATest.java deleted file mode 100644 index 7c7dc4cfe..0000000 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheUMATest.java +++ /dev/null
@@ -1,171 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.precache; - -import android.support.test.InstrumentationRegistry; -import android.support.test.filters.SmallTest; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.chromium.base.ContextUtils; -import org.chromium.base.library_loader.LibraryLoader; -import org.chromium.base.test.BaseJUnit4ClassRunner; -import org.chromium.base.test.util.Feature; -import org.chromium.base.test.util.MetricsUtils.HistogramDelta; -import org.chromium.base.test.util.RetryOnFailure; -import org.chromium.chrome.test.util.browser.signin.SigninTestUtil; -import org.chromium.content.browser.test.NativeLibraryTestRule; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Tests of {@link PrecacheUMA}. - */ -@RunWith(BaseJUnit4ClassRunner.class) -public class PrecacheUMATest { - @Rule - public NativeLibraryTestRule mActivityTestRule = new NativeLibraryTestRule(); - - @Before - public void setUp() { - // TODO (thildebr): This is just copied from the ChromeBrowserTestRule because we need to - // be selective of when we load the native library, so we can't just use the rule. - SigninTestUtil.setUpAuthForTest(InstrumentationRegistry.getInstrumentation()); - } - - @After - public void tearDown() { - // TODO (thildebr): Also copied from ChromeBrowserTestRule until there's a better way. - SigninTestUtil.resetSigninState(); - SigninTestUtil.tearDownAuthForTest(); - } - - @Test - @SmallTest - @Feature({"Precache"}) - public void testUMAEventBitPositionAndMask() { - // Test the bitmask and bit position of all UMA Events. - for (int event = PrecacheUMA.Event.EVENT_START; event < PrecacheUMA.Event.EVENT_END; - ++event) { - long bitmask = PrecacheUMA.Event.getBitMask(event); - Assert.assertTrue(bitmask > 0); - Assert.assertEquals(bitmask, 1L << PrecacheUMA.Event.getBitPosition(event)); - } - } - - @Test - @SmallTest - @Feature({"Precache"}) - public void testEventsInBitMask() { - int[] events = {PrecacheUMA.Event.PRECACHE_TASK_STARTED_PERIODIC, - PrecacheUMA.Event.PRECACHE_CANCEL_NO_UNMETERED_NETWORK, - PrecacheUMA.Event.PRECACHE_SESSION_STARTED, - PrecacheUMA.Event.PRECACHE_SESSION_COMPLETE}; - - long bitmask = 0; - for (int event : events) { - bitmask = PrecacheUMA.Event.addEventToBitMask(bitmask, event); - } - assert Arrays.equals(events, PrecacheUMA.Event.getEventsFromBitMask(bitmask)); - } - - @Test - @SmallTest - @Feature({"Precache"}) - @RetryOnFailure - public void testRecordUMA_NativeLibraryNotLoaded() { - // Tests that events are saved in preferences when native library is not loaded. - List<Integer> events = new ArrayList<>(); - events.add(PrecacheUMA.Event.PRECACHE_TASK_STARTED_PERIODIC); - events.add(PrecacheUMA.Event.PRECACHE_CANCEL_NO_UNMETERED_NETWORK); - events.add(PrecacheUMA.Event.PRECACHE_SESSION_STARTED); - events.add(PrecacheUMA.Event.PRECACHE_SESSION_COMPLETE); - - long bitmask = 0; - for (int event : events) { - PrecacheUMA.record(event); - bitmask = PrecacheUMA.Event.addEventToBitMask(bitmask, event); - } - Assert.assertEquals(false, LibraryLoader.isInitialized()); - Assert.assertEquals(bitmask, - ContextUtils.getAppSharedPreferences().getLong( - PrecacheUMA.PREF_PERSISTENCE_METRICS, 0)); - - mActivityTestRule.loadNativeLibraryAndInitBrowserProcess(); - Assert.assertEquals(true, LibraryLoader.isInitialized()); - - // When the library is initialized the events saved in preferences are dumped to histograms. - HistogramDelta histograms[] = new HistogramDelta[PrecacheUMA.Event.EVENT_END]; - for (int event = PrecacheUMA.Event.EVENT_START; event < PrecacheUMA.Event.EVENT_END; - ++event) { - histograms[PrecacheUMA.Event.getBitPosition(event)] = new HistogramDelta( - PrecacheUMA.EVENTS_HISTOGRAM, PrecacheUMA.Event.getBitPosition(event)); - } - - // The next event will trigger the recording of the UMA metric. - PrecacheUMA.record(PrecacheUMA.Event.PERIODIC_TASK_SCHEDULE_UPGRADE); - events.add(PrecacheUMA.Event.PERIODIC_TASK_SCHEDULE_UPGRADE); - Assert.assertEquals(0, - ContextUtils.getAppSharedPreferences().getLong( - PrecacheUMA.PREF_PERSISTENCE_METRICS, 0)); - - for (int event = PrecacheUMA.Event.EVENT_START; event < PrecacheUMA.Event.EVENT_END; - ++event) { - if (events.contains(event)) { - Assert.assertEquals( - 1, histograms[PrecacheUMA.Event.getBitPosition(event)].getDelta()); - } else { - Assert.assertEquals( - 0, histograms[PrecacheUMA.Event.getBitPosition(event)].getDelta()); - } - } - } - - @Test - @SmallTest - @Feature({"Precache"}) - @RetryOnFailure - public void testRecordUMA_NativeLibraryLoaded() { - // Test that events are recorded as UMA metric when library is initialized. - List<Integer> events = new ArrayList<>(); - events.add(PrecacheUMA.Event.PRECACHE_TASK_STARTED_PERIODIC); - events.add(PrecacheUMA.Event.PRECACHE_CANCEL_NO_UNMETERED_NETWORK); - events.add(PrecacheUMA.Event.PRECACHE_SESSION_STARTED); - events.add(PrecacheUMA.Event.PRECACHE_SESSION_COMPLETE); - - mActivityTestRule.loadNativeLibraryAndInitBrowserProcess(); - Assert.assertEquals(true, LibraryLoader.isInitialized()); - - HistogramDelta histograms[] = new HistogramDelta[PrecacheUMA.Event.EVENT_END]; - for (int event = PrecacheUMA.Event.EVENT_START; event < PrecacheUMA.Event.EVENT_END; - ++event) { - histograms[PrecacheUMA.Event.getBitPosition(event)] = new HistogramDelta( - PrecacheUMA.EVENTS_HISTOGRAM, PrecacheUMA.Event.getBitPosition(event)); - } - for (int event : events) { - PrecacheUMA.record(event); - Assert.assertEquals(0, - ContextUtils.getAppSharedPreferences().getLong( - PrecacheUMA.PREF_PERSISTENCE_METRICS, 0)); - } - for (int event = PrecacheUMA.Event.EVENT_START; event < PrecacheUMA.Event.EVENT_END; - ++event) { - if (events.contains(event)) { - Assert.assertEquals( - 1, histograms[PrecacheUMA.Event.getBitPosition(event)].getDelta()); - } else { - Assert.assertEquals( - 0, histograms[PrecacheUMA.Event.getBitPosition(event)].getDelta()); - } - } - } -}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappInfoTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappInfoTest.java similarity index 92% rename from chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappInfoTest.java rename to chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappInfoTest.java index b2475c7..6b7e3f13 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappInfoTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappInfoTest.java
@@ -5,27 +5,25 @@ package org.chromium.chrome.browser.webapps; import android.content.Intent; -import android.support.test.filters.SmallTest; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; -import org.chromium.base.test.util.Feature; import org.chromium.blink_public.platform.WebDisplayMode; import org.chromium.chrome.browser.ShortcutHelper; import org.chromium.chrome.browser.ShortcutSource; -import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.content_public.common.ScreenOrientationValues; +import org.chromium.testing.local.LocalRobolectricTestRunner; /** * Tests the WebappInfo class's ability to parse various URLs. */ -@RunWith(ChromeJUnit4ClassRunner.class) +@RunWith(LocalRobolectricTestRunner.class) +@Config(manifest = Config.NONE) public class WebappInfoTest { @Test - @SmallTest - @Feature({"Webapps"}) public void testAbout() { String id = "webapp id"; String name = "longName"; @@ -40,8 +38,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testRandomUrl() { String id = "webapp id"; String name = "longName"; @@ -56,8 +52,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testSpacesInUrl() { String id = "webapp id"; String name = "longName"; @@ -75,8 +69,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testIntentTitleFallBack() { String title = "webapp title"; @@ -89,8 +81,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testIntentNameBlankNoTitle() { String shortName = "name"; @@ -103,8 +93,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testIntentShortNameFallBack() { String title = "webapp title"; String shortName = "name"; @@ -119,8 +107,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testIntentNameShortname() { String name = "longName"; String shortName = "name"; @@ -135,8 +121,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testDisplayModeAndOrientationAndSource() { String id = "webapp id"; String name = "longName"; @@ -153,8 +137,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testNormalColors() { String id = "webapp id"; String name = "longName"; @@ -171,8 +153,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testInvalidOrMissingColors() { String id = "webapp id"; String name = "longName"; @@ -189,8 +169,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testColorsIntentCreation() { long themeColor = 0xFF00FF00L; long backgroundColor = 0xFF0000FFL; @@ -205,8 +183,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testScopeIntentCreation() { String scope = "https://www.foo.com"; Intent intent = createIntentWithUrlAndId(); @@ -216,8 +192,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testIntentScopeFallback() { String url = "https://www.foo.com/homepage.html"; Intent intent = createIntentWithUrlAndId(); @@ -227,8 +201,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testIntentDisplayMode() { Intent intent = createIntentWithUrlAndId(); intent.putExtra(ShortcutHelper.EXTRA_DISPLAY_MODE, WebDisplayMode.MINIMAL_UI); @@ -237,8 +209,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testIntentOrientation() { Intent intent = createIntentWithUrlAndId(); intent.putExtra(ShortcutHelper.EXTRA_ORIENTATION, ScreenOrientationValues.LANDSCAPE); @@ -247,8 +217,6 @@ } @Test - @SmallTest - @Feature({"Webapps"}) public void testIntentGeneratedIcon() { String id = "webapp id"; String name = "longName";
diff --git a/chrome/android/webapk/shell_apk/res/layout/choose_host_browser_dialog.xml b/chrome/android/webapk/shell_apk/res/layout/choose_host_browser_dialog.xml index bb8c584b7..20c2f07 100644 --- a/chrome/android/webapk/shell_apk/res/layout/choose_host_browser_dialog.xml +++ b/chrome/android/webapk/shell_apk/res/layout/choose_host_browser_dialog.xml
@@ -13,8 +13,6 @@ android:id="@+id/desc" android:textColor="@android:color/black" android:textAppearance="@android:style/TextAppearance.DeviceDefault.Small" - android:paddingStart="20dp" - android:paddingEnd="20dp" android:layout_width="match_parent" android:layout_height="wrap_content" />
diff --git a/chrome/android/webapk/shell_apk/res/layout/host_browser_list_item.xml b/chrome/android/webapk/shell_apk/res/layout/host_browser_list_item.xml index a500a1fe..726504ac 100644 --- a/chrome/android/webapk/shell_apk/res/layout/host_browser_list_item.xml +++ b/chrome/android/webapk/shell_apk/res/layout/host_browser_list_item.xml
@@ -16,12 +16,10 @@ android:contentDescription="@null" android:layout_width="48dp" android:layout_height="48dp" - android:paddingStart="20dp" android:layout_gravity="start" /> <TextView android:id="@+id/browser_name" - android:paddingStart="20dp" android:layout_gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" />
diff --git a/chrome/android/webapk/shell_apk/shell_apk_version.gni b/chrome/android/webapk/shell_apk/shell_apk_version.gni index f9b3db1..def53e2 100644 --- a/chrome/android/webapk/shell_apk/shell_apk_version.gni +++ b/chrome/android/webapk/shell_apk/shell_apk_version.gni
@@ -6,7 +6,7 @@ # (including AndroidManifest.xml) is updated. This version should be incremented # prior to uploading a new ShellAPK to the WebAPK Minting Server. # Does not affect Chrome.apk -template_shell_apk_version = 14 +template_shell_apk_version = 15 # The ShellAPK version expected by Chrome. Chrome will try to update the WebAPK # if the WebAPK's ShellAPK version is less than |expected_shell_apk_version|.
diff --git a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/ChooseHostBrowserDialog.java b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/ChooseHostBrowserDialog.java index 7a86e61..c2862b8 100644 --- a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/ChooseHostBrowserDialog.java +++ b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/ChooseHostBrowserDialog.java
@@ -95,6 +95,7 @@ TextView desc = (TextView) view.findViewById(R.id.desc); ListView browserList = (ListView) view.findViewById(R.id.browser_list); desc.setText(R.string.choose_host_browser); + WebApkUtils.setPadding(desc, context, WebApkUtils.PADDING_DP, 0, WebApkUtils.PADDING_DP, 0); browserList.setAdapter(new BrowserArrayAdapter(context, browserItems)); // The context theme wrapper is needed for pre-L. @@ -177,7 +178,9 @@ } TextView name = (TextView) convertView.findViewById(R.id.browser_name); + WebApkUtils.setPadding(name, mContext, WebApkUtils.PADDING_DP, 0, 0, 0); ImageView icon = (ImageView) convertView.findViewById(R.id.browser_icon); + WebApkUtils.setPadding(icon, mContext, WebApkUtils.PADDING_DP, 0, 0, 0); BrowserItem item = mBrowsers.get(position); name.setEnabled(item.supportsWebApks());
diff --git a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/InstallHostBrowserDialog.java b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/InstallHostBrowserDialog.java index 105895b..9be5c059 100644 --- a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/InstallHostBrowserDialog.java +++ b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/InstallHostBrowserDialog.java
@@ -39,7 +39,9 @@ int hostBrowserIconId) { View view = LayoutInflater.from(context).inflate(R.layout.host_browser_list_item, null); TextView name = (TextView) view.findViewById(R.id.browser_name); + WebApkUtils.setPadding(name, context, WebApkUtils.PADDING_DP, 0, 0, 0); ImageView icon = (ImageView) view.findViewById(R.id.browser_icon); + WebApkUtils.setPadding(icon, context, WebApkUtils.PADDING_DP, 0, 0, 0); name.setText(hostBrowserApplicationName); name.setTextColor(Color.BLACK);
diff --git a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/WebApkUtils.java b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/WebApkUtils.java index 8fb7235..630a7d0 100644 --- a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/WebApkUtils.java +++ b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/WebApkUtils.java
@@ -12,8 +12,11 @@ import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.net.Uri; +import android.os.Build; import android.os.Bundle; import android.text.TextUtils; +import android.util.TypedValue; +import android.view.View; import org.chromium.webapk.lib.common.WebApkConstants; import org.chromium.webapk.lib.common.WebApkMetaDataKeys; @@ -29,6 +32,7 @@ */ public class WebApkUtils { public static final String SHARED_PREF_RUNTIME_HOST = "runtime_host"; + public static final int PADDING_DP = 20; /** * The package names of the channels of Chrome that support WebAPKs. The most preferred one @@ -226,4 +230,27 @@ editor.putString(SHARED_PREF_RUNTIME_HOST, hostPackage); editor.apply(); } + + /** Converts a dp value to a px value. */ + public static int dpToPx(Context context, int value) { + return Math.round(TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics())); + } + + /** + * Android uses padding_left under API level 17 and uses padding_start after that. + * If we set the padding in resource file, android will create duplicated resource xml + * with the padding to be different. + */ + @SuppressWarnings("deprecation") + public static void setPadding( + View view, Context context, int start, int top, int end, int bottom) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + view.setPaddingRelative(dpToPx(context, start), dpToPx(context, top), + dpToPx(context, end), dpToPx(context, bottom)); + } else { + view.setPadding(dpToPx(context, start), dpToPx(context, top), dpToPx(context, end), + dpToPx(context, bottom)); + } + } }
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 51d0c55..bbe8ed387 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -2520,6 +2520,7 @@ "sessions/session_restore.h", "sessions/session_restore_delegate.cc", "sessions/session_restore_delegate.h", + "sessions/session_restore_observer.h", "sessions/session_restore_stats_collector.cc", "sessions/session_restore_stats_collector.h", "sessions/session_service.cc", @@ -2844,8 +2845,6 @@ "android/physical_web/physical_web_data_source_android.h", "android/policy/policy_auditor.cc", "android/policy/policy_auditor.h", - "android/precache/precache_launcher.cc", - "android/precache/precache_launcher.h", "android/preferences/autofill/autofill_profile_bridge.cc", "android/preferences/autofill/autofill_profile_bridge.h", "android/preferences/browser_prefs_android.cc", @@ -3056,10 +3055,6 @@ "platform_util_android.cc", "policy/cloud/user_policy_signin_service_mobile.cc", "policy/cloud/user_policy_signin_service_mobile.h", - "precache/precache_manager_factory.cc", - "precache/precache_manager_factory.h", - "precache/precache_util.cc", - "precache/precache_util.h", "prerender/external_prerender_handler_android.cc", "prerender/external_prerender_handler_android.h", "profiles/profile_android.cc", @@ -3091,8 +3086,6 @@ "//components/cdm/browser", "//components/data_usage/android", "//components/payments/content/android", - "//components/precache/content", - "//components/precache/core", "//components/resources:components_resources", "//components/toolbar", "//components/web_contents_delegate_android", @@ -4129,7 +4122,6 @@ "../android/java/src/org/chromium/chrome/browser/physicalweb/PhysicalWebBroadcastService.java", "../android/java/src/org/chromium/chrome/browser/physicalweb/UrlManager.java", "../android/java/src/org/chromium/chrome/browser/policy/PolicyAuditor.java", - "../android/java/src/org/chromium/chrome/browser/precache/PrecacheLauncher.java", "../android/java/src/org/chromium/chrome/browser/preferences/LocationSettings.java", "../android/java/src/org/chromium/chrome/browser/preferences/PrefServiceBridge.java", "../android/java/src/org/chromium/chrome/browser/preferences/PreferencesLauncher.java",
diff --git a/chrome/browser/android/chrome_jni_registrar.cc b/chrome/browser/android/chrome_jni_registrar.cc index f5718a0..8d2d390 100644 --- a/chrome/browser/android/chrome_jni_registrar.cc +++ b/chrome/browser/android/chrome_jni_registrar.cc
@@ -85,7 +85,6 @@ #include "chrome/browser/android/physical_web/eddystone_encoder_bridge.h" #include "chrome/browser/android/physical_web/physical_web_data_source_android.h" #include "chrome/browser/android/policy/policy_auditor.h" -#include "chrome/browser/android/precache/precache_launcher.h" #include "chrome/browser/android/preferences/autofill/autofill_profile_bridge.h" #include "chrome/browser/android/preferences/pref_service_bridge.h" #include "chrome/browser/android/preferences/website_preference_bridge.h" @@ -146,35 +145,6 @@ #include "chrome/browser/supervised_user/supervised_user_content_provider_android.h" #include "chrome/browser/sync/profile_sync_service_android.h" #include "chrome/browser/sync/sessions/sync_sessions_metrics_android.h" -#include "chrome/browser/ui/android/autofill/autofill_keyboard_accessory_view.h" -#include "chrome/browser/ui/android/autofill/autofill_popup_view_android.h" -#include "chrome/browser/ui/android/autofill/card_unmask_prompt_view_android.h" -#include "chrome/browser/ui/android/autofill/credit_card_scanner_view_android.h" -#include "chrome/browser/ui/android/autofill/password_generation_popup_view_android.h" -#include "chrome/browser/ui/android/bluetooth_chooser_android.h" -#include "chrome/browser/ui/android/chrome_http_auth_handler.h" -#include "chrome/browser/ui/android/context_menu_helper.h" -#include "chrome/browser/ui/android/infobars/app_banner_infobar_android.h" -#include "chrome/browser/ui/android/infobars/autofill_save_card_infobar.h" -#include "chrome/browser/ui/android/infobars/infobar_android.h" -#include "chrome/browser/ui/android/infobars/infobar_container_android.h" -#include "chrome/browser/ui/android/infobars/reader_mode_infobar.h" -#include "chrome/browser/ui/android/infobars/simple_confirm_infobar_builder.h" -#include "chrome/browser/ui/android/infobars/translate_compact_infobar.h" -#include "chrome/browser/ui/android/infobars/translate_infobar.h" -#include "chrome/browser/ui/android/javascript_app_modal_dialog_android.h" -#include "chrome/browser/ui/android/omnibox/omnibox_url_emphasizer.h" -#include "chrome/browser/ui/android/omnibox/omnibox_view_util.h" -#include "chrome/browser/ui/android/page_info/certificate_chain_helper.h" -#include "chrome/browser/ui/android/page_info/certificate_viewer_android.h" -#include "chrome/browser/ui/android/page_info/connection_info_popup_android.h" -#include "chrome/browser/ui/android/page_info/page_info_popup_android.h" -#include "chrome/browser/ui/android/snackbars/auto_signin_prompt_controller.h" -#include "chrome/browser/ui/android/ssl_client_certificate_request.h" -#include "chrome/browser/ui/android/tab_model/single_tab_model.h" -#include "chrome/browser/ui/android/tab_model/tab_model_jni_bridge.h" -#include "chrome/browser/ui/android/toolbar/toolbar_model_android.h" -#include "chrome/browser/ui/android/usb_chooser_dialog_android.h" #include "components/feature_engagement_tracker/public/android/feature_engagement_tracker_jni_registrar.h" #include "components/offline_pages/features/features.h" #include "components/safe_browsing_db/android/jni_registrar.h" @@ -208,44 +178,30 @@ banners::RegisterAppBannerInfoBarDelegateAndroid}, {"AppBannerManagerAndroid", banners::AppBannerManagerAndroid::Register}, {"AutocompleteControllerAndroid", RegisterAutocompleteControllerAndroid}, - {"AutofillSaveCardInfoBar", AutofillSaveCardInfoBar::Register}, - {"AutofillKeyboardAccessory", autofill::AutofillKeyboardAccessoryView:: - RegisterAutofillKeyboardAccessoryView}, - {"AutofillPopup", - autofill::AutofillPopupViewAndroid::RegisterAutofillPopupViewAndroid}, {"AutofillProfileBridge", autofill::RegisterAutofillProfileBridge}, {"BackgroundSchedulerBridge", offline_pages::android::RegisterBackgroundSchedulerBridge}, {"PrefetchBackgroundTask", offline_pages::RegisterPrefetchBackgroundTask}, - {"BluetoothChooserAndroid", BluetoothChooserAndroid::Register}, {"BookmarkBridge", BookmarkBridge::RegisterBookmarkBridge}, {"BrowsingDataBridge", RegisterBrowsingDataBridge}, {"BrowsingDataCounterBridge", BrowsingDataCounterBridge::Register}, {"BrowsingHistoryBridge", RegisterBrowsingHistoryBridge}, - {"CardUnmaskPrompt", autofill::CardUnmaskPromptViewAndroid::Register}, - {"CertificateViewer", RegisterCertificateViewer}, - {"CertificateChainHelper", RegisterCertificateChainHelper}, {"ChildAccountService", RegisterChildAccountService}, {"ChromeApplication", chrome::android::ChromeApplication::RegisterBindings}, {"ChromeBackupAgent", chrome::android::RegisterBackupAgent}, {"ChromeBrowserProvider", ChromeBrowserProvider::RegisterChromeBrowserProvider}, {"ChromeFeatureList", chrome::android::RegisterChromeFeatureListJni}, - {"ChromeHttpAuthHandler", - ChromeHttpAuthHandler::RegisterChromeHttpAuthHandler}, {"ChromeMediaRouter", media_router::MediaRouterAndroidBridge::Register}, {"ChromeMediaRouterDialogController", media_router::MediaRouterDialogControllerAndroid::Register}, {"ChromePayments", payments::android::RegisterChromePayments}, {"ChromeWebApkHost", ChromeWebApkHost::Register}, {"CompositorView", RegisterCompositorView}, - {"ConnectionInfoPopupAndroid", - ConnectionInfoPopupAndroid::RegisterConnectionInfoPopupAndroid}, {"SecurityStateModel", RegisterSecurityStateModelAndroid}, {"ConnectivityChecker", chrome::android::RegisterConnectivityChecker}, {"ContentSuggestionsNotificationHelper", ntp_snippets::ContentSuggestionsNotificationHelper::Register}, - {"ContextMenuHelper", RegisterContextMenuHelper}, {"ContextualSearchContext", RegisterContextualSearchContext}, {"ContextualSearchManager", RegisterContextualSearchManager}, {"ContextualSearchRankerLoggerImpl", @@ -253,8 +209,6 @@ {"ContextualSearchSceneLayer", RegisterContextualSearchSceneLayer}, {"ContextualSearchTabHelper", RegisterContextualSearchTabHelper}, {"CookiesFetcher", RegisterCookiesFetcher}, - {"CreditCardScannerBridge", - autofill::CreditCardScannerViewAndroid::Register}, {"CtrSuppression", RegisterCtrSuppression}, {"DataReductionPromoInfoBarDelegate", DataReductionPromoInfoBarDelegateAndroid::Register}, @@ -287,13 +241,10 @@ {"ForeignSessionHelper", ForeignSessionHelper::RegisterForeignSessionHelper}, {"HistoryReportJniBridge", history_report::RegisterHistoryReportJniBridge}, - {"InfoBarContainer", RegisterInfoBarContainer}, {"InstantAppsInfobarDelegate", RegisterInstantAppsInfoBarDelegate}, {"InstantAppsSettings", RegisterInstantAppsSettings}, {"InvalidationServiceFactory", invalidation::InvalidationServiceFactoryAndroid::Register}, - {"JavascriptAppModalDialog", - JavascriptAppModalDialogAndroid::RegisterJavascriptAppModalDialog}, {"LargeIconBridge", LargeIconBridge::RegisterLargeIconBridge}, {"LaunchMetrics", metrics::RegisterLaunchMetrics}, {"LayerTitleCache", RegisterLayerTitleCache}, @@ -304,7 +255,6 @@ {"MediaDrmCredentialManager", MediaDrmCredentialManager::RegisterMediaDrmCredentialManager}, {"MostVisitedSitesBridge", MostVisitedSitesBridge::Register}, - {"NativeInfoBar", RegisterNativeInfoBar}, {"ExternalEstimateProviderAndroid", chrome::android::RegisterExternalEstimateProviderAndroid}, {"RecentTabsPagePrefs", RecentTabsPagePrefs::RegisterJni}, @@ -321,15 +271,10 @@ offline_pages::android::OfflinePageEvaluationBridge::Register}, #endif {"OmniboxPrerender", RegisterOmniboxPrerender}, - {"OmniboxUrlEmphasizer", - OmniboxUrlEmphasizer::RegisterOmniboxUrlEmphasizer}, - {"OmniboxViewUtil", OmniboxViewUtil::RegisterOmniboxViewUtil}, {"OriginVerifier", customtabs::RegisterOriginVerifier}, {"OverlayPanelContent", RegisterOverlayPanelContent}, {"PartnerBookmarksReader", PartnerBookmarksReader::RegisterPartnerBookmarksReader}, - {"PasswordGenerationPopup", - autofill::PasswordGenerationPopupViewAndroid::Register}, {"PasswordUIViewAndroid", PasswordUIViewAndroid::RegisterPasswordUIViewAndroid}, {"PermissionDialogDelegate", @@ -342,7 +287,6 @@ {"PhysicalWebDataSourceAndroid", PhysicalWebDataSourceAndroid::RegisterPhysicalWebDataSource}, {"PolicyAuditor", RegisterPolicyAuditor}, - {"PrecacheLauncher", RegisterPrecacheLauncher}, {"PrefServiceBridge", PrefServiceBridge::RegisterPrefServiceBridge}, {"ProfileAndroid", ProfileAndroid::RegisterProfileAndroid}, {"ProfileDownloader", RegisterProfileDownloader}, @@ -350,7 +294,6 @@ {"RapporServiceBridge", rappor::RegisterRapporServiceBridge}, {"RecentlyClosedBridge", RecentlyClosedTabsBridge::Register}, {"RecordCastAction", remote_media::RegisterRecordCastAction}, - {"ReaderModeInfoBar", RegisterReaderModeInfoBar}, {"RemoteMediaPlayerBridge", remote_media::RemoteMediaPlayerBridge::RegisterRemoteMediaPlayerBridge}, {"ResourceFactory", RegisterResourceFactory}, @@ -367,16 +310,12 @@ {"ShortcutHelper", ShortcutHelper::RegisterShortcutHelper}, {"SigninInvestigator", SigninInvestigatorAndroid::Register}, {"SigninManager", SigninManagerAndroid::Register}, - {"SimpleConfirmInfoBarBuilder", RegisterSimpleConfirmInfoBarBuilder}, - {"SingleTabModel", RegisterSingleTabModel}, {"SiteEngagementService", SiteEngagementServiceAndroid::Register}, {"SpecialLocaleHandler", RegisterSpecialLocaleHandler}, #if BUILDFLAG(ENABLE_SPELLCHECK) {"SpellCheckerSessionBridge", spellcheck::android::RegisterSpellcheckJni}, #endif {"SqliteCursor", SQLiteCursor::RegisterSqliteCursor}, - {"SSLClientCertificateRequest", - chrome::android::RegisterSSLClientCertificateRequestAndroid}, {"StartupMetricUtils", chrome::android::RegisterStartupMetricUtils}, {"StaticTabSceneLayer", RegisterStaticTabSceneLayer}, {"SuggestionsEventReporterBridge", RegisterSuggestionsEventReporterBridge}, @@ -386,21 +325,16 @@ {"TabAndroid", TabAndroid::RegisterTabAndroid}, {"TabContentManager", RegisterTabContentManager}, {"TabListSceneLayer", RegisterTabListSceneLayer}, - {"TabModelJniBridge", TabModelJniBridge::Register}, {"TabState", RegisterTabState}, {"TabStripSceneLayer", RegisterTabStripSceneLayer}, {"TabWebContentsDelegateAndroid", RegisterTabWebContentsDelegateAndroid}, {"TemplateUrlServiceAndroid", TemplateUrlServiceAndroid::Register}, {"ThumbnailProvider", ThumbnailProvider::RegisterThumbnailProvider}, - {"ToolbarModelAndroid", ToolbarModelAndroid::RegisterToolbarModelAndroid}, {"ToolbarSceneLayer", RegisterToolbarSceneLayer}, - {"TranslateCompactInfoBar", RegisterTranslateCompactInfoBar}, - {"TranslateInfoBarDelegate", RegisterTranslateInfoBarDelegate}, {"TtsPlatformImpl", TtsPlatformImplAndroid::Register}, {"UmaSessionStats", RegisterUmaSessionStats}, {"UrlFilterBridge", UrlFilterBridge::Register}, {"UrlUtilities", RegisterUrlUtilities}, - {"UsbChooserDialogAndroid", UsbChooserDialogAndroid::Register}, {"Variations", variations::android::RegisterVariations}, {"VariationsSession", chrome::android::RegisterVariationsSession}, {"WarmupManager", RegisterWarmupManager}, @@ -409,8 +343,6 @@ {"WebApkUpdateDataFetcher", WebApkUpdateDataFetcher::Register}, {"WebContentsFactory", RegisterWebContentsFactory}, {"WebsitePreferenceBridge", RegisterWebsitePreferenceBridge}, - {"PageInfoPopupAndroid", - PageInfoPopupAndroid::RegisterPageInfoPopupAndroid}, #if BUILDFLAG(ENABLE_PRINTING) && !BUILDFLAG(ENABLE_PRINT_PREVIEW) {"PrintingContext", printing::PrintingContextAndroid::RegisterPrintingContext},
diff --git a/chrome/browser/android/precache/precache_launcher.cc b/chrome/browser/android/precache/precache_launcher.cc deleted file mode 100644 index 681d385..0000000 --- a/chrome/browser/android/precache/precache_launcher.cc +++ /dev/null
@@ -1,98 +0,0 @@ -// 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. - -#include "chrome/browser/android/precache/precache_launcher.h" - -#include <jni.h> - -#include "base/android/jni_android.h" -#include "base/android/jni_weak_ref.h" -#include "base/bind.h" -#include "base/logging.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/precache/precache_manager_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/profiles/profile_manager.h" -#include "components/precache/content/precache_manager.h" -#include "components/prefs/pref_service.h" -#include "jni/PrecacheLauncher_jni.h" - -using base::android::AttachCurrentThread; -using base::android::JavaParamRef; -using precache::PrecacheManager; - -namespace { - -// Get the profile that should be used for precaching. -Profile* GetProfile() { - Profile* profile = g_browser_process->profile_manager()->GetLastUsedProfile() - ->GetOriginalProfile(); - DCHECK(profile); - DCHECK(g_browser_process->profile_manager()->IsValidProfile(profile)); - return profile; -} - -// Get the PrecacheManager for the given |profile|. -PrecacheManager* GetPrecacheManager(Profile* profile) { - PrecacheManager* precache_manager = - precache::PrecacheManagerFactory::GetForBrowserContext(profile); - DCHECK(precache_manager); - return precache_manager; -} - -} // namespace - -PrecacheLauncher::PrecacheLauncher(JNIEnv* env, jobject obj) - : weak_java_precache_launcher_(env, obj), weak_factory_(this) {} - -PrecacheLauncher::~PrecacheLauncher() {} - -void PrecacheLauncher::Destroy(JNIEnv* env, const JavaParamRef<jobject>& obj) { - delete this; -} - -void PrecacheLauncher::Start(JNIEnv* env, const JavaParamRef<jobject>& obj) { - // TODO(bengr): Add integration tests for the whole feature. - Profile* profile = GetProfile(); - - PrecacheManager* precache_manager = GetPrecacheManager(profile); - - if (precache_manager == nullptr) { - OnPrecacheCompleted(false); - return; - } - - precache_manager->StartPrecaching(base::Bind( - &PrecacheLauncher::OnPrecacheCompleted, weak_factory_.GetWeakPtr())); -} - -void PrecacheLauncher::Cancel(JNIEnv* env, const JavaParamRef<jobject>& obj) { - Profile* profile = GetProfile(); - PrecacheManager* precache_manager = GetPrecacheManager(profile); - - precache_manager->CancelPrecaching(); -} - -void PrecacheLauncher::OnPrecacheCompleted(bool try_again_soon) { - JNIEnv* env = AttachCurrentThread(); - Java_PrecacheLauncher_onPrecacheCompletedCallback( - env, weak_java_precache_launcher_.get(env), - try_again_soon ? JNI_TRUE : JNI_FALSE); -} - -static jlong Init(JNIEnv* env, const JavaParamRef<jobject>& obj) { - return reinterpret_cast<intptr_t>(new PrecacheLauncher(env, obj)); -} - -// Must be run on the UI thread. -static jboolean ShouldRun(JNIEnv* env, const JavaParamRef<jobject>& obj) { - Profile* profile = GetProfile(); - PrecacheManager* precache_manager = GetPrecacheManager(profile); - return precache_manager && (precache_manager->IsInExperimentGroup() || - precache_manager->IsInControlGroup()); -} - -bool RegisterPrecacheLauncher(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/android/precache/precache_launcher.h b/chrome/browser/android/precache/precache_launcher.h deleted file mode 100644 index 8c73c4d..0000000 --- a/chrome/browser/android/precache/precache_launcher.h +++ /dev/null
@@ -1,40 +0,0 @@ -// 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. - -#ifndef CHROME_BROWSER_ANDROID_PRECACHE_PRECACHE_LAUNCHER_H_ -#define CHROME_BROWSER_ANDROID_PRECACHE_PRECACHE_LAUNCHER_H_ - -#include <jni.h> - -#include "base/android/jni_android.h" -#include "base/android/jni_weak_ref.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" - -class PrecacheLauncher { - public: - PrecacheLauncher(JNIEnv* env, jobject obj); - void Destroy(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); - void Start(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); - void Cancel(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); - - private: - ~PrecacheLauncher(); - // Called when precaching completes. |try_again_soon| is true iff the precache - // failed to start due to a transient error and should be attempted again - // soon. - void OnPrecacheCompleted(bool try_again_soon); - - JavaObjectWeakGlobalRef weak_java_precache_launcher_; - - // This must be the last member field in the class. - base::WeakPtrFactory<PrecacheLauncher> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(PrecacheLauncher); -}; - -// Registers the native methods to be called from Java. -bool RegisterPrecacheLauncher(JNIEnv* env); - -#endif // CHROME_BROWSER_ANDROID_PRECACHE_PRECACHE_LAUNCHER_H_
diff --git a/chrome/browser/chromeos/arc/arc_service_launcher.cc b/chrome/browser/chromeos/arc/arc_service_launcher.cc index 79325b6..c0c2e30 100644 --- a/chrome/browser/chromeos/arc/arc_service_launcher.cc +++ b/chrome/browser/chromeos/arc/arc_service_launcher.cc
@@ -95,14 +95,10 @@ // List in lexicographical order. arc_service_manager_->AddService( - base::MakeUnique<ArcDownloadsWatcherService>(arc_bridge_service)); - arc_service_manager_->AddService( base::MakeUnique<ArcImeService>(arc_bridge_service)); arc_service_manager_->AddService( base::MakeUnique<ArcIntentHelperBridge>(arc_bridge_service)); arc_service_manager_->AddService( - base::MakeUnique<ArcNetHostImpl>(arc_bridge_service)); - arc_service_manager_->AddService( base::MakeUnique<ArcPolicyBridge>(arc_bridge_service)); arc_service_manager_->AddService( base::MakeUnique<ArcProcessService>(arc_bridge_service)); @@ -111,8 +107,6 @@ arc_service_manager_->AddService( base::MakeUnique<ArcStorageManager>(arc_bridge_service)); arc_service_manager_->AddService( - base::MakeUnique<ArcTracingBridge>(arc_bridge_service)); - arc_service_manager_->AddService( base::MakeUnique<ArcTtsService>(arc_bridge_service)); arc_service_manager_->AddService( base::MakeUnique<ArcUserSessionService>(arc_bridge_service)); @@ -183,13 +177,16 @@ ArcBootErrorNotification::GetForBrowserContext(profile); ArcClipboardBridge::GetForBrowserContext(profile); ArcCrashCollectorBridge::GetForBrowserContext(profile); + ArcDownloadsWatcherService::GetForBrowserContext(profile); ArcEnterpriseReportingService::GetForBrowserContext(profile); ArcFileSystemMounter::GetForBrowserContext(profile); ArcMetricsService::GetForBrowserContext(profile); + ArcNetHostImpl::GetForBrowserContext(profile); ArcObbMounterBridge::GetForBrowserContext(profile); ArcPowerBridge::GetForBrowserContext(profile); ArcPrintService::GetForBrowserContext(profile); ArcProvisionNotificationService::GetForBrowserContext(profile); + ArcTracingBridge::GetForBrowserContext(profile); arc_service_manager_->AddService(base::MakeUnique<ArcBootPhaseMonitorBridge>( arc_service_manager_->arc_bridge_service(),
diff --git a/chrome/browser/chromeos/arc/downloads_watcher/arc_downloads_watcher_service.cc b/chrome/browser/chromeos/arc/downloads_watcher/arc_downloads_watcher_service.cc index f591fb6..e191651 100644 --- a/chrome/browser/chromeos/arc/downloads_watcher/arc_downloads_watcher_service.cc +++ b/chrome/browser/chromeos/arc/downloads_watcher/arc_downloads_watcher_service.cc
@@ -17,6 +17,7 @@ #include "base/files/file_path.h" #include "base/files/file_path_watcher.h" #include "base/memory/ptr_util.h" +#include "base/memory/singleton.h" #include "base/sequence_checker.h" #include "base/strings/string_util.h" #include "base/task_scheduler/post_task.h" @@ -24,9 +25,10 @@ #include "base/threading/sequenced_task_runner_handle.h" #include "base/time/time.h" #include "chrome/browser/download/download_prefs.h" -#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_paths.h" #include "components/arc/arc_bridge_service.h" +#include "components/arc/arc_browser_context_keyed_service_factory_base.h" #include "content/public/browser/browser_thread.h" using content::BrowserThread; @@ -167,6 +169,25 @@ return std::make_pair(snapshot_time, std::move(current_timestamp_map)); } +// Singleton factory for ArcDownloadsWatcherService. +class ArcDownloadsWatcherServiceFactory + : public internal::ArcBrowserContextKeyedServiceFactoryBase< + ArcDownloadsWatcherService, + ArcDownloadsWatcherServiceFactory> { + public: + // Factory name used by ArcBrowserContextKeyedServiceFactoryBase. + static constexpr const char* kName = "ArcDownloadsWatcherServiceFactory"; + + static ArcDownloadsWatcherServiceFactory* GetInstance() { + return base::Singleton<ArcDownloadsWatcherServiceFactory>::get(); + } + + private: + friend base::DefaultSingletonTraits<ArcDownloadsWatcherServiceFactory>; + ArcDownloadsWatcherServiceFactory() = default; + ~ArcDownloadsWatcherServiceFactory() override = default; +}; + } // namespace bool HasAndroidSupportedMediaExtension(const base::FilePath& path) { @@ -190,7 +211,7 @@ public: using Callback = base::Callback<void(const std::vector<std::string>& paths)>; - explicit DownloadsWatcher(const Callback& callback); + DownloadsWatcher(content::BrowserContext* context, const Callback& callback); ~DownloadsWatcher(); // Starts watching Downloads directory. @@ -230,6 +251,7 @@ }; ArcDownloadsWatcherService::DownloadsWatcher::DownloadsWatcher( + content::BrowserContext* context, const Callback& callback) : callback_(callback), last_notify_time_(base::TimeTicks()), @@ -238,7 +260,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); DETACH_FROM_SEQUENCE(sequence_checker_); - downloads_dir_ = DownloadPrefs(ProfileManager::GetActiveUserProfile()) + downloads_dir_ = DownloadPrefs(Profile::FromBrowserContext(context)) .GetDefaultDownloadDirectoryForProfile() .StripTrailingSeparators(); } @@ -314,21 +336,36 @@ outstanding_task_ = false; } +// static +ArcDownloadsWatcherService* ArcDownloadsWatcherService::GetForBrowserContext( + content::BrowserContext* context) { + return ArcDownloadsWatcherServiceFactory::GetForBrowserContext(context); +} + ArcDownloadsWatcherService::ArcDownloadsWatcherService( + content::BrowserContext* context, ArcBridgeService* bridge_service) - : ArcService(bridge_service), + : context_(context), + arc_bridge_service_(bridge_service), file_task_runner_( base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})), weak_ptr_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - arc_bridge_service()->file_system()->AddObserver(this); + arc_bridge_service_->file_system()->AddObserver(this); } ArcDownloadsWatcherService::~ArcDownloadsWatcherService() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - arc_bridge_service()->file_system()->RemoveObserver(this); + StopWatchingDownloads(); DCHECK(!watcher_); + + // TODO(hidehiko): Currently, the lifetime of ArcBridgeService and + // BrowserContextKeyedService is not nested. + // If ArcServiceManager::Get() returns nullptr, it is already destructed, + // so do not touch it. + if (ArcServiceManager::Get()) + arc_bridge_service_->file_system()->RemoveObserver(this); } void ArcDownloadsWatcherService::OnInstanceReady() { @@ -346,8 +383,8 @@ StopWatchingDownloads(); DCHECK(!watcher_); watcher_ = base::MakeUnique<DownloadsWatcher>( - base::Bind(&ArcDownloadsWatcherService::OnDownloadsChanged, - weak_ptr_factory_.GetWeakPtr())); + context_, base::Bind(&ArcDownloadsWatcherService::OnDownloadsChanged, + weak_ptr_factory_.GetWeakPtr())); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&DownloadsWatcher::Start, base::Unretained(watcher_.get()))); @@ -364,7 +401,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); auto* instance = ARC_GET_INSTANCE_FOR_METHOD( - arc_bridge_service()->file_system(), RequestMediaScan); + arc_bridge_service_->file_system(), RequestMediaScan); if (!instance) return; instance->RequestMediaScan(paths);
diff --git a/chrome/browser/chromeos/arc/downloads_watcher/arc_downloads_watcher_service.h b/chrome/browser/chromeos/arc/downloads_watcher/arc_downloads_watcher_service.h index dabadc3..b0592fab 100644 --- a/chrome/browser/chromeos/arc/downloads_watcher/arc_downloads_watcher_service.h +++ b/chrome/browser/chromeos/arc/downloads_watcher/arc_downloads_watcher_service.h
@@ -12,15 +12,19 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" -#include "components/arc/arc_service.h" #include "components/arc/common/file_system.mojom.h" #include "components/arc/instance_holder.h" +#include "components/keyed_service/core/keyed_service.h" namespace base { class FilePath; class SequencedTaskRunner; } // namespace base +namespace content { +class BrowserContext; +} // namespace content + namespace arc { class ArcBridgeService; @@ -31,10 +35,16 @@ // Watches Downloads directory and registers newly created media files to // Android MediaProvider. class ArcDownloadsWatcherService - : public ArcService, + : public KeyedService, public InstanceHolder<mojom::FileSystemInstance>::Observer { public: - explicit ArcDownloadsWatcherService(ArcBridgeService* bridge_service); + // Returns singleton instance for the given BrowserContext, + // or nullptr if the browser |context| is not allowed to use ARC. + static ArcDownloadsWatcherService* GetForBrowserContext( + content::BrowserContext* context); + + ArcDownloadsWatcherService(content::BrowserContext* context, + ArcBridgeService* bridge_service); ~ArcDownloadsWatcherService() override; // InstanceHolder<mojom::FileSystemInstance>::Observer @@ -49,6 +59,9 @@ void OnDownloadsChanged(const std::vector<std::string>& paths); + content::BrowserContext* const context_; + ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager. + std::unique_ptr<DownloadsWatcher> watcher_; scoped_refptr<base::SequencedTaskRunner> file_task_runner_;
diff --git a/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc b/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc index be3ede1..deeb0c6 100644 --- a/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc +++ b/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc
@@ -6,8 +6,10 @@ #include "base/bind.h" #include "base/logging.h" +#include "base/memory/singleton.h" #include "base/threading/thread_task_runner_handle.h" #include "components/arc/arc_bridge_service.h" +#include "components/arc/arc_browser_context_keyed_service_factory_base.h" #include "components/arc/arc_service_manager.h" #include "content/public/browser/browser_thread.h" #include "mojo/public/cpp/system/platform_handle.h" @@ -21,6 +23,25 @@ // the prefix and the real categories. constexpr char kCategoryPrefix[] = TRACE_DISABLED_BY_DEFAULT("android "); +// Singleton factory for ArcTracingBridge. +class ArcTracingBridgeFactory + : public internal::ArcBrowserContextKeyedServiceFactoryBase< + ArcTracingBridge, + ArcTracingBridgeFactory> { + public: + // Factory name used by ArcBrowserContextKeyedServiceFactoryBase. + static constexpr const char* kName = "ArcTracingBridgeFactory"; + + static ArcTracingBridgeFactory* GetInstance() { + return base::Singleton<ArcTracingBridgeFactory>::get(); + } + + private: + friend base::DefaultSingletonTraits<ArcTracingBridgeFactory>; + ArcTracingBridgeFactory() = default; + ~ArcTracingBridgeFactory() override = default; +}; + } // namespace struct ArcTracingBridge::Category { @@ -30,21 +51,34 @@ std::string full_name; }; -ArcTracingBridge::ArcTracingBridge(ArcBridgeService* bridge_service) - : ArcService(bridge_service), weak_ptr_factory_(this) { - arc_bridge_service()->tracing()->AddObserver(this); +// static +ArcTracingBridge* ArcTracingBridge::GetForBrowserContext( + content::BrowserContext* context) { + return ArcTracingBridgeFactory::GetForBrowserContext(context); +} + +ArcTracingBridge::ArcTracingBridge(content::BrowserContext* context, + ArcBridgeService* bridge_service) + : arc_bridge_service_(bridge_service), weak_ptr_factory_(this) { + arc_bridge_service_->tracing()->AddObserver(this); content::ArcTracingAgent::GetInstance()->SetDelegate(this); } ArcTracingBridge::~ArcTracingBridge() { content::ArcTracingAgent::GetInstance()->SetDelegate(nullptr); - arc_bridge_service()->tracing()->RemoveObserver(this); + + // TODO(hidehiko): Currently, the lifetime of ArcBridgeService and + // BrowserContextKeyedService is not nested. + // If ArcServiceManager::Get() returns nullptr, it is already destructed, + // so do not touch it. + if (ArcServiceManager::Get()) + arc_bridge_service_->tracing()->RemoveObserver(this); } void ArcTracingBridge::OnInstanceReady() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); mojom::TracingInstance* tracing_instance = ARC_GET_INSTANCE_FOR_METHOD( - arc_bridge_service()->tracing(), QueryAvailableCategories); + arc_bridge_service_->tracing(), QueryAvailableCategories); if (!tracing_instance) return; tracing_instance->QueryAvailableCategories(base::Bind( @@ -73,8 +107,8 @@ const StartTracingCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - mojom::TracingInstance* tracing_instance = ARC_GET_INSTANCE_FOR_METHOD( - arc_bridge_service()->tracing(), StartTracing); + mojom::TracingInstance* tracing_instance = + ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->tracing(), StartTracing); if (!tracing_instance) { // Use PostTask as the convention of TracingAgent. The caller expects // callback to be called after this function returns. @@ -98,7 +132,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); mojom::TracingInstance* tracing_instance = - ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service()->tracing(), StopTracing); + ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->tracing(), StopTracing); if (!tracing_instance) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, false));
diff --git a/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.h b/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.h index 0c301c37..3025311 100644 --- a/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.h +++ b/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.h
@@ -12,22 +12,32 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/trace_event/trace_event.h" -#include "components/arc/arc_service.h" #include "components/arc/common/tracing.mojom.h" #include "components/arc/instance_holder.h" +#include "components/keyed_service/core/keyed_service.h" #include "content/public/browser/arc_tracing_agent.h" +namespace content { +class BrowserContext; +} // namespace content + namespace arc { class ArcBridgeService; // This class provides the interface to trigger tracing in the container. class ArcTracingBridge - : public ArcService, + : public KeyedService, public content::ArcTracingAgent::Delegate, public InstanceHolder<mojom::TracingInstance>::Observer { public: - explicit ArcTracingBridge(ArcBridgeService* bridge_service); + // Returns singleton instance for the given BrowserContext, + // or nullptr if the browser |context| is not allowed to use ARC. + static ArcTracingBridge* GetForBrowserContext( + content::BrowserContext* context); + + ArcTracingBridge(content::BrowserContext* context, + ArcBridgeService* bridge_service); ~ArcTracingBridge() override; // InstanceHolder<mojom::TracingInstance>::Observer overrides: @@ -45,6 +55,8 @@ // Callback for QueryAvailableCategories. void OnCategoriesReady(const std::vector<std::string>& categories); + ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager. + // List of available categories. std::vector<Category> categories_;
diff --git a/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.cc b/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.cc index 7e19591..047e2ee 100644 --- a/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.cc +++ b/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.cc
@@ -9,6 +9,7 @@ #include "base/files/file_util.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" +#include "base/task_scheduler/post_task.h" #include "base/time/time.h" #include "chrome/browser/media/webrtc/webrtc_rtp_dump_writer.h" #include "content/public/browser/browser_thread.h" @@ -52,11 +53,10 @@ incoming_state_(STATE_NONE), outgoing_state_(STATE_NONE), weak_ptr_factory_(this) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); } WebRtcRtpDumpHandler::~WebRtcRtpDumpHandler() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_); // Reset dump writer first to stop writing. if (dump_writer_) { @@ -65,15 +65,15 @@ } if (incoming_state_ != STATE_NONE && !incoming_dump_path_.empty()) { - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, + base::PostTaskWithTraits( + FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), incoming_dump_path_, false)); } if (outgoing_state_ != STATE_NONE && !outgoing_dump_path_.empty()) { - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, + base::PostTaskWithTraits( + FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), outgoing_dump_path_, false)); } @@ -81,7 +81,7 @@ bool WebRtcRtpDumpHandler::StartDump(RtpDumpType type, std::string* error_message) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_); if (!dump_writer_ && g_ongoing_rtp_dumps >= kMaxOngoingRtpDumpsAllowed) { *error_message = "Max RTP dump limit reached."; @@ -139,7 +139,7 @@ void WebRtcRtpDumpHandler::StopDump(RtpDumpType type, const GenericDoneCallback& callback) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_); // Returns an error if any type of dump specified by the caller cannot be // stopped. @@ -177,7 +177,7 @@ } bool WebRtcRtpDumpHandler::ReadyToRelease() const { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_); return incoming_state_ != STATE_STARTED && incoming_state_ != STATE_STOPPING && @@ -185,7 +185,7 @@ } WebRtcRtpDumpHandler::ReleasedDumps WebRtcRtpDumpHandler::ReleaseDumps() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_); DCHECK(ReadyToRelease()); base::FilePath incoming_dump, outgoing_dump; @@ -210,7 +210,7 @@ size_t header_length, size_t packet_length, bool incoming) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_); if ((incoming && incoming_state_ != STATE_STARTED) || (!incoming && outgoing_state_ != STATE_STARTED)) { @@ -222,7 +222,7 @@ } void WebRtcRtpDumpHandler::StopOngoingDumps(const base::Closure& callback) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_); DCHECK(!callback.is_null()); // No ongoing dumps, return directly. @@ -232,11 +232,11 @@ return; } - // If the FILE thread is working on stopping the dumps, wait for the FILE - // thread to return and check the states again. + // If the background task runner is working on stopping the dumps, wait for it + // to complete and then check the states again. if (incoming_state_ == STATE_STOPPING || outgoing_state_ == STATE_STOPPING) { - BrowserThread::PostTaskAndReply( - BrowserThread::FILE, FROM_HERE, base::BindOnce(&base::DoNothing), + dump_writer_->background_task_runner()->PostTaskAndReply( + FROM_HERE, base::BindOnce(&base::DoNothing), base::BindOnce(&WebRtcRtpDumpHandler::StopOngoingDumps, weak_ptr_factory_.GetWeakPtr(), callback)); return; @@ -266,7 +266,7 @@ void WebRtcRtpDumpHandler::SetDumpWriterForTesting( std::unique_ptr<WebRtcRtpDumpWriter> writer) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_); dump_writer_ = std::move(writer); ++g_ongoing_rtp_dumps; @@ -276,7 +276,7 @@ } void WebRtcRtpDumpHandler::OnMaxDumpSizeReached() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_); RtpDumpType type = (incoming_state_ == STATE_STARTED) @@ -290,15 +290,15 @@ RtpDumpType ended_type, bool incoming_success, bool outgoing_success) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_); if (DumpTypeContainsIncoming(ended_type)) { DCHECK_EQ(STATE_STOPPING, incoming_state_); incoming_state_ = STATE_STOPPED; if (!incoming_success) { - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, + base::PostTaskWithTraits( + FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), incoming_dump_path_, false)); @@ -313,8 +313,8 @@ outgoing_state_ = STATE_STOPPED; if (!outgoing_success) { - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, + base::PostTaskWithTraits( + FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), outgoing_dump_path_, false));
diff --git a/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.h b/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.h index 6480b8d..da67198 100644 --- a/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.h +++ b/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.h
@@ -14,6 +14,7 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "base/sequence_checker.h" #include "chrome/browser/media/webrtc/rtp_dump_type.h" class WebRtcRtpDumpWriter; @@ -114,6 +115,8 @@ bool incoming_succeeded, bool outgoing_succeeded); + SEQUENCE_CHECKER(main_sequence_); + // The absolute path to the directory containing the incoming/outgoing dumps. const base::FilePath dump_dir_;
diff --git a/chrome/browser/media/webrtc/webrtc_rtp_dump_handler_unittest.cc b/chrome/browser/media/webrtc/webrtc_rtp_dump_handler_unittest.cc index bf3ebe5..092cb88 100644 --- a/chrome/browser/media/webrtc/webrtc_rtp_dump_handler_unittest.cc +++ b/chrome/browser/media/webrtc/webrtc_rtp_dump_handler_unittest.cc
@@ -16,7 +16,9 @@ #include "base/location.h" #include "base/macros.h" #include "base/run_loop.h" +#include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" +#include "base/task_scheduler/task_scheduler.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/media/webrtc/webrtc_rtp_dump_writer.h" #include "content/public/test/test_browser_thread_bundle.h" @@ -99,6 +101,11 @@ EXPECT_GT(base::WriteFile(*outgoing_dump, dummy, arraysize(dummy)), 0); } + void FlushTaskRunners() { + base::TaskScheduler::GetInstance()->FlushForTesting(); + base::RunLoop().RunUntilIdle(); + } + MOCK_METHOD2(OnStopDumpFinished, void(bool success, const std::string& error)); @@ -283,9 +290,10 @@ base::Bind(&WebRtcRtpDumpHandlerTest::OnStopDumpFinished, base::Unretained(this))); base::RunLoop().RunUntilIdle(); + FlushTaskRunners(); handler_.reset(); - base::RunLoop().RunUntilIdle(); + FlushTaskRunners(); EXPECT_FALSE(base::PathExists(incoming_dump)); EXPECT_FALSE(base::PathExists(outgoing_dump)); @@ -309,6 +317,7 @@ base::Bind(&WebRtcRtpDumpHandlerTest::OnStopDumpFinished, base::Unretained(this))); base::RunLoop().RunUntilIdle(); + FlushTaskRunners(); EXPECT_FALSE(base::PathExists(incoming_dump)); EXPECT_TRUE(base::PathExists(outgoing_dump)); @@ -317,6 +326,7 @@ base::Bind(&WebRtcRtpDumpHandlerTest::OnStopDumpFinished, base::Unretained(this))); base::RunLoop().RunUntilIdle(); + FlushTaskRunners(); EXPECT_FALSE(base::PathExists(outgoing_dump)); } @@ -331,12 +341,13 @@ handler_->StopDump(RTP_DUMP_BOTH, base::Bind(&WebRtcRtpDumpHandlerTest::OnStopDumpFinished, base::Unretained(this))); + base::RunLoop().RunUntilIdle(); handler_->StopOngoingDumps( base::Bind(&WebRtcRtpDumpHandlerTest::OnStopOngoingDumpsFinished, base::Unretained(this))); - base::RunLoop().RunUntilIdle(); + FlushTaskRunners(); WebRtcRtpDumpHandler::ReleasedDumps dumps(handler_->ReleaseDumps()); EXPECT_FALSE(dumps.incoming_dump_path.empty()); @@ -353,7 +364,7 @@ base::Bind(&WebRtcRtpDumpHandlerTest::OnStopOngoingDumpsFinished, base::Unretained(this))); - base::RunLoop().RunUntilIdle(); + FlushTaskRunners(); WebRtcRtpDumpHandler::ReleasedDumps dumps(handler_->ReleaseDumps()); EXPECT_FALSE(dumps.incoming_dump_path.empty()); @@ -371,6 +382,7 @@ base::Bind(&WebRtcRtpDumpHandlerTest::OnStopDumpFinished, base::Unretained(this))); base::RunLoop().RunUntilIdle(); + FlushTaskRunners(); } EXPECT_CALL(*this, OnStopOngoingDumpsFinished()); @@ -390,12 +402,13 @@ handler_->StopDump(RTP_DUMP_INCOMING, base::Bind(&WebRtcRtpDumpHandlerTest::OnStopDumpFinished, base::Unretained(this))); + base::RunLoop().RunUntilIdle(); handler_->StopOngoingDumps( base::Bind(&WebRtcRtpDumpHandlerTest::OnStopOngoingDumpsFinished, base::Unretained(this))); - base::RunLoop().RunUntilIdle(); + FlushTaskRunners(); WebRtcRtpDumpHandler::ReleasedDumps dumps(handler_->ReleaseDumps()); EXPECT_FALSE(dumps.incoming_dump_path.empty());
diff --git a/chrome/browser/media/webrtc/webrtc_rtp_dump_writer.cc b/chrome/browser/media/webrtc/webrtc_rtp_dump_writer.cc index f64ef25..61b7b971 100644 --- a/chrome/browser/media/webrtc/webrtc_rtp_dump_writer.cc +++ b/chrome/browser/media/webrtc/webrtc_rtp_dump_writer.cc
@@ -10,6 +10,7 @@ #include "base/files/file_util.h" #include "base/logging.h" #include "base/macros.h" +#include "base/task_scheduler/post_task.h" #include "content/public/browser/browser_thread.h" #include "third_party/zlib/zlib.h" @@ -90,13 +91,12 @@ } // namespace -// This class is running on the FILE thread for compressing and writing the +// This class runs on the backround task runner, compresses and writes the // dump buffer to disk. -class WebRtcRtpDumpWriter::FileThreadWorker { +class WebRtcRtpDumpWriter::FileWorker { public: - explicit FileThreadWorker(const base::FilePath& dump_path) - : dump_path_(dump_path) { - thread_checker_.DetachFromThread(); + explicit FileWorker(const base::FilePath& dump_path) : dump_path_(dump_path) { + DETACH_FROM_SEQUENCE(sequence_checker_); memset(&stream_, 0, sizeof(stream_)); int result = deflateInit2(&stream_, @@ -110,8 +110,8 @@ DCHECK_EQ(Z_OK, result); } - ~FileThreadWorker() { - DCHECK(thread_checker_.CalledOnValidThread()); + ~FileWorker() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Makes sure all allocations are freed. deflateEnd(&stream_); @@ -125,7 +125,7 @@ bool end_stream, FlushResult* result, size_t* bytes_written) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // This is called either when the in-memory buffer is full or the dump // should be ended. @@ -153,7 +153,7 @@ // dump. size_t CompressAndWriteBufferToFile(std::vector<uint8_t>* buffer, FlushResult* result) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(buffer->size()); *result = FLUSH_RESULT_SUCCESS; @@ -193,7 +193,7 @@ // Compresses |input| into |output|. bool Compress(std::vector<uint8_t>* input, std::vector<uint8_t>* output) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); int result = Z_OK; output->resize(std::max(kMinimumGzipOutputBufferSize, input->size())); @@ -217,7 +217,7 @@ // Ends the compression stream and completes the dump file. bool EndDumpFile() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); std::vector<uint8_t> output_buffer; output_buffer.resize(kMinimumGzipOutputBufferSize); @@ -247,9 +247,9 @@ z_stream stream_; - base::ThreadChecker thread_checker_; + SEQUENCE_CHECKER(sequence_checker_); - DISALLOW_COPY_AND_ASSIGN(FileThreadWorker); + DISALLOW_COPY_AND_ASSIGN(FileWorker); }; WebRtcRtpDumpWriter::WebRtcRtpDumpWriter( @@ -260,20 +260,21 @@ : max_dump_size_(max_dump_size), max_dump_size_reached_callback_(max_dump_size_reached_callback), total_dump_size_on_disk_(0), - incoming_file_thread_worker_(new FileThreadWorker(incoming_dump_path)), - outgoing_file_thread_worker_(new FileThreadWorker(outgoing_dump_path)), - weak_ptr_factory_(this) { -} + background_task_runner_(base::CreateSequencedTaskRunnerWithTraits( + {base::MayBlock(), base::TaskPriority::BACKGROUND})), + incoming_file_thread_worker_(new FileWorker(incoming_dump_path)), + outgoing_file_thread_worker_(new FileWorker(outgoing_dump_path)), + weak_ptr_factory_(this) {} WebRtcRtpDumpWriter::~WebRtcRtpDumpWriter() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - bool success = BrowserThread::DeleteSoon( - BrowserThread::FILE, FROM_HERE, incoming_file_thread_worker_.release()); + bool success = background_task_runner_->DeleteSoon( + FROM_HERE, incoming_file_thread_worker_.release()); DCHECK(success); - success = BrowserThread::DeleteSoon( - BrowserThread::FILE, FROM_HERE, outgoing_file_thread_worker_.release()); + success = background_task_runner_->DeleteSoon( + FROM_HERE, outgoing_file_thread_worker_.release()); DCHECK(success); } @@ -281,7 +282,7 @@ size_t header_length, size_t packet_length, bool incoming) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); static const size_t kMaxInMemoryBufferSize = 65536; @@ -317,7 +318,7 @@ void WebRtcRtpDumpWriter::EndDump(RtpDumpType type, const EndDumpCallback& finished_callback) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(type == RTP_DUMP_OUTGOING || incoming_file_thread_worker_ != NULL); DCHECK(type == RTP_DUMP_INCOMING || outgoing_file_thread_worker_ != NULL); @@ -335,7 +336,7 @@ } size_t WebRtcRtpDumpWriter::max_dump_size() const { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return max_dump_size_; } @@ -357,7 +358,7 @@ void WebRtcRtpDumpWriter::FlushBuffer(bool incoming, bool end_stream, const FlushDoneCallback& callback) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); std::unique_ptr<std::vector<uint8_t>> new_buffer(new std::vector<uint8_t>()); @@ -373,32 +374,31 @@ std::unique_ptr<size_t> bytes_written(new size_t(0)); - FileThreadWorker* worker = incoming ? incoming_file_thread_worker_.get() - : outgoing_file_thread_worker_.get(); + FileWorker* worker = incoming ? incoming_file_thread_worker_.get() + : outgoing_file_thread_worker_.get(); // Using "Unretained(worker)" because |worker| is owner by this object and it - // guaranteed to be deleted on the FILE thread before this object goes away. - base::Closure task = - base::Bind(&FileThreadWorker::CompressAndWriteToFileOnFileThread, - base::Unretained(worker), base::Passed(&new_buffer), - end_stream, result.get(), bytes_written.get()); + // guaranteed to be deleted on the backround task runner before this object + // goes away. + base::OnceClosure task = base::BindOnce( + &FileWorker::CompressAndWriteToFileOnFileThread, base::Unretained(worker), + std::move(new_buffer), end_stream, result.get(), bytes_written.get()); // OnFlushDone is necessary to avoid running the callback after this // object is gone. - base::Closure reply = base::Bind( + base::OnceClosure reply = base::BindOnce( &WebRtcRtpDumpWriter::OnFlushDone, weak_ptr_factory_.GetWeakPtr(), - callback, base::Passed(&result), base::Passed(&bytes_written)); + callback, std::move(result), std::move(bytes_written)); // Define the task and reply outside the method call so that getting and // passing the scoped_ptr does not depend on the argument evaluation order. - BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE, task, reply); + background_task_runner_->PostTaskAndReply(FROM_HERE, std::move(task), + std::move(reply)); if (end_stream) { - bool success = BrowserThread::DeleteSoon( - BrowserThread::FILE, - FROM_HERE, - incoming ? incoming_file_thread_worker_.release() - : outgoing_file_thread_worker_.release()); + bool success = background_task_runner_->DeleteSoon( + FROM_HERE, incoming ? incoming_file_thread_worker_.release() + : outgoing_file_thread_worker_.release()); DCHECK(success); } } @@ -407,7 +407,7 @@ const FlushDoneCallback& callback, const std::unique_ptr<FlushResult>& result, const std::unique_ptr<size_t>& bytes_written) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); total_dump_size_on_disk_ += *bytes_written; @@ -427,7 +427,7 @@ void WebRtcRtpDumpWriter::OnDumpEnded(EndDumpContext context, bool incoming, bool success) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DVLOG(2) << "Dump ended, incoming = " << incoming << ", succeeded = " << success;
diff --git a/chrome/browser/media/webrtc/webrtc_rtp_dump_writer.h b/chrome/browser/media/webrtc/webrtc_rtp_dump_writer.h index fb902c10..36551a9 100644 --- a/chrome/browser/media/webrtc/webrtc_rtp_dump_writer.h +++ b/chrome/browser/media/webrtc/webrtc_rtp_dump_writer.h
@@ -14,7 +14,8 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" +#include "base/sequence_checker.h" +#include "base/sequenced_task_runner.h" #include "base/time/time.h" #include "chrome/browser/media/webrtc/rtp_dump_type.h" @@ -65,6 +66,11 @@ size_t max_dump_size() const; + const scoped_refptr<base::SequencedTaskRunner>& background_task_runner() + const { + return background_task_runner_; + } + private: enum FlushResult { // Flushing has succeeded and the dump size is under the max limit. @@ -75,7 +81,7 @@ FLUSH_RESULT_FAILURE }; - class FileThreadWorker; + class FileWorker; typedef base::Callback<void(bool)> FlushDoneCallback; @@ -127,11 +133,12 @@ // The total on-disk size of the compressed incoming and outgoing dumps. size_t total_dump_size_on_disk_; - // File thread workers must be called and deleted on the FILE thread. - std::unique_ptr<FileThreadWorker> incoming_file_thread_worker_; - std::unique_ptr<FileThreadWorker> outgoing_file_thread_worker_; + // File workers must be called and deleted on the backround task runner. + scoped_refptr<base::SequencedTaskRunner> background_task_runner_; + std::unique_ptr<FileWorker> incoming_file_thread_worker_; + std::unique_ptr<FileWorker> outgoing_file_thread_worker_; - base::ThreadChecker thread_checker_; + SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory<WebRtcRtpDumpWriter> weak_ptr_factory_;
diff --git a/chrome/browser/media/webrtc/webrtc_rtp_dump_writer_unittest.cc b/chrome/browser/media/webrtc/webrtc_rtp_dump_writer_unittest.cc index 72c158f8..12e0d40 100644 --- a/chrome/browser/media/webrtc/webrtc_rtp_dump_writer_unittest.cc +++ b/chrome/browser/media/webrtc/webrtc_rtp_dump_writer_unittest.cc
@@ -16,6 +16,7 @@ #include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/run_loop.h" +#include "base/sequenced_task_runner.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h" @@ -49,6 +50,12 @@ static_cast<uint16_t>(extension_header_count)); } +static void FlushTaskRunner(base::SequencedTaskRunner* task_runner) { + base::RunLoop run_loop; + task_runner->PostTask(FROM_HERE, run_loop.QuitClosure()); + run_loop.Run(); +} + class WebRtcRtpDumpWriterTest : public testing::Test { public: WebRtcRtpDumpWriterTest() @@ -242,9 +249,9 @@ base::Bind(&WebRtcRtpDumpWriterTest::OnEndDumpDone, base::Unretained(this))); - content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); + FlushTaskRunner(writer_->background_task_runner().get()); base::RunLoop().RunUntilIdle(); - content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); + FlushTaskRunner(writer_->background_task_runner().get()); base::RunLoop().RunUntilIdle(); } EXPECT_FALSE(base::PathExists(incoming_dump_path_)); @@ -269,9 +276,9 @@ base::Bind(&WebRtcRtpDumpWriterTest::OnEndDumpDone, base::Unretained(this))); - content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); + FlushTaskRunner(writer_->background_task_runner().get()); base::RunLoop().RunUntilIdle(); - content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); + FlushTaskRunner(writer_->background_task_runner().get()); base::RunLoop().RunUntilIdle(); } @@ -311,9 +318,9 @@ base::Bind(&WebRtcRtpDumpWriterTest::OnEndDumpDone, base::Unretained(this))); - content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); + FlushTaskRunner(writer_->background_task_runner().get()); base::RunLoop().RunUntilIdle(); - content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); + FlushTaskRunner(writer_->background_task_runner().get()); base::RunLoop().RunUntilIdle(); } VerifyDumps(kPacketCount, kPacketCount); @@ -328,9 +335,9 @@ writer_.reset(); - content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); + // Two |RunUntilIdle()| calls are needed as the first run posts a task that + // we need to give a chance to run with the second call. base::RunLoop().RunUntilIdle(); - content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); base::RunLoop().RunUntilIdle(); } @@ -359,9 +366,9 @@ base::Bind(&WebRtcRtpDumpWriterTest::OnEndDumpDone, base::Unretained(this))); - content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); + FlushTaskRunner(writer_->background_task_runner().get()); base::RunLoop().RunUntilIdle(); - content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); + FlushTaskRunner(writer_->background_task_runner().get()); base::RunLoop().RunUntilIdle(); }
diff --git a/chrome/browser/metrics/chrome_metrics_service_accessor.h b/chrome/browser/metrics/chrome_metrics_service_accessor.h index 143a252..74a0b98 100644 --- a/chrome/browser/metrics/chrome_metrics_service_accessor.h +++ b/chrome/browser/metrics/chrome_metrics_service_accessor.h
@@ -50,10 +50,6 @@ class BrowserOptionsHandler; } -namespace precache { -void RegisterPrecacheSyntheticFieldTrial(base::Time); -} - namespace prerender { bool IsOmniboxEnabled(Profile* profile); } @@ -115,7 +111,6 @@ bool, const OnMetricsReportingCallbackType&); friend class options::BrowserOptionsHandler; - friend void precache::RegisterPrecacheSyntheticFieldTrial(base::Time); friend bool prerender::IsOmniboxEnabled(Profile* profile); friend class settings::MetricsReportingHandler; friend class speech::ChromeSpeechRecognitionManagerDelegate;
diff --git a/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc b/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc index cfb80a2..02b443f 100644 --- a/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc +++ b/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc
@@ -395,8 +395,17 @@ content::BrowserContext::GetDefaultStoragePartition(profile) ->GetURLRequestContext(); + std::string api_key; + // The API is private. If we don't have the official API key, don't even try. + if (google_apis::IsGoogleChromeAPIKeyUsed()) { + bool is_stable_channel = + chrome::GetChannel() == version_info::Channel::STABLE; + api_key = is_stable_channel ? google_apis::GetAPIKey() + : google_apis::GetNonStableAPIKey(); + } + auto subscription_manager = base::MakeUnique<SubscriptionManager>( - request_context, pref_service, signin_manager, token_service, + request_context, pref_service, signin_manager, token_service, api_key, GetPushUpdatesSubscriptionEndpoint(chrome::GetChannel()), GetPushUpdatesUnsubscriptionEndpoint(chrome::GetChannel()));
diff --git a/chrome/browser/precache/OWNERS b/chrome/browser/precache/OWNERS deleted file mode 100644 index f24d985..0000000 --- a/chrome/browser/precache/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -file://components/precache/OWNERS \ No newline at end of file
diff --git a/chrome/browser/precache/precache_manager_factory.cc b/chrome/browser/precache/precache_manager_factory.cc deleted file mode 100644 index 3ec3cfb7..0000000 --- a/chrome/browser/precache/precache_manager_factory.cc +++ /dev/null
@@ -1,69 +0,0 @@ -// 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 "chrome/browser/precache/precache_manager_factory.h" - -#include <memory> -#include <utility> - -#include "base/files/file_path.h" -#include "chrome/browser/history/history_service_factory.h" -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h" -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h" -#include "chrome/browser/predictors/loading_predictor.h" -#include "chrome/browser/predictors/loading_predictor_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/sync/profile_sync_service_factory.h" -#include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/keyed_service/core/service_access_type.h" -#include "components/precache/content/precache_manager.h" -#include "components/precache/core/precache_database.h" -#include "content/public/browser/browser_context.h" - -namespace precache { - -// static -PrecacheManager* PrecacheManagerFactory::GetForBrowserContext( - content::BrowserContext* browser_context) { - return static_cast<PrecacheManager*>( - GetInstance()->GetServiceForBrowserContext(browser_context, true)); -} - -// static -PrecacheManagerFactory* PrecacheManagerFactory::GetInstance() { - return base::Singleton<PrecacheManagerFactory>::get(); -} - -PrecacheManagerFactory::PrecacheManagerFactory() - : BrowserContextKeyedServiceFactory( - "PrecacheManager", - BrowserContextDependencyManager::GetInstance()) { - DependsOn(ProfileSyncServiceFactory::GetInstance()); - DependsOn(HistoryServiceFactory::GetInstance()); - DependsOn(DataReductionProxyChromeSettingsFactory::GetInstance()); - DependsOn(predictors::LoadingPredictorFactory::GetInstance()); -} - -PrecacheManagerFactory::~PrecacheManagerFactory() { -} - -KeyedService* PrecacheManagerFactory::BuildServiceInstanceFor( - content::BrowserContext* browser_context) const { - std::unique_ptr<PrecacheDatabase> precache_database( - new PrecacheDatabase()); - base::FilePath db_path(browser_context->GetPath().Append( - base::FilePath(FILE_PATH_LITERAL("PrecacheDatabase")))); - return new PrecacheManager( - browser_context, - ProfileSyncServiceFactory::GetSyncServiceForBrowserContext( - browser_context), - HistoryServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context), - ServiceAccessType::IMPLICIT_ACCESS), - DataReductionProxyChromeSettingsFactory::GetForBrowserContext( - browser_context), - db_path, std::move(precache_database)); -} - -} // namespace precache
diff --git a/chrome/browser/precache/precache_manager_factory.h b/chrome/browser/precache/precache_manager_factory.h deleted file mode 100644 index f65e844..0000000 --- a/chrome/browser/precache/precache_manager_factory.h +++ /dev/null
@@ -1,41 +0,0 @@ -// 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 CHROME_BROWSER_PRECACHE_PRECACHE_MANAGER_FACTORY_H_ -#define CHROME_BROWSER_PRECACHE_PRECACHE_MANAGER_FACTORY_H_ - -#include "base/macros.h" -#include "base/memory/singleton.h" -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" - -namespace content { -class BrowserContext; -} - -namespace precache { - -class PrecacheManager; - -class PrecacheManagerFactory : public BrowserContextKeyedServiceFactory { - public: - static PrecacheManager* GetForBrowserContext( - content::BrowserContext* browser_context); - static PrecacheManagerFactory* GetInstance(); - - private: - friend struct base::DefaultSingletonTraits<PrecacheManagerFactory>; - - PrecacheManagerFactory(); - ~PrecacheManagerFactory() override; - - // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* browser_context) const override; - - DISALLOW_COPY_AND_ASSIGN(PrecacheManagerFactory); -}; - -} // namespace precache - -#endif // CHROME_BROWSER_PRECACHE_PRECACHE_MANAGER_FACTORY_H_
diff --git a/chrome/browser/precache/precache_util.cc b/chrome/browser/precache/precache_util.cc deleted file mode 100644 index ca37327..0000000 --- a/chrome/browser/precache/precache_util.cc +++ /dev/null
@@ -1,101 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/precache/precache_util.h" - -#include <string> -#include <vector> - -#include "base/metrics/field_trial.h" -#include "base/time/time.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/metrics/chrome_metrics_service_accessor.h" -#include "chrome/browser/precache/precache_manager_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/profiles/profile_manager.h" -#include "components/data_use_measurement/content/content_url_request_classifier.h" -#include "components/precache/content/precache_manager.h" -#include "content/public/browser/browser_thread.h" -#include "net/url_request/url_request.h" -#include "url/gurl.h" - -namespace net { -class HttpResponseInfo; -} - -namespace { - -const char kPrecacheSynthetic15D[] = "PrecacheSynthetic15D"; -const char kPrecacheSynthetic1D[] = "PrecacheSynthetic1D"; - -void UpdatePrecacheMetricsAndStateOnUIThread(const GURL& url, - const GURL& referrer, - const base::Time& fetch_time, - const net::HttpResponseInfo& info, - int64_t size, - bool is_user_traffic, - void* profile_id) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - if (!g_browser_process->profile_manager()->IsValidProfile(profile_id)) - return; - Profile* profile = reinterpret_cast<Profile*>(profile_id); - - precache::PrecacheManager* precache_manager = - precache::PrecacheManagerFactory::GetForBrowserContext(profile); - // |precache_manager| could be NULL if the profile is off the record. - if (!precache_manager || !precache_manager->IsPrecachingAllowed()) - return; - - precache_manager->UpdatePrecacheMetricsAndState( - url, referrer, fetch_time, info, size, is_user_traffic, - base::Bind(&precache::RegisterPrecacheSyntheticFieldTrial)); -} - -} // namespace - -namespace precache { - -// TODO(rajendrant): Add unittests for this function. -void UpdatePrecacheMetricsAndState(const net::URLRequest* request, - void* profile_id) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - - // For better accuracy, we use the actual bytes read instead of the length - // specified with the Content-Length header, which may be inaccurate, - // or missing, as is the case with chunked encoding. - int64_t received_content_length = request->received_response_content_length(); - - // Record precache metrics when a fetch is completed successfully, if - // precaching is allowed. - content::BrowserThread::PostTask( - content::BrowserThread::UI, FROM_HERE, - base::Bind(&UpdatePrecacheMetricsAndStateOnUIThread, request->url(), - GURL(request->referrer()), base::Time::Now(), - request->response_info(), received_content_length, - data_use_measurement::IsUserRequest(*request), profile_id)); -} - -// |last_precache_time| is the last time precache task was run. -void RegisterPrecacheSyntheticFieldTrial(base::Time last_precache_time) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - std::vector<uint32_t> groups; - base::TimeDelta time_ago = base::Time::Now() - last_precache_time; - // Look up the current group name (e.g. Control or Enabled). - std::string group_name = - base::FieldTrialList::FindFullName(kPrecacheFieldTrialName); - // group_name should only be empty if the Precache trial does not exist. - if (!group_name.empty()) { - // Register matching synthetic trials for 15-day and 1-day candidates. - if (time_ago <= base::TimeDelta::FromDays(15)) - ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial( - kPrecacheSynthetic15D, group_name); - if (time_ago <= base::TimeDelta::FromDays(1)) - ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial( - kPrecacheSynthetic1D, group_name); - } -} - -} // namespace precache
diff --git a/chrome/browser/precache/precache_util.h b/chrome/browser/precache/precache_util.h deleted file mode 100644 index 80a1fc8..0000000 --- a/chrome/browser/precache/precache_util.h +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_PRECACHE_PRECACHE_UTIL_H_ -#define CHROME_BROWSER_PRECACHE_PRECACHE_UTIL_H_ - -namespace net { -class URLRequest; -} - -namespace precache { - -void UpdatePrecacheMetricsAndState(const net::URLRequest* request, - void* profile_id); - -} // namespace precache - -#endif // CHROME_BROWSER_PRECACHE_PRECACHE_UTIL_H_
diff --git a/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html b/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html index 59d5d65..dc95636 100644 --- a/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html +++ b/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html
@@ -87,6 +87,10 @@ #clearFrom { -webkit-margin-start: 0.5em; + /* Adjust for 1px md-select-underline and 1px additional bottom padding + * to keep md-select's text (without the underline) aligned with + * neighboring text that does not have an underline. */ + margin-top: 2px; } .title .secondary {
diff --git a/chrome/browser/search_engines/template_url_parser_unittest.cc b/chrome/browser/search_engines/template_url_parser_unittest.cc index 105f91a..ea31c628 100644 --- a/chrome/browser/search_engines/template_url_parser_unittest.cc +++ b/chrome/browser/search_engines/template_url_parser_unittest.cc
@@ -56,8 +56,6 @@ void SetUp() override; - bool is_disabled() const; - // Parses the OpenSearch description document at file_name (relative to the // data dir). The TemplateURL is placed in |template_url_|. void ParseFile(const std::string& file_name, @@ -67,7 +65,7 @@ std::unique_ptr<TemplateURL> template_url_; private: - base::FilePath full_path_; + base::FilePath osdd_dir_; }; TemplateURLParserTest::TemplateURLParserTest() { @@ -77,26 +75,18 @@ } void TemplateURLParserTest::SetUp() { - ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &full_path_)); - full_path_ = full_path_.AppendASCII("osdd"); - if (!base::PathExists(full_path_)) { - LOG(ERROR) << - "This test can't be run without some non-redistributable data"; - full_path_ = base::FilePath(); - } -} - -bool TemplateURLParserTest::is_disabled() const { - return full_path_.empty(); + ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &osdd_dir_)); + // TODO(https://crbug.com/739331): Rename the path to "osdd" after most + // developers have synced over the removal of the old osdd directory from the + // internal repository. + osdd_dir_ = osdd_dir_.AppendASCII("osdd_new"); + ASSERT_TRUE(base::PathExists(osdd_dir_)); } void TemplateURLParserTest::ParseFile( const std::string& file_name, TemplateURLParser::ParameterFilter* filter) { - base::FilePath full_path; - ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &full_path)); - full_path = full_path.AppendASCII("osdd"); - full_path = full_path.AppendASCII(file_name); + base::FilePath full_path = osdd_dir_.AppendASCII(file_name); ASSERT_TRUE(base::PathExists(full_path)); std::string contents; @@ -109,29 +99,21 @@ // Actual tests --------------------------------------------------------------- TEST_F(TemplateURLParserTest, FailOnBogusURL) { - if (is_disabled()) - return; ASSERT_NO_FATAL_FAILURE(ParseFile("bogus.xml", NULL)); EXPECT_FALSE(template_url_.get()); } TEST_F(TemplateURLParserTest, PassOnHTTPS) { - if (is_disabled()) - return; ASSERT_NO_FATAL_FAILURE(ParseFile("https.xml", NULL)); EXPECT_TRUE(template_url_.get()); } TEST_F(TemplateURLParserTest, FailOnPost) { - if (is_disabled()) - return; ASSERT_NO_FATAL_FAILURE(ParseFile("post.xml", NULL)); EXPECT_FALSE(template_url_.get()); } TEST_F(TemplateURLParserTest, TestDictionary) { - if (is_disabled()) - return; ASSERT_NO_FATAL_FAILURE(ParseFile("dictionary.xml", NULL)); ASSERT_TRUE(template_url_.get()); EXPECT_EQ(ASCIIToUTF16("Dictionary.com"), template_url_->short_name()); @@ -143,8 +125,6 @@ } TEST_F(TemplateURLParserTest, TestMSDN) { - if (is_disabled()) - return; ASSERT_NO_FATAL_FAILURE(ParseFile("msdn.xml", NULL)); ASSERT_TRUE(template_url_.get()); EXPECT_EQ(ASCIIToUTF16("Search \" MSDN"), template_url_->short_name()); @@ -157,8 +137,6 @@ } TEST_F(TemplateURLParserTest, TestWikipedia) { - if (is_disabled()) - return; ASSERT_NO_FATAL_FAILURE(ParseFile("wikipedia.xml", NULL)); ASSERT_TRUE(template_url_.get()); EXPECT_EQ(ASCIIToUTF16("Wikipedia (English)"), template_url_->short_name()); @@ -179,14 +157,10 @@ } TEST_F(TemplateURLParserTest, NoCrashOnEmptyAttributes) { - if (is_disabled()) - return; ASSERT_NO_FATAL_FAILURE(ParseFile("url_with_no_attributes.xml", NULL)); } TEST_F(TemplateURLParserTest, TestFirefoxEbay) { - if (is_disabled()) - return; // This file uses the Parameter extension // (see http://www.opensearch.org/Specifications/OpenSearch/Extensions/Parameter/1.0) ParamFilterImpl filter("ebay", "ebay"); @@ -205,8 +179,6 @@ } TEST_F(TemplateURLParserTest, TestFirefoxWebster) { - if (is_disabled()) - return; // This XML file uses a namespace. ParamFilterImpl filter(std::string(), "Mozilla"); ASSERT_NO_FATAL_FAILURE(ParseFile("firefox_webster.xml", &filter)); @@ -222,8 +194,6 @@ } TEST_F(TemplateURLParserTest, TestFirefoxYahoo) { - if (is_disabled()) - return; // This XML file uses a namespace. ParamFilterImpl filter(std::string(), "Mozilla"); ASSERT_NO_FATAL_FAILURE(ParseFile("firefox_yahoo.xml", &filter)); @@ -244,8 +214,6 @@ // Make sure we ignore POST suggestions (this is the same XML file as // firefox_yahoo.xml, the suggestion method was just changed to POST). TEST_F(TemplateURLParserTest, TestPostSuggestion) { - if (is_disabled()) - return; // This XML file uses a namespace. ParamFilterImpl filter(std::string(), "Mozilla"); ASSERT_NO_FATAL_FAILURE(ParseFile("post_suggestion.xml", &filter));
diff --git a/chrome/browser/signin/dice_response_handler.cc b/chrome/browser/signin/dice_response_handler.cc index 5b93dda..042f222a 100644 --- a/chrome/browser/signin/dice_response_handler.cc +++ b/chrome/browser/signin/dice_response_handler.cc
@@ -225,6 +225,8 @@ VLOG(1) << "[Dice] Signing out all accounts."; signin_manager_->SignOut(signin_metrics::SERVER_FORCED_DISABLE, signin_metrics::SignoutDelete::IGNORE_METRIC); + // Cancel all Dice token fetches currently in flight. + token_fetchers_.clear(); return; } else { signed_out_accounts.push_back(signed_out_account); @@ -234,6 +236,16 @@ for (const auto& account : signed_out_accounts) { VLOG(1) << "[Dice]: Revoking token for account: " << account; token_service_->RevokeCredentials(account); + // If a token fetch is in flight for the same account, cancel it. + for (auto it = token_fetchers_.begin(); it != token_fetchers_.end(); ++it) { + std::string token_fetcher_account_id = + account_tracker_service_->PickAccountIdForAccount( + it->get()->gaia_id(), it->get()->email()); + if (token_fetcher_account_id == account) { + token_fetchers_.erase(it); + break; + } + } } }
diff --git a/chrome/browser/signin/dice_response_handler_unittest.cc b/chrome/browser/signin/dice_response_handler_unittest.cc index 50e1bb9..87fbfa8 100644 --- a/chrome/browser/signin/dice_response_handler_unittest.cc +++ b/chrome/browser/signin/dice_response_handler_unittest.cc
@@ -295,6 +295,76 @@ EXPECT_FALSE(signin_manager_.IsAuthenticated()); } +// Checks that signin in progress is canceled by a signout for the main account. +TEST_F(DiceResponseHandlerTest, SigninSignoutMainAccount) { + DiceResponseParams dice_params = MakeDiceParams(DiceAction::SIGNOUT); + // User is signed in to Chrome with a main account. + signin_manager_.SignIn(dice_params.signout_info.gaia_id[0], + dice_params.signout_info.email[0], "password"); + token_service_.UpdateCredentials(dice_params.signout_info.gaia_id[0], + "token"); + ASSERT_TRUE(token_service_.RefreshTokenIsAvailable( + dice_params.signout_info.gaia_id[0])); + // Start Dice signin with a secondary account. + DiceResponseParams dice_params_2 = MakeDiceParams(DiceAction::SIGNIN); + dice_params_2.signin_info.email = "other_email"; + dice_params_2.signin_info.gaia_id = "other_gaia_id"; + dice_response_handler_.ProcessDiceHeader(dice_params_2); + // Check that a GaiaAuthFetcher has been created and is pending. + ASSERT_THAT(signin_client_.consumer_, testing::NotNull()); + EXPECT_EQ( + 1u, dice_response_handler_.GetPendingDiceTokenFetchersCountForTesting()); + ASSERT_FALSE(token_service_.RefreshTokenIsAvailable( + dice_params_2.signin_info.gaia_id)); + // Signout from main account while signin for the other account is in flight. + dice_response_handler_.ProcessDiceHeader(dice_params); + // Check that the token fetcher has been canceled and all tokens erased. + EXPECT_EQ( + 0u, dice_response_handler_.GetPendingDiceTokenFetchersCountForTesting()); + EXPECT_FALSE( + token_service_.RefreshTokenIsAvailable(dice_params.signin_info.gaia_id)); + EXPECT_FALSE(token_service_.RefreshTokenIsAvailable( + dice_params_2.signin_info.gaia_id)); +} + +// Checks that signin in progress is canceled by a signout for a secondary +// account. +TEST_F(DiceResponseHandlerTest, SigninSignoutSecondaryAccount) { + // User starts signin in the web with two accounts, and is not signed into + // Chrome. + DiceResponseParams signout_params_1 = MakeDiceParams(DiceAction::SIGNOUT); + DiceResponseParams signin_params_1 = MakeDiceParams(DiceAction::SIGNIN); + DiceResponseParams signin_params_2 = MakeDiceParams(DiceAction::SIGNIN); + signin_params_2.signin_info.email = "other_email"; + signin_params_2.signin_info.gaia_id = "other_gaia_id"; + dice_response_handler_.ProcessDiceHeader(signin_params_1); + ASSERT_THAT(signin_client_.consumer_, testing::NotNull()); + signin_client_.consumer_ = nullptr; + dice_response_handler_.ProcessDiceHeader(signin_params_2); + ASSERT_THAT(signin_client_.consumer_, testing::NotNull()); + EXPECT_EQ( + 2u, dice_response_handler_.GetPendingDiceTokenFetchersCountForTesting()); + ASSERT_FALSE(token_service_.RefreshTokenIsAvailable( + signin_params_1.signin_info.gaia_id)); + ASSERT_FALSE(token_service_.RefreshTokenIsAvailable( + signin_params_2.signin_info.gaia_id)); + // Signout from one of the accounts while signin is in flight. + dice_response_handler_.ProcessDiceHeader(signout_params_1); + // Check that one of the fetchers is cancelled. + EXPECT_EQ( + 1u, dice_response_handler_.GetPendingDiceTokenFetchersCountForTesting()); + // Allow the remaining fetcher to complete. + signin_client_.consumer_->OnClientOAuthSuccess( + GaiaAuthConsumer::ClientOAuthResult("refresh_token", "access_token", 10)); + EXPECT_EQ( + 0u, dice_response_handler_.GetPendingDiceTokenFetchersCountForTesting()); + // Check that the right token is available. + EXPECT_FALSE(token_service_.RefreshTokenIsAvailable( + signin_params_1.signin_info.gaia_id)); + EXPECT_TRUE(token_service_.RefreshTokenIsAvailable( + signin_params_2.signin_info.gaia_id)); +} + // Tests that the DiceResponseHandler is created for a normal profile but not // for an incognito profile. TEST(DiceResponseHandlerFactoryTest, NotInIncognito) {
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 0fe9ce05..b256144e 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -2328,7 +2328,6 @@ "android/infobars/search_geolocation_disclosure_infobar.cc", "android/infobars/search_geolocation_disclosure_infobar.h", "android/infobars/simple_confirm_infobar_builder.cc", - "android/infobars/simple_confirm_infobar_builder.h", "android/infobars/translate_compact_infobar.cc", "android/infobars/translate_compact_infobar.h", "android/infobars/translate_infobar.cc", @@ -2343,9 +2342,7 @@ "android/omnibox/omnibox_view_util.cc", "android/omnibox/omnibox_view_util.h", "android/page_info/certificate_chain_helper.cc", - "android/page_info/certificate_chain_helper.h", "android/page_info/certificate_viewer_android.cc", - "android/page_info/certificate_viewer_android.h", "android/page_info/connection_info_popup_android.cc", "android/page_info/connection_info_popup_android.h", "android/page_info/page_info_popup_android.cc", @@ -2354,13 +2351,11 @@ "android/snackbars/auto_signin_prompt_controller.cc", "android/snackbars/auto_signin_prompt_controller.h", "android/ssl_client_certificate_request.cc", - "android/ssl_client_certificate_request.h", "android/tab_contents/chrome_web_contents_view_delegate_android.cc", "android/tab_contents/chrome_web_contents_view_delegate_android.h", "android/tab_model/android_live_tab_context.cc", "android/tab_model/android_live_tab_context.h", "android/tab_model/single_tab_model.cc", - "android/tab_model/single_tab_model.h", "android/tab_model/tab_model.cc", "android/tab_model/tab_model.h", "android/tab_model/tab_model_jni_bridge.cc",
diff --git a/chrome/browser/ui/android/autofill/autofill_keyboard_accessory_view.cc b/chrome/browser/ui/android/autofill/autofill_keyboard_accessory_view.cc index 8f48efa5c..aeb4fd1 100644 --- a/chrome/browser/ui/android/autofill/autofill_keyboard_accessory_view.cc +++ b/chrome/browser/ui/android/autofill/autofill_keyboard_accessory_view.cc
@@ -174,10 +174,4 @@ delete this; } -// static -bool AutofillKeyboardAccessoryView::RegisterAutofillKeyboardAccessoryView( - JNIEnv* env) { - return RegisterNativesImpl(env); -} - } // namespace autofill
diff --git a/chrome/browser/ui/android/autofill/autofill_keyboard_accessory_view.h b/chrome/browser/ui/android/autofill/autofill_keyboard_accessory_view.h index 2a89a518..ac4f292 100644 --- a/chrome/browser/ui/android/autofill/autofill_keyboard_accessory_view.h +++ b/chrome/browser/ui/android/autofill/autofill_keyboard_accessory_view.h
@@ -45,8 +45,6 @@ void ViewDismissed(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); - static bool RegisterAutofillKeyboardAccessoryView(JNIEnv* env); - protected: // AutofillPopupView implementation. void Show() override;
diff --git a/chrome/browser/ui/android/autofill/autofill_popup_view_android.cc b/chrome/browser/ui/android/autofill/autofill_popup_view_android.cc index 618c5713..c21446f 100644 --- a/chrome/browser/ui/android/autofill/autofill_popup_view_android.cc +++ b/chrome/browser/ui/android/autofill/autofill_popup_view_android.cc
@@ -176,11 +176,6 @@ } // static -bool AutofillPopupViewAndroid::RegisterAutofillPopupViewAndroid(JNIEnv* env) { - return RegisterNativesImpl(env); -} - -// static AutofillPopupView* AutofillPopupView::Create( AutofillPopupController* controller) { if (IsKeyboardAccessoryEnabled())
diff --git a/chrome/browser/ui/android/autofill/autofill_popup_view_android.h b/chrome/browser/ui/android/autofill/autofill_popup_view_android.h index 3b58062..21a2c164 100644 --- a/chrome/browser/ui/android/autofill/autofill_popup_view_android.h +++ b/chrome/browser/ui/android/autofill/autofill_popup_view_android.h
@@ -40,8 +40,6 @@ void PopupDismissed(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); - static bool RegisterAutofillPopupViewAndroid(JNIEnv* env); - protected: // AutofillPopupView implementation. void Show() override;
diff --git a/chrome/browser/ui/android/autofill/card_unmask_prompt_view_android.cc b/chrome/browser/ui/android/autofill/card_unmask_prompt_view_android.cc index 5de30c6..ebc243e4 100644 --- a/chrome/browser/ui/android/autofill/card_unmask_prompt_view_android.cc +++ b/chrome/browser/ui/android/autofill/card_unmask_prompt_view_android.cc
@@ -128,9 +128,4 @@ allow_retry); } -// static -bool CardUnmaskPromptViewAndroid::Register(JNIEnv* env) { - return RegisterNativesImpl(env); -} - } // namespace autofill
diff --git a/chrome/browser/ui/android/autofill/card_unmask_prompt_view_android.h b/chrome/browser/ui/android/autofill/card_unmask_prompt_view_android.h index 4cae721b..bcf9742 100644 --- a/chrome/browser/ui/android/autofill/card_unmask_prompt_view_android.h +++ b/chrome/browser/ui/android/autofill/card_unmask_prompt_view_android.h
@@ -50,8 +50,6 @@ void GotVerificationResult(const base::string16& error_message, bool allow_retry) override; - static bool Register(JNIEnv* env); - private: ~CardUnmaskPromptViewAndroid() override;
diff --git a/chrome/browser/ui/android/autofill/credit_card_scanner_view_android.cc b/chrome/browser/ui/android/autofill/credit_card_scanner_view_android.cc index b174505..ab68e20 100644 --- a/chrome/browser/ui/android/autofill/credit_card_scanner_view_android.cc +++ b/chrome/browser/ui/android/autofill/credit_card_scanner_view_android.cc
@@ -39,11 +39,6 @@ new CreditCardScannerViewAndroid(delegate, web_contents)); } -// static -bool CreditCardScannerViewAndroid::Register(JNIEnv* env) { - return RegisterNativesImpl(env); -} - CreditCardScannerViewAndroid::CreditCardScannerViewAndroid( const base::WeakPtr<CreditCardScannerViewDelegate>& delegate, content::WebContents* web_contents)
diff --git a/chrome/browser/ui/android/autofill/credit_card_scanner_view_android.h b/chrome/browser/ui/android/autofill/credit_card_scanner_view_android.h index 4e8a98f..069c505 100644 --- a/chrome/browser/ui/android/autofill/credit_card_scanner_view_android.h +++ b/chrome/browser/ui/android/autofill/credit_card_scanner_view_android.h
@@ -24,9 +24,6 @@ // APIs through JNI service. class CreditCardScannerViewAndroid : public CreditCardScannerView { public: - // Registers with JNI services. - static bool Register(JNIEnv* env); - CreditCardScannerViewAndroid( const base::WeakPtr<CreditCardScannerViewDelegate>& delegate, content::WebContents* web_contents);
diff --git a/chrome/browser/ui/android/autofill/password_generation_popup_view_android.cc b/chrome/browser/ui/android/autofill/password_generation_popup_view_android.cc index 1a8193cd..aa27dd02 100644 --- a/chrome/browser/ui/android/autofill/password_generation_popup_view_android.cc +++ b/chrome/browser/ui/android/autofill/password_generation_popup_view_android.cc
@@ -50,11 +50,6 @@ controller_->PasswordAccepted(); } -// static -bool PasswordGenerationPopupViewAndroid::Register(JNIEnv* env) { - return RegisterNativesImpl(env); -} - PasswordGenerationPopupViewAndroid::~PasswordGenerationPopupViewAndroid() {} void PasswordGenerationPopupViewAndroid::Show() {
diff --git a/chrome/browser/ui/android/autofill/password_generation_popup_view_android.h b/chrome/browser/ui/android/autofill/password_generation_popup_view_android.h index 81ce1065..3694a47f 100644 --- a/chrome/browser/ui/android/autofill/password_generation_popup_view_android.h +++ b/chrome/browser/ui/android/autofill/password_generation_popup_view_android.h
@@ -36,9 +36,6 @@ void PasswordSelected(JNIEnv* env, const base::android::JavaParamRef<jobject>& object); - // Registers the popup with JNI. - static bool Register(JNIEnv* env); - private: // The popup owns itself. virtual ~PasswordGenerationPopupViewAndroid();
diff --git a/chrome/browser/ui/android/bluetooth_chooser_android.cc b/chrome/browser/ui/android/bluetooth_chooser_android.cc index aabfc617..0c567a81 100644 --- a/chrome/browser/ui/android/bluetooth_chooser_android.cc +++ b/chrome/browser/ui/android/bluetooth_chooser_android.cc
@@ -159,11 +159,6 @@ event_handler_.Run(Event::SHOW_NEED_LOCATION_HELP, ""); } -// static -bool BluetoothChooserAndroid::Register(JNIEnv* env) { - return RegisterNativesImpl(env); -} - void BluetoothChooserAndroid::OpenURL(const char* url) { web_contents_->OpenURL(content::OpenURLParams( GURL(url), content::Referrer(), WindowOpenDisposition::NEW_FOREGROUND_TAB,
diff --git a/chrome/browser/ui/android/bluetooth_chooser_android.h b/chrome/browser/ui/android/bluetooth_chooser_android.h index 899ad48..af41b0e 100644 --- a/chrome/browser/ui/android/bluetooth_chooser_android.h +++ b/chrome/browser/ui/android/bluetooth_chooser_android.h
@@ -50,8 +50,6 @@ JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); - static bool Register(JNIEnv* env); - private: void OpenURL(const char* url); base::android::ScopedJavaGlobalRef<jobject> java_dialog_;
diff --git a/chrome/browser/ui/android/chrome_http_auth_handler.cc b/chrome/browser/ui/android/chrome_http_auth_handler.cc index bc094d9..4e084bd 100644 --- a/chrome/browser/ui/android/chrome_http_auth_handler.cc +++ b/chrome/browser/ui/android/chrome_http_auth_handler.cc
@@ -82,8 +82,3 @@ return ConvertUTF16ToJavaString( env, authority_ + base::ASCIIToUTF16(" ") + explanation_); } - -// static -bool ChromeHttpAuthHandler::RegisterChromeHttpAuthHandler(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/chrome_http_auth_handler.h b/chrome/browser/ui/android/chrome_http_auth_handler.h index 9aea6e1..17b0ff9 100644 --- a/chrome/browser/ui/android/chrome_http_auth_handler.h +++ b/chrome/browser/ui/android/chrome_http_auth_handler.h
@@ -55,8 +55,6 @@ base::android::ScopedJavaLocalRef<jstring> GetMessageBody( JNIEnv* env, const base::android::JavaParamRef<jobject>&); - // Registers the ChromeHttpAuthHandler native methods. - static bool RegisterChromeHttpAuthHandler(JNIEnv* env); private: LoginHandler* observer_; base::android::ScopedJavaGlobalRef<jobject> java_chrome_http_auth_handler_;
diff --git a/chrome/browser/ui/android/context_menu_helper.cc b/chrome/browser/ui/android/context_menu_helper.cc index fc954f3d..493bd39 100644 --- a/chrome/browser/ui/android/context_menu_helper.cc +++ b/chrome/browser/ui/android/context_menu_helper.cc
@@ -228,7 +228,3 @@ base::Bind(retrieve_callback, base::Passed(&thumbnail_capturer), base::android::ScopedJavaGlobalRef<jobject>(env, jcallback))); } - -bool RegisterContextMenuHelper(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/context_menu_helper.h b/chrome/browser/ui/android/context_menu_helper.h index 2d6b5b4..fc841db9 100644 --- a/chrome/browser/ui/android/context_menu_helper.h +++ b/chrome/browser/ui/android/context_menu_helper.h
@@ -85,6 +85,4 @@ DISALLOW_COPY_AND_ASSIGN(ContextMenuHelper); }; -bool RegisterContextMenuHelper(JNIEnv* env); - #endif // CHROME_BROWSER_UI_ANDROID_CONTEXT_MENU_HELPER_H_
diff --git a/chrome/browser/ui/android/infobars/autofill_save_card_infobar.cc b/chrome/browser/ui/android/infobars/autofill_save_card_infobar.cc index b100550..4a16294 100644 --- a/chrome/browser/ui/android/infobars/autofill_save_card_infobar.cc +++ b/chrome/browser/ui/android/infobars/autofill_save_card_infobar.cc
@@ -43,11 +43,6 @@ GURL(base::android::ConvertJavaStringToUTF16(env, url))); } -// static -bool AutofillSaveCardInfoBar::Register(JNIEnv* env) { - return RegisterNativesImpl(env); -} - base::android::ScopedJavaLocalRef<jobject> AutofillSaveCardInfoBar::CreateRenderInfoBar(JNIEnv* env) { autofill::AutofillSaveCardInfoBarDelegateMobile* delegate =
diff --git a/chrome/browser/ui/android/infobars/autofill_save_card_infobar.h b/chrome/browser/ui/android/infobars/autofill_save_card_infobar.h index 498e8f8..0a70497 100644 --- a/chrome/browser/ui/android/infobars/autofill_save_card_infobar.h +++ b/chrome/browser/ui/android/infobars/autofill_save_card_infobar.h
@@ -27,9 +27,6 @@ // Called when a link in the legal message text was clicked. void OnLegalMessageLinkClicked(JNIEnv* env, jobject obj, jstring url); - // Registers the JNI bindings. - static bool Register(JNIEnv* env); - private: // ConfirmInfoBar: base::android::ScopedJavaLocalRef<jobject> CreateRenderInfoBar(
diff --git a/chrome/browser/ui/android/infobars/infobar_android.cc b/chrome/browser/ui/android/infobars/infobar_android.cc index 6c130164..6c4b366 100644 --- a/chrome/browser/ui/android/infobars/infobar_android.cc +++ b/chrome/browser/ui/android/infobars/infobar_android.cc
@@ -84,10 +84,3 @@ int InfoBarAndroid::GetEnumeratedIconId() { return ResourceMapper::MapFromChromiumId(delegate()->GetIconId()); } - - -// Native JNI methods --------------------------------------------------------- - -bool RegisterNativeInfoBar(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/infobars/infobar_android.h b/chrome/browser/ui/android/infobars/infobar_android.h index 0115ea6..e326aa8 100644 --- a/chrome/browser/ui/android/infobars/infobar_android.h +++ b/chrome/browser/ui/android/infobars/infobar_android.h
@@ -81,7 +81,4 @@ DISALLOW_COPY_AND_ASSIGN(InfoBarAndroid); }; -// Registers the NativeInfoBar's native methods through JNI. -bool RegisterNativeInfoBar(JNIEnv* env); - #endif // CHROME_BROWSER_UI_ANDROID_INFOBARS_INFOBAR_ANDROID_H_
diff --git a/chrome/browser/ui/android/infobars/infobar_container_android.cc b/chrome/browser/ui/android/infobars/infobar_container_android.cc index 71a733a..8d74a5e 100644 --- a/chrome/browser/ui/android/infobars/infobar_container_android.cc +++ b/chrome/browser/ui/android/infobars/infobar_container_android.cc
@@ -109,7 +109,3 @@ new InfoBarContainerAndroid(env, obj); return reinterpret_cast<intptr_t>(infobar_container); } - -bool RegisterInfoBarContainer(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/infobars/infobar_container_android.h b/chrome/browser/ui/android/infobars/infobar_container_android.h index f3178e2..f772f7b78 100644 --- a/chrome/browser/ui/android/infobars/infobar_container_android.h +++ b/chrome/browser/ui/android/infobars/infobar_container_android.h
@@ -52,7 +52,4 @@ DISALLOW_COPY_AND_ASSIGN(InfoBarContainerAndroid); }; -// Registers the InfoBarContainer's native methods through JNI. -bool RegisterInfoBarContainer(JNIEnv* env); - #endif // CHROME_BROWSER_UI_ANDROID_INFOBARS_INFOBAR_CONTAINER_ANDROID_H_
diff --git a/chrome/browser/ui/android/infobars/reader_mode_infobar.cc b/chrome/browser/ui/android/infobars/reader_mode_infobar.cc index facc5f9..c73aef3 100644 --- a/chrome/browser/ui/android/infobars/reader_mode_infobar.cc +++ b/chrome/browser/ui/android/infobars/reader_mode_infobar.cc
@@ -66,7 +66,3 @@ service->AddInfoBar(base::MakeUnique<ReaderModeInfoBar>( base::MakeUnique<ReaderModeInfoBarDelegate>())); } - -bool RegisterReaderModeInfoBar(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/infobars/reader_mode_infobar.h b/chrome/browser/ui/android/infobars/reader_mode_infobar.h index 430c7f9..96b85bb 100644 --- a/chrome/browser/ui/android/infobars/reader_mode_infobar.h +++ b/chrome/browser/ui/android/infobars/reader_mode_infobar.h
@@ -35,7 +35,4 @@ DISALLOW_COPY_AND_ASSIGN(ReaderModeInfoBar); }; -// Register native methods. -bool RegisterReaderModeInfoBar(JNIEnv* env); - #endif // CHROME_BROWSER_UI_ANDROID_INFOBARS_READER_MODE_INFOBAR_H_
diff --git a/chrome/browser/ui/android/infobars/simple_confirm_infobar_builder.cc b/chrome/browser/ui/android/infobars/simple_confirm_infobar_builder.cc index 26252bf56..ab6d383 100644 --- a/chrome/browser/ui/android/infobars/simple_confirm_infobar_builder.cc +++ b/chrome/browser/ui/android/infobars/simple_confirm_infobar_builder.cc
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/android/infobars/simple_confirm_infobar_builder.h" - #include <memory> #include "base/android/jni_android.h" @@ -164,7 +162,3 @@ j_listener, infobar_identifier, icon_bitmap, message_str, primary_str, secondary_str, auto_expire))); } - -bool RegisterSimpleConfirmInfoBarBuilder(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/infobars/simple_confirm_infobar_builder.h b/chrome/browser/ui/android/infobars/simple_confirm_infobar_builder.h deleted file mode 100644 index f001a5c..0000000 --- a/chrome/browser/ui/android/infobars/simple_confirm_infobar_builder.h +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_ANDROID_INFOBARS_SIMPLE_CONFIRM_INFOBAR_BUILDER_H_ -#define CHROME_BROWSER_UI_ANDROID_INFOBARS_SIMPLE_CONFIRM_INFOBAR_BUILDER_H_ - -#include "base/android/jni_android.h" - -// Registers native methods. -bool RegisterSimpleConfirmInfoBarBuilder(JNIEnv* env); - -#endif // CHROME_BROWSER_UI_ANDROID_INFOBARS_SIMPLE_CONFIRM_INFOBAR_BUILDER_H_
diff --git a/chrome/browser/ui/android/infobars/translate_compact_infobar.cc b/chrome/browser/ui/android/infobars/translate_compact_infobar.cc index 05ca5b6..9ff8fccd 100644 --- a/chrome/browser/ui/android/infobars/translate_compact_infobar.cc +++ b/chrome/browser/ui/android/infobars/translate_compact_infobar.cc
@@ -207,10 +207,3 @@ // Whether there is any affirmative action bit. return action_flags_ == FLAG_NONE; } - -// Native JNI methods --------------------------------------------------------- - -// static -bool RegisterTranslateCompactInfoBar(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/infobars/translate_compact_infobar.h b/chrome/browser/ui/android/infobars/translate_compact_infobar.h index 25d78ab..0beca80f 100644 --- a/chrome/browser/ui/android/infobars/translate_compact_infobar.h +++ b/chrome/browser/ui/android/infobars/translate_compact_infobar.h
@@ -93,7 +93,4 @@ DISALLOW_COPY_AND_ASSIGN(TranslateCompactInfoBar); }; -// Registers the native methods through JNI. -bool RegisterTranslateCompactInfoBar(JNIEnv* env); - #endif // CHROME_BROWSER_UI_ANDROID_INFOBARS_TRANSLATE_COMPACT_INFOBAR_H_
diff --git a/chrome/browser/ui/android/infobars/translate_infobar.cc b/chrome/browser/ui/android/infobars/translate_infobar.cc index ad43cd3d..c9146b7 100644 --- a/chrome/browser/ui/android/infobars/translate_infobar.cc +++ b/chrome/browser/ui/android/infobars/translate_infobar.cc
@@ -158,10 +158,3 @@ translate::TranslateInfoBarDelegate* TranslateInfoBar::GetDelegate() { return delegate()->AsTranslateInfoBarDelegate(); } - - -// Native JNI methods --------------------------------------------------------- - -bool RegisterTranslateInfoBarDelegate(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/infobars/translate_infobar.h b/chrome/browser/ui/android/infobars/translate_infobar.h index 6140e65..fb3e1ec 100644 --- a/chrome/browser/ui/android/infobars/translate_infobar.h +++ b/chrome/browser/ui/android/infobars/translate_infobar.h
@@ -47,8 +47,4 @@ DISALLOW_COPY_AND_ASSIGN(TranslateInfoBar); }; - -// Registers the native methods through JNI. -bool RegisterTranslateInfoBarDelegate(JNIEnv* env); - #endif // CHROME_BROWSER_UI_ANDROID_INFOBARS_TRANSLATE_INFOBAR_H_
diff --git a/chrome/browser/ui/android/javascript_app_modal_dialog_android.cc b/chrome/browser/ui/android/javascript_app_modal_dialog_android.cc index f3aeb72..255bef7 100644 --- a/chrome/browser/ui/android/javascript_app_modal_dialog_android.cc +++ b/chrome/browser/ui/android/javascript_app_modal_dialog_android.cc
@@ -162,12 +162,6 @@ return ScopedJavaLocalRef<jobject>(js_dialog->GetDialogObject()); } -// static -bool JavascriptAppModalDialogAndroid::RegisterJavascriptAppModalDialog( - JNIEnv* env) { - return RegisterNativesImpl(env); -} - JavascriptAppModalDialogAndroid::~JavascriptAppModalDialogAndroid() { // In case the dialog is still displaying, tell it to close itself. // This can happen if you trigger a dialog but close the Tab before it's
diff --git a/chrome/browser/ui/android/javascript_app_modal_dialog_android.h b/chrome/browser/ui/android/javascript_app_modal_dialog_android.h index b19f135..5cfcb86 100644 --- a/chrome/browser/ui/android/javascript_app_modal_dialog_android.h +++ b/chrome/browser/ui/android/javascript_app_modal_dialog_android.h
@@ -45,8 +45,6 @@ const base::android::ScopedJavaGlobalRef<jobject>& GetDialogObject() const; - static bool RegisterJavascriptAppModalDialog(JNIEnv* env); - private: // The object deletes itself. ~JavascriptAppModalDialogAndroid() override;
diff --git a/chrome/browser/ui/android/omnibox/omnibox_url_emphasizer.cc b/chrome/browser/ui/android/omnibox/omnibox_url_emphasizer.cc index edbcbb6..b55e4e5 100644 --- a/chrome/browser/ui/android/omnibox/omnibox_url_emphasizer.cc +++ b/chrome/browser/ui/android/omnibox/omnibox_url_emphasizer.cc
@@ -32,8 +32,3 @@ int emphasize_values[] = {scheme.begin, scheme.len, host.begin, host.len}; return base::android::ToJavaIntArray(env, emphasize_values, 4); } - -// static -bool OmniboxUrlEmphasizer::RegisterOmniboxUrlEmphasizer(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/omnibox/omnibox_url_emphasizer.h b/chrome/browser/ui/android/omnibox/omnibox_url_emphasizer.h index 127025bc..a76a0ca 100644 --- a/chrome/browser/ui/android/omnibox/omnibox_url_emphasizer.h +++ b/chrome/browser/ui/android/omnibox/omnibox_url_emphasizer.h
@@ -11,9 +11,6 @@ // Helper functions for the Omnibox URL emphasizer on Android. class OmniboxUrlEmphasizer { - public: - static bool RegisterOmniboxUrlEmphasizer(JNIEnv* env); - private: DISALLOW_IMPLICIT_CONSTRUCTORS(OmniboxUrlEmphasizer); };
diff --git a/chrome/browser/ui/android/omnibox/omnibox_view_util.cc b/chrome/browser/ui/android/omnibox/omnibox_view_util.cc index 22c00e5..d0fd7fc 100644 --- a/chrome/browser/ui/android/omnibox/omnibox_view_util.cc +++ b/chrome/browser/ui/android/omnibox/omnibox_view_util.cc
@@ -21,8 +21,3 @@ pasted_text = OmniboxView::SanitizeTextForPaste(pasted_text); return base::android::ConvertUTF16ToJavaString(env, pasted_text); } - -// static -bool OmniboxViewUtil::RegisterOmniboxViewUtil(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/omnibox/omnibox_view_util.h b/chrome/browser/ui/android/omnibox/omnibox_view_util.h index 2e42cec5..98895b94 100644 --- a/chrome/browser/ui/android/omnibox/omnibox_view_util.h +++ b/chrome/browser/ui/android/omnibox/omnibox_view_util.h
@@ -11,9 +11,6 @@ // Helper functions for the Omnibox view on Android. class OmniboxViewUtil { - public: - static bool RegisterOmniboxViewUtil(JNIEnv* env); - private: DISALLOW_IMPLICIT_CONSTRUCTORS(OmniboxViewUtil); };
diff --git a/chrome/browser/ui/android/page_info/certificate_chain_helper.cc b/chrome/browser/ui/android/page_info/certificate_chain_helper.cc index 8638fab..87f9c28 100644 --- a/chrome/browser/ui/android/page_info/certificate_chain_helper.cc +++ b/chrome/browser/ui/android/page_info/certificate_chain_helper.cc
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/android/page_info/certificate_chain_helper.h" - #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" @@ -50,8 +48,3 @@ return base::android::ToJavaArrayOfByteArray(env, cert_chain); } - -// static -bool RegisterCertificateChainHelper(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/page_info/certificate_chain_helper.h b/chrome/browser/ui/android/page_info/certificate_chain_helper.h deleted file mode 100644 index cfc3e87..0000000 --- a/chrome/browser/ui/android/page_info/certificate_chain_helper.h +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_ANDROID_PAGE_INFO_CERTIFICATE_CHAIN_HELPER_H_ -#define CHROME_BROWSER_UI_ANDROID_PAGE_INFO_CERTIFICATE_CHAIN_HELPER_H_ - -#include <jni.h> - -bool RegisterCertificateChainHelper(JNIEnv* env); - -#endif // CHROME_BROWSER_UI_ANDROID_PAGE_INFO_CERTIFICATE_CHAIN_HELPER_H_
diff --git a/chrome/browser/ui/android/page_info/certificate_viewer_android.cc b/chrome/browser/ui/android/page_info/certificate_viewer_android.cc index 1570a83..bd60a1b 100644 --- a/chrome/browser/ui/android/page_info/certificate_viewer_android.cc +++ b/chrome/browser/ui/android/page_info/certificate_viewer_android.cc
@@ -2,10 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/android/page_info/certificate_viewer_android.h" - #include "base/android/jni_string.h" #include "base/logging.h" +#include "chrome/browser/certificate_viewer.h" #include "chrome/grit/generated_resources.h" #include "jni/CertificateViewer_jni.h" #include "net/cert/x509_certificate.h" @@ -105,7 +104,3 @@ return ConvertUTF8ToJavaString( env, l10n_util::GetStringUTF8(IDS_CERT_INFO_SHA1_FINGERPRINT_LABEL)); } - -bool RegisterCertificateViewer(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/page_info/certificate_viewer_android.h b/chrome/browser/ui/android/page_info/certificate_viewer_android.h deleted file mode 100644 index 34f20b3..0000000 --- a/chrome/browser/ui/android/page_info/certificate_viewer_android.h +++ /dev/null
@@ -1,14 +0,0 @@ -// 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 CHROME_BROWSER_UI_ANDROID_PAGE_INFO_CERTIFICATE_VIEWER_ANDROID_H_ -#define CHROME_BROWSER_UI_ANDROID_PAGE_INFO_CERTIFICATE_VIEWER_ANDROID_H_ - -#include "chrome/browser/certificate_viewer.h" - -#include <jni.h> - -bool RegisterCertificateViewer(JNIEnv* env); - -#endif // CHROME_BROWSER_UI_ANDROID_PAGE_INFO_CERTIFICATE_VIEWER_ANDROID_H_
diff --git a/chrome/browser/ui/android/page_info/connection_info_popup_android.cc b/chrome/browser/ui/android/page_info/connection_info_popup_android.cc index 6ea9590..49bd7a5 100644 --- a/chrome/browser/ui/android/page_info/connection_info_popup_android.cc +++ b/chrome/browser/ui/android/page_info/connection_info_popup_android.cc
@@ -153,10 +153,3 @@ ChosenObjectInfoList chosen_object_info_list) { NOTIMPLEMENTED(); } - -// static -bool -ConnectionInfoPopupAndroid::RegisterConnectionInfoPopupAndroid( - JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/page_info/connection_info_popup_android.h b/chrome/browser/ui/android/page_info/connection_info_popup_android.h index d70c2c04..c99f75a 100644 --- a/chrome/browser/ui/android/page_info/connection_info_popup_android.h +++ b/chrome/browser/ui/android/page_info/connection_info_popup_android.h
@@ -40,8 +40,6 @@ ChosenObjectInfoList chosen_object_info_list) override; void SetIdentityInfo(const IdentityInfo& identity_info) override; - static bool RegisterConnectionInfoPopupAndroid(JNIEnv* env); - private: // The presenter that controls the Page Info UI. std::unique_ptr<PageInfo> presenter_;
diff --git a/chrome/browser/ui/android/page_info/page_info_popup_android.cc b/chrome/browser/ui/android/page_info/page_info_popup_android.cc index ace3406..be6e53a 100644 --- a/chrome/browser/ui/android/page_info/page_info_popup_android.cc +++ b/chrome/browser/ui/android/page_info/page_info_popup_android.cc
@@ -184,8 +184,3 @@ } return base::Optional<ContentSetting>(); } - -// static -bool PageInfoPopupAndroid::RegisterPageInfoPopupAndroid(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/page_info/page_info_popup_android.h b/chrome/browser/ui/android/page_info/page_info_popup_android.h index fe8000a1..21fc783 100644 --- a/chrome/browser/ui/android/page_info/page_info_popup_android.h +++ b/chrome/browser/ui/android/page_info/page_info_popup_android.h
@@ -49,8 +49,6 @@ ChosenObjectInfoList chosen_object_info_list) override; void SetIdentityInfo(const IdentityInfo& identity_info) override; - static bool RegisterPageInfoPopupAndroid(JNIEnv* env); - private: // Returns an optional value which is set if this permission should be // displayed in Page Info. Most permissions will only be displayed if they are
diff --git a/chrome/browser/ui/android/ssl_client_certificate_request.cc b/chrome/browser/ui/android/ssl_client_certificate_request.cc index 0886180..8e6f9893 100644 --- a/chrome/browser/ui/android/ssl_client_certificate_request.cc +++ b/chrome/browser/ui/android/ssl_client_certificate_request.cc
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/android/ssl_client_certificate_request.h" - #include <stddef.h> #include <utility> @@ -178,10 +176,6 @@ } } -bool RegisterSSLClientCertificateRequestAndroid(JNIEnv* env) { - return RegisterNativesImpl(env); -} - } // namespace android void ShowSSLClientCertificateSelector(
diff --git a/chrome/browser/ui/android/ssl_client_certificate_request.h b/chrome/browser/ui/android/ssl_client_certificate_request.h deleted file mode 100644 index a7296348..0000000 --- a/chrome/browser/ui/android/ssl_client_certificate_request.h +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright (c) 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 CHROME_BROWSER_UI_ANDROID_SSL_CLIENT_CERTIFICATE_REQUEST_H_ -#define CHROME_BROWSER_UI_ANDROID_SSL_CLIENT_CERTIFICATE_REQUEST_H_ - -#include <jni.h> - -namespace chrome { -namespace android { - -// Register JNI methods. -bool RegisterSSLClientCertificateRequestAndroid(JNIEnv* env); - -} // namespace android -} // namespace chrome - -#endif // CHROME_BROWSER_UI_ANDROID_SSL_CLIENT_CERTIFICATE_REQUEST_H_
diff --git a/chrome/browser/ui/android/tab_model/single_tab_model.cc b/chrome/browser/ui/android/tab_model/single_tab_model.cc index 567c949..b71a360 100644 --- a/chrome/browser/ui/android/tab_model/single_tab_model.cc +++ b/chrome/browser/ui/android/tab_model/single_tab_model.cc
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/android/tab_model/single_tab_model.h" - #include "base/android/jni_android.h" #include "chrome/browser/android/tab_android.h" #include "chrome/browser/android/webapps/single_tab_mode_tab_helper.h" @@ -28,8 +26,3 @@ SingleTabModeTabHelper::FromWebContents(web_contents); tab_helper->PermanentlyBlockAllNewWindows(); } - -// Register native methods -bool RegisterSingleTabModel(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/tab_model/single_tab_model.h b/chrome/browser/ui/android/tab_model/single_tab_model.h deleted file mode 100644 index 0e27825c..0000000 --- a/chrome/browser/ui/android/tab_model/single_tab_model.h +++ /dev/null
@@ -1,13 +0,0 @@ -// 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 CHROME_BROWSER_UI_ANDROID_TAB_MODEL_SINGLE_TAB_MODEL_H_ -#define CHROME_BROWSER_UI_ANDROID_TAB_MODEL_SINGLE_TAB_MODEL_H_ - -#include "base/android/jni_android.h" - -// Register native methods -bool RegisterSingleTabModel(JNIEnv* env); - -#endif // CHROME_BROWSER_UI_ANDROID_TAB_MODEL_SINGLE_TAB_MODEL_H_
diff --git a/chrome/browser/ui/android/tab_model/tab_model_jni_bridge.cc b/chrome/browser/ui/android/tab_model/tab_model_jni_bridge.cc index a7f15d0..fbe26ff 100644 --- a/chrome/browser/ui/android/tab_model/tab_model_jni_bridge.cc +++ b/chrome/browser/ui/android/tab_model/tab_model_jni_bridge.cc
@@ -210,10 +210,6 @@ TabModelList::RemoveTabModel(this); } -bool TabModelJniBridge::Register(JNIEnv* env) { - return RegisterNativesImpl(env); -} - static jlong Init(JNIEnv* env, const JavaParamRef<jobject>& obj, jboolean is_incognito,
diff --git a/chrome/browser/ui/android/tab_model/tab_model_jni_bridge.h b/chrome/browser/ui/android/tab_model/tab_model_jni_bridge.h index eaaf17e..a3bfa52d 100644 --- a/chrome/browser/ui/android/tab_model/tab_model_jni_bridge.h +++ b/chrome/browser/ui/android/tab_model/tab_model_jni_bridge.h
@@ -33,9 +33,6 @@ void Destroy(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); ~TabModelJniBridge() override; - // Registers the JNI bindings. - static bool Register(JNIEnv* env); - // Called by JNI base::android::ScopedJavaLocalRef<jobject> GetProfileAndroid( JNIEnv* env,
diff --git a/chrome/browser/ui/android/toolbar/toolbar_model_android.cc b/chrome/browser/ui/android/toolbar/toolbar_model_android.cc index 9368db5..b1513b1d 100644 --- a/chrome/browser/ui/android/toolbar/toolbar_model_android.cc +++ b/chrome/browser/ui/android/toolbar/toolbar_model_android.cc
@@ -45,11 +45,6 @@ } // static -bool ToolbarModelAndroid::RegisterToolbarModelAndroid(JNIEnv* env) { - return RegisterNativesImpl(env); -} - -// static jlong Init(JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jobject>& delegate) {
diff --git a/chrome/browser/ui/android/toolbar/toolbar_model_android.h b/chrome/browser/ui/android/toolbar/toolbar_model_android.h index 141cda0..761ad55 100644 --- a/chrome/browser/ui/android/toolbar/toolbar_model_android.h +++ b/chrome/browser/ui/android/toolbar/toolbar_model_android.h
@@ -32,8 +32,6 @@ // ChromeToolbarModelDelegate: content::WebContents* GetActiveWebContents() const override; - static bool RegisterToolbarModelAndroid(JNIEnv* env); - private: std::unique_ptr<ToolbarModel> toolbar_model_; JavaObjectWeakGlobalRef weak_java_delegate_;
diff --git a/chrome/browser/ui/android/usb_chooser_dialog_android.cc b/chrome/browser/ui/android/usb_chooser_dialog_android.cc index 3bf01d8..6cc5b32 100644 --- a/chrome/browser/ui/android/usb_chooser_dialog_android.cc +++ b/chrome/browser/ui/android/usb_chooser_dialog_android.cc
@@ -241,8 +241,3 @@ return true; } - -// static -bool UsbChooserDialogAndroid::Register(JNIEnv* env) { - return RegisterNativesImpl(env); -}
diff --git a/chrome/browser/ui/android/usb_chooser_dialog_android.h b/chrome/browser/ui/android/usb_chooser_dialog_android.h index 09cbcdb1..fa8a867 100644 --- a/chrome/browser/ui/android/usb_chooser_dialog_android.h +++ b/chrome/browser/ui/android/usb_chooser_dialog_android.h
@@ -49,8 +49,6 @@ void LoadUsbHelpPage(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); - static bool Register(JNIEnv* env); - private: void GotUsbDeviceList( const std::vector<scoped_refptr<device::UsbDevice>>& devices);
diff --git a/chrome/browser/vr/ui_scene_manager.cc b/chrome/browser/vr/ui_scene_manager.cc index cba3abbf..d5a9624 100644 --- a/chrome/browser/vr/ui_scene_manager.cc +++ b/chrome/browser/vr/ui_scene_manager.cc
@@ -102,7 +102,7 @@ static constexpr float kSplashScreenIconWidth = kSplashScreenIconDMM * kSplashScreenDistance; static constexpr float kSplashScreenIconVerticalOffset = - 0.2 * kSplashScreenDistance; + -0.1 * kSplashScreenDistance; static constexpr float kCloseButtonDistance = 2.4; static constexpr float kCloseButtonHeight = @@ -675,7 +675,8 @@ } void UiSceneManager::ConfigureSecurityWarnings() { - bool enabled = web_vr_mode_ && !secure_origin_; + bool enabled = + web_vr_mode_ && !secure_origin_ && !waiting_for_first_web_vr_frame_; permanent_security_warning_->SetEnabled(enabled); transient_security_warning_->SetEnabled(enabled); }
diff --git a/chrome/browser/vr/ui_scene_manager_unittest.cc b/chrome/browser/vr/ui_scene_manager_unittest.cc index c4518c6..676d71b3 100644 --- a/chrome/browser/vr/ui_scene_manager_unittest.cc +++ b/chrome/browser/vr/ui_scene_manager_unittest.cc
@@ -296,6 +296,28 @@ } } +TEST_F(UiSceneManagerTest, WebVrAutopresentedInsecureOrigin) { + base::ScopedMockTimeMessageLoopTaskRunner task_runner_; + + MakeAutoPresentedManager(); + manager_->SetWebVrSecureOrigin(false); + manager_->SetWebVrMode(true, false); + // Initially, the security warnings should not be visible since the first + // WebVR frame is not received. + VerifyElementsVisible("Initial", + std::set<UiElementDebugId>{kSplashScreenIcon}); + manager_->OnWebVrFrameAvailable(); + VerifyElementsVisible("Autopresented", std::set<UiElementDebugId>{ + kWebVrPermanentHttpSecurityWarning, + kWebVrTransientHttpSecurityWarning, + kTransientUrlBar}); + + // Make sure the transient elements go away. + task_runner_->FastForwardUntilNoTasksRemain(); + VerifyElementsVisible("End state", std::set<UiElementDebugId>{ + kWebVrPermanentHttpSecurityWarning}); +} + TEST_F(UiSceneManagerTest, WebVrAutopresented) { base::ScopedMockTimeMessageLoopTaskRunner task_runner_;
diff --git a/chrome/test/data/osdd_new/bogus.xml b/chrome/test/data/osdd_new/bogus.xml new file mode 100644 index 0000000..78c15cb --- /dev/null +++ b/chrome/test/data/osdd_new/bogus.xml
@@ -0,0 +1,7 @@ +<?xml version="1.0"?> +<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"> +<ShortName>Dictionary.com</ShortName> +<Description>Look it up at Dictionary.com</Description> +<Image height="16" width="16" type="image/x-icon">https://cache.lexico.com/g/d/favicon.ico</Image> +<Url type="text/html" method="get" template="bogus-url"/> +</OpenSearchDescription> \ No newline at end of file
diff --git a/chrome/test/data/osdd_new/dictionary.xml b/chrome/test/data/osdd_new/dictionary.xml new file mode 100644 index 0000000..962ce75 --- /dev/null +++ b/chrome/test/data/osdd_new/dictionary.xml
@@ -0,0 +1,7 @@ +<?xml version="1.0"?> +<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"> +<ShortName>Dictionary.com</ShortName> +<Description>Look it up at Dictionary.com</Description> +<Image height="16" width="16" type="image/x-icon">http://cache.lexico.com/g/d/favicon.ico</Image> +<Url type="text/html" method="get" template="http://dictionary.reference.com/browse/{searchTerms}?r=75"/> +</OpenSearchDescription> \ No newline at end of file
diff --git a/chrome/test/data/osdd_new/firefox_ebay.xml b/chrome/test/data/osdd_new/firefox_ebay.xml new file mode 100644 index 0000000..705f3f3 --- /dev/null +++ b/chrome/test/data/osdd_new/firefox_ebay.xml
@@ -0,0 +1,17 @@ +<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/"> +<ShortName>eBay</ShortName> +<Description>eBay - Online actions</Description> +<InputEncoding>ISO-8859-1</InputEncoding> +<Image width="16" height="16">data:image/x-icon;base64,R0lGODlhEAAQAMQAAAAAAMz/zMwAADMAzOfn1sxmAP///5kAZpnM////AACZM/777zPMAP+ZAP8AAP9mmf/MzMwAZjNmAADMM/+ZM/9mM//MMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAQUAP8ALAAAAAAQABAAAAVPoCGOZGmeaKqiQDkMYqAoBqMELpxUlVTfBohjeHjBLJLZZCF0GASOAWJQSFAUE1FTwIUNKoYKTQslGCLSb6MBFD2G3Zdo0k4tVvi8fl8KAQA7</Image> +<Url type="text/html" method="GET" template="http://search.ebay.com/search/search.dll"> + <Param name="query" value="{searchTerms}"/> + <Param name="MfcISAPICommand" value="GetResult"/> + <Param name="ht" value="1"/> + <Param name="ebaytag1" value="ebayreg"/> + <Param name="srchdesc" value="n"/> + <Param name="maxRecordsReturned" value="300"/> + <Param name="maxRecordsPerPage" value="50"/> + <Param name="SortProperty" value="MetaEndSort"/> +</Url> +<SearchForm>http://search.ebay.com/</SearchForm> +</SearchPlugin>
diff --git a/chrome/test/data/osdd_new/firefox_webster.xml b/chrome/test/data/osdd_new/firefox_webster.xml new file mode 100644 index 0000000..0f5c6e2 --- /dev/null +++ b/chrome/test/data/osdd_new/firefox_webster.xml
@@ -0,0 +1,9 @@ +<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/" xmlns:os="http://a9.com/-/spec/opensearch/1.1/"> +<os:ShortName>Webster</os:ShortName> +<os:Description>The Webster Dictionary</os:Description> +<os:InputEncoding>ISO-8859-1</os:InputEncoding> +<os:Image width="16" height="16">data:image/x-icon;base64,R0lGODlhEAAQAKIEAP////8AAAAA/7+/v////wAAAAAAAAAAACH5BAEAAAQALAAAAAAQABAAAANCSLrRsZCFQUeLaoLNbQxcyD3ZIJ4kCJjn9oCCMMQyTTcbPeuxpbYiXM3W670AxWEMkGIBmYwnFKIReTCNig9DdWASADs=</os:Image> +<SearchForm>http://www.webster.com/</SearchForm> +<os:Url type="text/html" method="GET" template="http://www.webster.com/cgi-bin/dictionary?sourceid=Mozilla-search&va={searchTerms}"> +</os:Url> +</SearchPlugin>
diff --git a/chrome/test/data/osdd_new/firefox_yahoo.xml b/chrome/test/data/osdd_new/firefox_yahoo.xml new file mode 100644 index 0000000..8ae1adb --- /dev/null +++ b/chrome/test/data/osdd_new/firefox_yahoo.xml
@@ -0,0 +1,17 @@ +<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/"> +<ShortName>Yahoo</ShortName> +<Description>Yahoo Search</Description> +<InputEncoding>UTF-8</InputEncoding> +<Image width="16" height="16">data:image/x-icon;base64,R0lGODlhEAAQAJECAP8AAAAAAP///wAAACH5BAEAAAIALAAAAAAQABAAAAIplI+py+0NogQuyBDEnEd2kHkfFWUamEzmpZSfmaIHPHrRguUm/fT+UwAAOw==</Image> +<Url type="application/x-suggestions+json" method="GET" + template="http://ff.search.yahoo.com/gossip"> + <Param name="output" value="fxjson"/> + <Param name="command" value="{searchTerms}"/> +</Url> +<Url type="text/html" method="GET" template="http://search.yahoo.com/search"> + <Param name="p" value="{searchTerms}"/> + <Param name="ei" value="UTF-8"/> + <MozParam name="fr" condition="pref" pref="yahoo-fr" /> +</Url> +<SearchForm>http://search.yahoo.com/</SearchForm> +</SearchPlugin>
diff --git a/chrome/test/data/osdd_new/https.xml b/chrome/test/data/osdd_new/https.xml new file mode 100644 index 0000000..7703249 --- /dev/null +++ b/chrome/test/data/osdd_new/https.xml
@@ -0,0 +1,7 @@ +<?xml version="1.0"?> +<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"> +<ShortName>Dictionary.com</ShortName> +<Description>Look it up at Dictionary.com</Description> +<Image height="16" width="16" type="image/x-icon">https://cache.lexico.com/g/d/favicon.ico</Image> +<Url type="text/html" method="get" template="https://dictionary.reference.com/browse/{searchTerms}?r=75"/> +</OpenSearchDescription> \ No newline at end of file
diff --git a/chrome/test/data/osdd_new/msdn.xml b/chrome/test/data/osdd_new/msdn.xml new file mode 100644 index 0000000..a13b4d4 --- /dev/null +++ b/chrome/test/data/osdd_new/msdn.xml
@@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"> + <ShortName>Search " MSDN</ShortName> + <Description>Search MSDN with Windows Live</Description> + <Tags>MSDN User</Tags> + <Contact>msdnfind@microsoft.com</Contact> + <Url type="text/html" template="http://search.msdn.microsoft.com/search/default.aspx?Query={searchTerms}&brand=msdn&locale=en-US"/> + <Url type="application/rss+xml" template="http://search.msdn.microsoft.com/search/default.aspx?Query={searchTerms}&brand=msdn&locale=en-US&feed=rss"/> + <Url type="application/atom+xml" template="http://search.msdn.microsoft.com/search/default.aspx?Query={searchTerms}&brand=msdn&locale=en-US&feed=atom"/> + <LongName>Search MSDN</LongName> + <Image height="16" width="16" type="image/vnd.microsoft.icon">http://search.msdn.microsoft.com/search/favicon.ico</Image> + <Query role="example" searchTerms="Console"/> + <Developer>Microsoft</Developer> + <Attribution>Search data &copy; 2007, Microsoft Corporation, All Rights Reserved</Attribution> + <SyndicationRight>open</SyndicationRight> + <AdultContent>false</AdultContent> + <Language>en-US</Language> + <OutputEncoding>UTF-8</OutputEncoding> + <InputEncoding>UTF-8</InputEncoding> +</OpenSearchDescription> \ No newline at end of file
diff --git a/chrome/test/data/osdd_new/post.xml b/chrome/test/data/osdd_new/post.xml new file mode 100644 index 0000000..1d65f6c --- /dev/null +++ b/chrome/test/data/osdd_new/post.xml
@@ -0,0 +1,17 @@ +<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/"> +<ShortName>Yahoo</ShortName> +<Description>Yahoo Search</Description> +<InputEncoding>UTF-8</InputEncoding> +<Image width="16" height="16">data:image/x-icon;base64,R0lGODlhEAAQAJECAP8AAAAAAP///wAAACH5BAEAAAIALAAAAAAQABAAAAIplI+py+0NogQuyBDEnEd2kHkfFWUamEzmpZSfmaIHPHrRguUm/fT+UwAAOw==</Image> +<Url type="application/x-suggestions+json" method="GET" + template="http://ff.search.yahoo.com/gossip"> + <Param name="output" value="fxjson"/> + <Param name="command" value="{searchTerms}"/> +</Url> +<Url type="text/html" method="POST" template="http://search.yahoo.com/search"> + <Param name="p" value="{searchTerms}"/> + <Param name="ei" value="UTF-8"/> + <MozParam name="fr" condition="pref" pref="yahoo-fr" /> +</Url> +<SearchForm>http://search.yahoo.com/</SearchForm> +</SearchPlugin>
diff --git a/chrome/test/data/osdd_new/post_suggestion.xml b/chrome/test/data/osdd_new/post_suggestion.xml new file mode 100644 index 0000000..24514970 --- /dev/null +++ b/chrome/test/data/osdd_new/post_suggestion.xml
@@ -0,0 +1,17 @@ +<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/"> +<ShortName>Yahoo</ShortName> +<Description>Yahoo Search</Description> +<InputEncoding>UTF-8</InputEncoding> +<Image width="16" height="16">data:image/x-icon;base64,R0lGODlhEAAQAJECAP8AAAAAAP///wAAACH5BAEAAAIALAAAAAAQABAAAAIplI+py+0NogQuyBDEnEd2kHkfFWUamEzmpZSfmaIHPHrRguUm/fT+UwAAOw==</Image> +<Url type="application/x-suggestions+json" method="POST" + template="http://ff.search.yahoo.com/gossip"> + <Param name="output" value="fxjson"/> + <Param name="command" value="{searchTerms}"/> +</Url> +<Url type="text/html" method="GET" template="http://search.yahoo.com/search"> + <Param name="p" value="{searchTerms}"/> + <Param name="ei" value="UTF-8"/> + <MozParam name="fr" condition="pref" pref="yahoo-fr" /> +</Url> +<SearchForm>http://search.yahoo.com/</SearchForm> +</SearchPlugin>
diff --git a/chrome/test/data/osdd_new/url_with_no_attributes.xml b/chrome/test/data/osdd_new/url_with_no_attributes.xml new file mode 100644 index 0000000..37b93e6 --- /dev/null +++ b/chrome/test/data/osdd_new/url_with_no_attributes.xml
@@ -0,0 +1,2 @@ +<?xml version="1.0" encoding="UTF-8"?> +<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"><ShortName>Search MIX Online</ShortName><Description>Search the content on MIX Online</Description><Url>http://visitmix.com/Search/?Term={searchTerms}</Url></OpenSearchDescription> \ No newline at end of file
diff --git a/chrome/test/data/osdd_new/wikipedia.xml b/chrome/test/data/osdd_new/wikipedia.xml new file mode 100644 index 0000000..39666631 --- /dev/null +++ b/chrome/test/data/osdd_new/wikipedia.xml
@@ -0,0 +1,11 @@ +<?xml version="1.0"?> +<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"> +<ShortName>Wikipedia (English)</ShortName> +<Description>Wikipedia (English)</Description> +<Image height="16" width="16" type="image/x-icon">http://en.wikipedia.org/favicon.ico</Image> +<Url type="text/html" method="get" template="http://en.wikipedia.org/w/index.php?title=Special:Search&search={searchTerms}"/> +<Url type="application/x-suggestions+json" method="GET" template="http://en.wikipedia.org/w/api.php?action=opensearch&search={searchTerms}"/> +<InputEncoding>UTF-8</InputEncoding> +<InputEncoding>Shift_JIS</InputEncoding> +<InputEncoding>!!!</InputEncoding> +</OpenSearchDescription> \ No newline at end of file
diff --git a/chromecast/BUILD.gn b/chromecast/BUILD.gn index 142cd8a..ac22671 100644 --- a/chromecast/BUILD.gn +++ b/chromecast/BUILD.gn
@@ -515,5 +515,7 @@ "//chromecast/android:libcast_shell_android", "//chromecast/browser/android:cast_shell_java", ] + + command_line_flags_file = "castshell-command-line" } }
diff --git a/components/BUILD.gn b/components/BUILD.gn index 8c0eb5c..93afa70 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -115,7 +115,6 @@ "//components/payments/core:unit_tests", "//components/physical_web/data_source:unit_tests", "//components/physical_web/eddystone:unit_tests", - "//components/precache/core:unit_tests", "//components/prefs:unit_tests", "//components/previews/core:unit_tests", "//components/proxy_config:unit_tests", @@ -211,7 +210,6 @@ "//components/payments/content/utility:unit_tests", "//components/policy/core/browser:unit_tests", "//components/policy/core/common:unit_tests", - "//components/precache/content:unit_tests", "//components/safe_browsing/common:unit_tests", "//components/safe_browsing/password_protection:password_protection_unittest", "//components/safe_browsing/triggers:unit_tests",
diff --git a/components/arc/net/arc_net_host_impl.cc b/components/arc/net/arc_net_host_impl.cc index 67776f9d..6a91cce9 100644 --- a/components/arc/net/arc_net_host_impl.cc +++ b/components/arc/net/arc_net_host_impl.cc
@@ -11,6 +11,7 @@ #include "base/bind.h" #include "base/location.h" #include "base/logging.h" +#include "base/memory/singleton.h" #include "base/posix/eintr_wrapper.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" @@ -24,6 +25,7 @@ #include "chromeos/network/network_util.h" #include "chromeos/network/onc/onc_utils.h" #include "components/arc/arc_bridge_service.h" +#include "components/arc/arc_browser_context_keyed_service_factory_base.h" #include "components/user_manager/user_manager.h" namespace { @@ -288,18 +290,52 @@ } // namespace namespace arc { +namespace { -ArcNetHostImpl::ArcNetHostImpl(ArcBridgeService* bridge_service) - : ArcService(bridge_service), binding_(this), weak_factory_(this) { - arc_bridge_service()->net()->AddObserver(this); +// Singleton factory for ArcNetHostImpl. +class ArcNetHostImplFactory + : public internal::ArcBrowserContextKeyedServiceFactoryBase< + ArcNetHostImpl, + ArcNetHostImplFactory> { + public: + // Factory name used by ArcBrowserContextKeyedServiceFactoryBase. + static constexpr const char* kName = "ArcNetHostImplFactory"; + + static ArcNetHostImplFactory* GetInstance() { + return base::Singleton<ArcNetHostImplFactory>::get(); + } + + private: + friend base::DefaultSingletonTraits<ArcNetHostImplFactory>; + ArcNetHostImplFactory() = default; + ~ArcNetHostImplFactory() override = default; +}; + +} // namespace + +// static +ArcNetHostImpl* ArcNetHostImpl::GetForBrowserContext( + content::BrowserContext* context) { + return ArcNetHostImplFactory::GetForBrowserContext(context); +} + +ArcNetHostImpl::ArcNetHostImpl(content::BrowserContext* context, + ArcBridgeService* bridge_service) + : arc_bridge_service_(bridge_service), binding_(this), weak_factory_(this) { + arc_bridge_service_->net()->AddObserver(this); } ArcNetHostImpl::~ArcNetHostImpl() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - arc_bridge_service()->net()->RemoveObserver(this); - if (observing_network_state_) { + if (observing_network_state_) GetStateHandler()->RemoveObserver(this, FROM_HERE); - } + + // TODO(hidehiko): Currently, the lifetime of ArcBridgeService and + // BrowserContextKeyedService is not nested. + // If ArcServiceManager::Get() returns nullptr, it is already destructed, + // so do not touch it. + if (ArcServiceManager::Get()) + arc_bridge_service_->net()->RemoveObserver(this); } void ArcNetHostImpl::OnInstanceReady() { @@ -308,7 +344,7 @@ mojom::NetHostPtr host; binding_.Bind(MakeRequest(&host)); auto* instance = - ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service()->net(), Init); + ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->net(), Init); DCHECK(instance); instance->Init(std::move(host)); @@ -589,7 +625,7 @@ void ArcNetHostImpl::ScanCompleted(const chromeos::DeviceState* /*unused*/) { auto* net_instance = - ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service()->net(), ScanCompleted); + ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->net(), ScanCompleted); if (!net_instance) return; @@ -617,7 +653,7 @@ void ArcNetHostImpl::DefaultNetworkSuccessCallback( const std::string& service_path, const base::DictionaryValue& dictionary) { - auto* net_instance = ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service()->net(), + auto* net_instance = ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->net(), DefaultNetworkChanged); if (!net_instance) return; @@ -630,8 +666,8 @@ const chromeos::NetworkState* network) { if (!network) { VLOG(1) << "No default network"; - auto* net_instance = ARC_GET_INSTANCE_FOR_METHOD( - arc_bridge_service()->net(), DefaultNetworkChanged); + auto* net_instance = ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->net(), + DefaultNetworkChanged); if (net_instance) net_instance->DefaultNetworkChanged(nullptr, nullptr); return; @@ -647,7 +683,7 @@ } void ArcNetHostImpl::DeviceListChanged() { - auto* net_instance = ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service()->net(), + auto* net_instance = ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->net(), WifiEnabledStateChanged); if (!net_instance) return;
diff --git a/components/arc/net/arc_net_host_impl.h b/components/arc/net/arc_net_host_impl.h index d047c27..83bd473 100644 --- a/components/arc/net/arc_net_host_impl.h +++ b/components/arc/net/arc_net_host_impl.h
@@ -15,29 +15,36 @@ #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "chromeos/network/network_state_handler_observer.h" -#include "components/arc/arc_service.h" #include "components/arc/common/net.mojom.h" #include "components/arc/instance_holder.h" +#include "components/keyed_service/core/keyed_service.h" #include "mojo/public/cpp/bindings/binding.h" namespace base { - class DictionaryValue; - } // namespace base +namespace content { +class BrowserContext; +} // namespace content + namespace arc { class ArcBridgeService; // Private implementation of ArcNetHost. -class ArcNetHostImpl : public ArcService, +class ArcNetHostImpl : public KeyedService, public InstanceHolder<mojom::NetInstance>::Observer, public chromeos::NetworkStateHandlerObserver, public mojom::NetHost { public: + // Returns singleton instance for the given BrowserContext, + // or nullptr if the browser |context| is not allowed to use ARC. + static ArcNetHostImpl* GetForBrowserContext(content::BrowserContext* context); + // The constructor will register an Observer with ArcBridgeService. - explicit ArcNetHostImpl(ArcBridgeService* arc_bridge_service); + ArcNetHostImpl(content::BrowserContext* context, + ArcBridgeService* arc_bridge_service); ~ArcNetHostImpl() override; // ARC -> Chrome calls: @@ -104,6 +111,8 @@ const std::string& error_name, std::unique_ptr<base::DictionaryValue> error_data); + ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager. + // True if the chrome::NetworkStateHandler is currently being observed for // state changes. bool observing_network_state_ = false;
diff --git a/components/autofill/content/browser/content_autofill_driver.cc b/components/autofill/content/browser/content_autofill_driver.cc index 66b1c7fe..0d37b7c 100644 --- a/components/autofill/content/browser/content_autofill_driver.cc +++ b/components/autofill/content/browser/content_autofill_driver.cc
@@ -44,6 +44,7 @@ if (provider) { autofill_handler_ = base::MakeUnique<AutofillHandlerProxy>(this, provider); GetAutofillAgent()->SetUserGestureRequired(false); + GetAutofillAgent()->SetSecureContextRequired(true); } else { autofill_handler_ = base::MakeUnique<AutofillManager>( this, client, app_locale, enable_download_manager);
diff --git a/components/autofill/content/browser/content_autofill_driver_unittest.cc b/components/autofill/content/browser/content_autofill_driver_unittest.cc index b9532df7..3ae21b4 100644 --- a/components/autofill/content/browser/content_autofill_driver_unittest.cc +++ b/components/autofill/content/browser/content_autofill_driver_unittest.cc
@@ -203,6 +203,8 @@ void SetUserGestureRequired(bool required) override {} + void SetSecureContextRequired(bool required) override {} + mojo::BindingSet<mojom::AutofillAgent> bindings_; base::Closure quit_closure_;
diff --git a/components/autofill/content/common/autofill_agent.mojom b/components/autofill/content/common/autofill_agent.mojom index c513c3a7..9dd9fa99 100644 --- a/components/autofill/content/common/autofill_agent.mojom +++ b/components/autofill/content/common/autofill_agent.mojom
@@ -60,6 +60,10 @@ // autofill service with the user's consent, so the gesture check is // redundant there anyway. SetUserGestureRequired(bool required); + + // Configures the render to require, or not, the secure context to query + // autofill suggestion, the default is false. + SetSecureContextRequired(bool required); }; // There is one instance of this interface per render frame in the render
diff --git a/components/autofill/content/renderer/autofill_agent.cc b/components/autofill/content/renderer/autofill_agent.cc index 0101670..2af1273 100644 --- a/components/autofill/content/renderer/autofill_agent.cc +++ b/components/autofill/content/renderer/autofill_agent.cc
@@ -37,6 +37,7 @@ #include "components/autofill/core/common/password_form_fill_data.h" #include "components/autofill/core/common/save_password_progress_logger.h" #include "content/public/common/content_switches.h" +#include "content/public/common/origin_util.h" #include "content/public/common/url_constants.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" @@ -153,6 +154,7 @@ is_popup_possibly_visible_(false), is_generation_popup_possibly_visible_(false), is_user_gesture_required_(true), + is_secure_context_required_(false), page_click_tracker_(new PageClickTracker(render_frame, this)), binding_(this), weak_ptr_factory_(this) { @@ -671,6 +673,10 @@ QueryAutofillSuggestions(element); } +void AutofillAgent::SetSecureContextRequired(bool required) { + is_secure_context_required_ = required; +} + void AutofillAgent::QueryAutofillSuggestions( const WebFormControlElement& element) { if (!element.GetDocument().GetFrame()) @@ -691,6 +697,15 @@ &field); } + if (is_secure_context_required_ && + !(element.GetDocument().IsSecureContext() && + content::IsOriginSecure(form.action))) { + LOG(WARNING) << "Autofill suggestions are disabled because the document " + "isn't a secure context or the form's action attribute " + "isn't secure."; + return; + } + std::vector<base::string16> data_list_values; std::vector<base::string16> data_list_labels; const WebInputElement* input_element = ToWebInputElement(&element);
diff --git a/components/autofill/content/renderer/autofill_agent.h b/components/autofill/content/renderer/autofill_agent.h index 585e90a..55a083b3 100644 --- a/components/autofill/content/renderer/autofill_agent.h +++ b/components/autofill/content/renderer/autofill_agent.h
@@ -84,6 +84,7 @@ int32_t key, const PasswordFormFillData& form_data) override; void SetUserGestureRequired(bool required) override; + void SetSecureContextRequired(bool required) override; void ShowNotSecureWarning(const blink::WebInputElement& element); @@ -283,6 +284,10 @@ // field change. Default to true. bool is_user_gesture_required_; + // Whether or not the secure context is required to query autofill suggestion. + // Default to false. + bool is_secure_context_required_; + std::unique_ptr<PageClickTracker> page_click_tracker_; mojo::Binding<mojom::AutofillAgent> binding_;
diff --git a/components/ntp_snippets/breaking_news/subscription_manager.cc b/components/ntp_snippets/breaking_news/subscription_manager.cc index f9077a7..2a10fc45 100644 --- a/components/ntp_snippets/breaking_news/subscription_manager.cc +++ b/components/ntp_snippets/breaking_news/subscription_manager.cc
@@ -15,6 +15,7 @@ #include "components/prefs/pref_service.h" #include "components/signin/core/browser/access_token_fetcher.h" #include "components/signin/core/browser/signin_manager_base.h" +#include "net/base/url_util.h" namespace ntp_snippets { @@ -28,6 +29,7 @@ // Variation parameter for chrome-push-unsubscription backend. const char kPushUnsubscriptionBackendParam[] = "push_unsubscription_backend"; +const char kApiKeyParamName[] = "key"; const char kAuthorizationRequestHeaderFormat[] = "Bearer %s"; } // namespace @@ -64,6 +66,7 @@ PrefService* pref_service, SigninManagerBase* signin_manager, OAuth2TokenService* access_token_service, + const std::string& api_key, const GURL& subscribe_url, const GURL& unsubscribe_url) : url_request_context_getter_(std::move(url_request_context_getter)), @@ -74,6 +77,7 @@ base::Bind(&SubscriptionManager::SigninStatusChanged, base::Unretained(this)))), access_token_service_(access_token_service), + api_key_(api_key), subscribe_url_(subscribe_url), unsubscribe_url_(unsubscribe_url) {} @@ -96,11 +100,16 @@ const std::string& access_token) { SubscriptionJsonRequest::Builder builder; builder.SetToken(subscription_token) - .SetUrlRequestContextGetter(url_request_context_getter_) - .SetUrl(subscribe_url_); + .SetUrlRequestContextGetter(url_request_context_getter_); + if (!access_token.empty()) { + builder.SetUrl(subscribe_url_); builder.SetAuthenticationHeader(base::StringPrintf( kAuthorizationRequestHeaderFormat, access_token.c_str())); + } else { + // When not providing OAuth token, we need to pass the Google API key. + builder.SetUrl( + net::AppendQueryParameter(subscribe_url_, kApiKeyParamName, api_key_)); } request_ = builder.Build(); @@ -180,9 +189,10 @@ } SubscriptionJsonRequest::Builder builder; - builder.SetToken(old_token) - .SetUrlRequestContextGetter(url_request_context_getter_) - .SetUrl(unsubscribe_url_); + builder.SetToken(old_token).SetUrlRequestContextGetter( + url_request_context_getter_); + builder.SetUrl( + net::AppendQueryParameter(unsubscribe_url_, kApiKeyParamName, api_key_)); request_ = builder.Build(); request_->Start(base::BindOnce(&SubscriptionManager::DidUnsubscribe,
diff --git a/components/ntp_snippets/breaking_news/subscription_manager.h b/components/ntp_snippets/breaking_news/subscription_manager.h index ba5a3b3..f04bb14 100644 --- a/components/ntp_snippets/breaking_news/subscription_manager.h +++ b/components/ntp_snippets/breaking_news/subscription_manager.h
@@ -39,6 +39,7 @@ PrefService* pref_service, SigninManagerBase* signin_manager, OAuth2TokenService* access_token_service, + const std::string& api_key, const GURL& subscribe_url, const GURL& unsubscribe_url); @@ -94,6 +95,9 @@ std::unique_ptr<SigninObserver> signin_observer_; OAuth2TokenService* access_token_service_; + // API key to use for non-authenticated requests. + const std::string api_key_; + // API endpoint for subscribing and unsubscribing. const GURL subscribe_url_; const GURL unsubscribe_url_;
diff --git a/components/ntp_snippets/breaking_news/subscription_manager_unittest.cc b/components/ntp_snippets/breaking_news/subscription_manager_unittest.cc index ad222d5..468988f 100644 --- a/components/ntp_snippets/breaking_news/subscription_manager_unittest.cc +++ b/components/ntp_snippets/breaking_news/subscription_manager_unittest.cc
@@ -20,8 +20,16 @@ namespace ntp_snippets { const char kTestEmail[] = "test@email.com"; +const char kAPIKey[] = "fakeAPIkey"; const char kSubscriptionUrl[] = "http://valid-url.test/subscribe"; +const char kSubscriptionUrlSignedIn[] = "http://valid-url.test/subscribe"; +; +const char kSubscriptionUrlSignedOut[] = + "http://valid-url.test/subscribe?key=fakeAPIkey"; const char kUnsubscriptionUrl[] = "http://valid-url.test/unsubscribe"; +const char kUnsubscriptionUrlSignedIn[] = "http://valid-url.test/unsubscribe"; +const char kUnsubscriptionUrlSignedOut[] = + "http://valid-url.test/unsubscribe?key=fakeAPIkey"; class SubscriptionManagerTest : public testing::Test { public: @@ -54,27 +62,47 @@ return url_fetcher; } - void RespondToSubscriptionRequestSuccessfully() { + void RespondToSubscriptionRequestSuccessfully(bool is_signed_in) { net::TestURLFetcher* url_fetcher = GetRunningFetcher(); - ASSERT_EQ(GURL(kSubscriptionUrl), url_fetcher->GetOriginalURL()); + if (is_signed_in) { + ASSERT_EQ(GURL(kSubscriptionUrlSignedIn), url_fetcher->GetOriginalURL()); + } else { + ASSERT_EQ(GURL(kSubscriptionUrlSignedOut), url_fetcher->GetOriginalURL()); + } RespondSuccessfully(); } - void RespondToUnsubscriptionRequestSuccessfully() { + void RespondToUnsubscriptionRequestSuccessfully(bool is_signed_in) { net::TestURLFetcher* url_fetcher = GetRunningFetcher(); - ASSERT_EQ(GURL(kUnsubscriptionUrl), url_fetcher->GetOriginalURL()); + if (is_signed_in) { + ASSERT_EQ(GURL(kUnsubscriptionUrlSignedIn), + url_fetcher->GetOriginalURL()); + } else { + ASSERT_EQ(GURL(kUnsubscriptionUrlSignedOut), + url_fetcher->GetOriginalURL()); + } RespondSuccessfully(); } - void RespondToSubscriptionWithError(int error_code) { + void RespondToSubscriptionWithError(bool is_signed_in, int error_code) { net::TestURLFetcher* url_fetcher = GetRunningFetcher(); - ASSERT_EQ(GURL(kSubscriptionUrl), url_fetcher->GetOriginalURL()); + if (is_signed_in) { + ASSERT_EQ(GURL(kSubscriptionUrlSignedIn), url_fetcher->GetOriginalURL()); + } else { + ASSERT_EQ(GURL(kSubscriptionUrlSignedOut), url_fetcher->GetOriginalURL()); + } RespondWithError(error_code); } - void RespondToUnsubscriptionWithError(int error_code) { + void RespondToUnsubscriptionWithError(bool is_signed_in, int error_code) { net::TestURLFetcher* url_fetcher = GetRunningFetcher(); - ASSERT_EQ(GURL(kUnsubscriptionUrl), url_fetcher->GetOriginalURL()); + if (is_signed_in) { + ASSERT_EQ(GURL(kUnsubscriptionUrlSignedIn), + url_fetcher->GetOriginalURL()); + } else { + ASSERT_EQ(GURL(kUnsubscriptionUrlSignedOut), + url_fetcher->GetOriginalURL()); + } RespondWithError(error_code); } @@ -124,9 +152,10 @@ std::string subscription_token = "1234567890"; SubscriptionManager manager(GetRequestContext(), GetPrefService(), GetSigninManager(), GetOAuth2TokenService(), - GURL(kSubscriptionUrl), GURL(kUnsubscriptionUrl)); + kAPIKey, GURL(kSubscriptionUrl), + GURL(kUnsubscriptionUrl)); manager.Subscribe(subscription_token); - RespondToSubscriptionRequestSuccessfully(); + RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/false); ASSERT_TRUE(manager.IsSubscribed()); EXPECT_EQ(subscription_token, GetPrefService()->GetString( prefs::kBreakingNewsSubscriptionDataToken)); @@ -147,7 +176,7 @@ // Create manager and subscribe. std::string subscription_token = "1234567890"; SubscriptionManager manager(GetRequestContext(), GetPrefService(), - GetSigninManager(), auth_token_service, + GetSigninManager(), auth_token_service, kAPIKey, GURL(kSubscriptionUrl), GURL(kUnsubscriptionUrl)); manager.Subscribe(subscription_token); @@ -158,7 +187,7 @@ // Issue the access token and respond to the subscription request. IssueAccessToken(auth_token_service); ASSERT_FALSE(manager.IsSubscribed()); - RespondToSubscriptionRequestSuccessfully(); + RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/true); ASSERT_TRUE(manager.IsSubscribed()); // Check that we are now subscribed correctly with authentication. @@ -173,10 +202,11 @@ std::string subscription_token = "1234567890"; SubscriptionManager manager(GetRequestContext(), GetPrefService(), GetSigninManager(), GetOAuth2TokenService(), - GURL(kSubscriptionUrl), GURL(kUnsubscriptionUrl)); + kAPIKey, GURL(kSubscriptionUrl), + GURL(kUnsubscriptionUrl)); manager.Subscribe(subscription_token); - RespondToSubscriptionWithError(net::ERR_TIMED_OUT); + RespondToSubscriptionWithError(/*is_signed_in=*/false, net::ERR_TIMED_OUT); EXPECT_FALSE(manager.IsSubscribed()); } @@ -184,12 +214,13 @@ std::string subscription_token = "1234567890"; SubscriptionManager manager(GetRequestContext(), GetPrefService(), GetSigninManager(), GetOAuth2TokenService(), - GURL(kSubscriptionUrl), GURL(kUnsubscriptionUrl)); + kAPIKey, GURL(kSubscriptionUrl), + GURL(kUnsubscriptionUrl)); manager.Subscribe(subscription_token); - RespondToSubscriptionRequestSuccessfully(); + RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/false); ASSERT_TRUE(manager.IsSubscribed()); manager.Unsubscribe(); - RespondToUnsubscriptionRequestSuccessfully(); + RespondToUnsubscriptionRequestSuccessfully(/*is_signed_in=*/false); EXPECT_FALSE(manager.IsSubscribed()); EXPECT_FALSE( GetPrefService()->HasPrefPath(prefs::kBreakingNewsSubscriptionDataToken)); @@ -200,12 +231,13 @@ std::string subscription_token = "1234567890"; SubscriptionManager manager(GetRequestContext(), GetPrefService(), GetSigninManager(), GetOAuth2TokenService(), - GURL(kSubscriptionUrl), GURL(kUnsubscriptionUrl)); + kAPIKey, GURL(kSubscriptionUrl), + GURL(kUnsubscriptionUrl)); manager.Subscribe(subscription_token); - RespondToSubscriptionRequestSuccessfully(); + RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/false); ASSERT_TRUE(manager.IsSubscribed()); manager.Unsubscribe(); - RespondToUnsubscriptionWithError(net::ERR_TIMED_OUT); + RespondToUnsubscriptionWithError(/*is_signed_in=*/false, net::ERR_TIMED_OUT); ASSERT_TRUE(manager.IsSubscribed()); EXPECT_EQ(subscription_token, GetPrefService()->GetString( prefs::kBreakingNewsSubscriptionDataToken)); @@ -219,10 +251,10 @@ FakeProfileOAuth2TokenService* auth_token_service = GetOAuth2TokenService(); std::string subscription_token = "1234567890"; SubscriptionManager manager(GetRequestContext(), GetPrefService(), - GetSigninManager(), auth_token_service, + GetSigninManager(), auth_token_service, kAPIKey, GURL(kSubscriptionUrl), GURL(kUnsubscriptionUrl)); manager.Subscribe(subscription_token); - RespondToSubscriptionRequestSuccessfully(); + RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/false); ASSERT_FALSE(manager.NeedsToResubscribe()); // Sign in. This should trigger a resubscribe. @@ -231,7 +263,7 @@ ASSERT_TRUE(manager.NeedsToResubscribe()); ASSERT_EQ(1u, auth_token_service->GetPendingRequests().size()); IssueAccessToken(auth_token_service); - RespondToSubscriptionRequestSuccessfully(); + RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/true); // Check that we are now subscribed with authentication. EXPECT_TRUE(GetPrefService()->GetBoolean( @@ -249,17 +281,17 @@ IssueRefreshToken(auth_token_service); std::string subscription_token = "1234567890"; SubscriptionManager manager(GetRequestContext(), GetPrefService(), - GetSigninManager(), auth_token_service, + GetSigninManager(), auth_token_service, kAPIKey, GURL(kSubscriptionUrl), GURL(kUnsubscriptionUrl)); manager.Subscribe(subscription_token); ASSERT_EQ(1u, auth_token_service->GetPendingRequests().size()); IssueAccessToken(auth_token_service); - RespondToSubscriptionRequestSuccessfully(); + RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/true); // Signout, this should trigger a resubscribe. SignOut(); EXPECT_TRUE(manager.NeedsToResubscribe()); - RespondToSubscriptionRequestSuccessfully(); + RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/false); // Check that we are now subscribed without authentication. EXPECT_FALSE(GetPrefService()->GetBoolean( @@ -273,9 +305,10 @@ std::string old_subscription_token = "1234567890"; SubscriptionManager manager(GetRequestContext(), GetPrefService(), GetSigninManager(), GetOAuth2TokenService(), - GURL(kSubscriptionUrl), GURL(kUnsubscriptionUrl)); + kAPIKey, GURL(kSubscriptionUrl), + GURL(kUnsubscriptionUrl)); manager.Subscribe(old_subscription_token); - RespondToSubscriptionRequestSuccessfully(); + RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/false); EXPECT_EQ( old_subscription_token, GetPrefService()->GetString(prefs::kBreakingNewsSubscriptionDataToken)); @@ -285,8 +318,8 @@ manager.Resubscribe(new_subscription_token); // Resubscribe with a new token should issue an unsubscribe request before // subscribing. - RespondToUnsubscriptionRequestSuccessfully(); - RespondToSubscriptionRequestSuccessfully(); + RespondToUnsubscriptionRequestSuccessfully(/*is_signed_in=*/false); + RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/false); // Check we are now subscribed with the new token. EXPECT_EQ(
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_utils.cc b/components/password_manager/core/browser/android_affiliation/affiliation_utils.cc index bd69920..ce491749 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_utils.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_utils.cc
@@ -10,7 +10,6 @@ #include "base/base64.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" -#include "components/autofill/core/common/password_form.h" #include "components/url_formatter/elide_url.h" #include "components/variations/variations_associated_data.h" #include "net/base/escape.h" @@ -196,7 +195,7 @@ [](const Facet& facet) { return facet.uri; }); std::sort(uris.begin(), uris.end()); return uris; -}; +} } // namespace @@ -317,20 +316,4 @@ return facet.IsValidAndroidFacetURI(); } -std::string GetHumanReadableOrigin( - const autofill::PasswordForm& password_form) { - FacetURI facet_uri = - FacetURI::FromPotentiallyInvalidSpec(password_form.signon_realm); - if (facet_uri.IsValidAndroidFacetURI()) - return GetHumanReadableOriginForAndroidUri(facet_uri); - - return base::UTF16ToUTF8( - url_formatter::FormatUrlForSecurityDisplay(password_form.origin)); -} - -std::string GetHumanReadableOriginForAndroidUri(const FacetURI facet_uri) { - DCHECK(facet_uri.IsValidAndroidFacetURI()); - return facet_uri.scheme() + "://" + facet_uri.android_package_name(); -} - } // namespace password_manager
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_utils.h b/components/password_manager/core/browser/android_affiliation/affiliation_utils.h index 187288d..392bfe5 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_utils.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_utils.h
@@ -56,10 +56,6 @@ #include "url/gurl.h" #include "url/third_party/mozilla/url_parse.h" -namespace autofill { -struct PasswordForm; -} // namespace autofill - namespace password_manager { // Encapsulates a facet URI in canonical form. @@ -204,13 +200,6 @@ // A shorter way to spell FacetURI::IsValidAndroidFacetURI(). bool IsValidAndroidFacetURI(const std::string& uri); -// Returns the origin URI in a format which can be presented to a user based of -// |password_from| field values. -std::string GetHumanReadableOrigin(const autofill::PasswordForm& password_form); - -// Returns the Android origin URI for presenting to a user. -std::string GetHumanReadableOriginForAndroidUri(const FacetURI facet_uri); - // For logging use only. std::ostream& operator<<(std::ostream& os, const FacetURI& facet_uri);
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_utils_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliation_utils_unittest.cc index cc36bcfd..5cd22af 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_utils_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_utils_unittest.cc
@@ -15,7 +15,6 @@ namespace password_manager { namespace { -const std::string kSchemeHostExample = "http://example.com"; const char kTestFacetURI1[] = "https://alpha.example.com/"; const char kTestFacetURI2[] = "https://beta.example.com/"; const char kTestFacetURI3[] = "https://gamma.example.com/"; @@ -240,50 +239,4 @@ EXPECT_FALSE(AreEquivalenceClassesEqual(c, b)); } -class GetHumanReadableOriginTest : public testing::Test { - public: - GetHumanReadableOriginTest() { - form_template_.origin = GURL(kSchemeHostExample); - form_template_.action = GURL(kSchemeHostExample); - form_template_.username_element = base::ASCIIToUTF16("Email"); - form_template_.password_element = base::ASCIIToUTF16("Password"); - form_template_.submit_element = base::ASCIIToUTF16("signIn"); - form_template_.signon_realm = kSchemeHostExample; - } - const autofill::PasswordForm& form_remplate() { return form_template_; } - - private: - autofill::PasswordForm form_template_; -}; - -TEST_F(GetHumanReadableOriginTest, OriginFromHtmlForm) { - autofill::PasswordForm html_form(form_remplate()); - html_form.origin = GURL(kSchemeHostExample + "/LoginAuth"); - html_form.action = GURL(kSchemeHostExample + "/Login"); - html_form.scheme = autofill::PasswordForm::SCHEME_HTML; - EXPECT_EQ(GetHumanReadableOrigin(html_form), "http://example.com"); -} - -TEST_F(GetHumanReadableOriginTest, OriginFromDigestForm) { - autofill::PasswordForm non_html_form(form_remplate()); - non_html_form.scheme = autofill::PasswordForm::SCHEME_DIGEST; - non_html_form.action = GURL(); - non_html_form.signon_realm = kSchemeHostExample + "42"; - EXPECT_EQ(GetHumanReadableOrigin(non_html_form), "http://example.com"); -} - -TEST_F(GetHumanReadableOriginTest, OriginFromAndroidForm) { - autofill::PasswordForm android_form(form_remplate()); - android_form.action = GURL(); - android_form.origin = GURL(); - android_form.scheme = autofill::PasswordForm::SCHEME_OTHER; - android_form.signon_realm = - "android://" - "m3HSJL1i83hdltRq0-o9czGb-8KJDKra4t_" - "3JRlnPKcjI8PZm6XBHXx6zG4UuMXaDEZjR1wuXDre9G9zvN7AQw==" - "@com.example.android"; - EXPECT_EQ(GetHumanReadableOrigin(android_form), - "android://com.example.android"); -} - } // namespace password_manager
diff --git a/components/payments/content/payment_request.cc b/components/payments/content/payment_request.cc index cf0c0718..e9198fba 100644 --- a/components/payments/content/payment_request.cc +++ b/components/payments/content/payment_request.cc
@@ -36,14 +36,15 @@ observer_for_testing_(observer_for_testing), journey_logger_(delegate_->IsIncognito(), web_contents_->GetLastCommittedURL(), - delegate_->GetUkmRecorder()) { + delegate_->GetUkmRecorder()), + weak_ptr_factory_(this) { // OnConnectionTerminated will be called when the Mojo pipe is closed. This // will happen as a result of many renderer-side events (both successful and // erroneous in nature). // TODO(crbug.com/683636): Investigate using // set_connection_error_with_reason_handler with Binding::CloseWithReason. binding_.set_connection_error_handler(base::Bind( - &PaymentRequest::OnConnectionTerminated, base::Unretained(this))); + &PaymentRequest::OnConnectionTerminated, weak_ptr_factory_.GetWeakPtr())); } PaymentRequest::~PaymentRequest() {}
diff --git a/components/payments/content/payment_request.h b/components/payments/content/payment_request.h index ff8c2474..d4145f8 100644 --- a/components/payments/content/payment_request.h +++ b/components/payments/content/payment_request.h
@@ -9,6 +9,7 @@ #include <vector> #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "components/payments/content/payment_request_spec.h" #include "components/payments/content/payment_request_state.h" #include "components/payments/core/journey_logger.h" @@ -126,6 +127,8 @@ // Whether a completion was already recorded for this Payment Request. bool has_recorded_completion_ = false; + base::WeakPtrFactory<PaymentRequest> weak_ptr_factory_; + DISALLOW_COPY_AND_ASSIGN(PaymentRequest); };
diff --git a/components/precache/DEPS b/components/precache/DEPS deleted file mode 100644 index 975943c..0000000 --- a/components/precache/DEPS +++ /dev/null
@@ -1,11 +0,0 @@ -include_rules = [ - # Precache is a layered component; subdirectories must introduce the ability - # to use the content layer explicitly as appropriate. - # http://www.chromium.org/developers/design-documents/layered-components-design - "+components/data_use_measurement/core", - "-components/precache", - "+components/precache/core", - - "+components/history/core/browser", - "+components/prefs", -]
diff --git a/components/precache/OWNERS b/components/precache/OWNERS deleted file mode 100644 index 1bec579..0000000 --- a/components/precache/OWNERS +++ /dev/null
@@ -1,8 +0,0 @@ -lizeb@chromium.org -pasko@chromium.org -twifkak@chromium.org - -# Emeritus: -bengr@chromium.org -rajendrant@chromium.org -sclittle@chromium.org
diff --git a/components/precache/README b/components/precache/README deleted file mode 100644 index 438ab7b..0000000 --- a/components/precache/README +++ /dev/null
@@ -1,11 +0,0 @@ -The precache component contains code for an experimental prototype to -proactively load Web resources into the network stack's disk cache. - -To enable this feature use the command line flag --enable-precache. - -Precache is a layered component. See: -http://www.chromium.org/developers/design-documents/layered-components-design - -Folder structure: - - core/ contains the core logic of the component.
diff --git a/components/precache/android/BUILD.gn b/components/precache/android/BUILD.gn deleted file mode 100644 index af99562..0000000 --- a/components/precache/android/BUILD.gn +++ /dev/null
@@ -1,29 +0,0 @@ -# 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("//build/config/android/rules.gni") - -android_library("precache_java") { - deps = [ - "//base:base_java", - ] - java_files = [ - "java/src/org/chromium/components/precache/DeviceState.java", - "java/src/org/chromium/components/precache/NetworkInfoDelegate.java", - "java/src/org/chromium/components/precache/NetworkInfoDelegateFactory.java", - ] -} - -android_library("precache_javatests") { - testonly = true - deps = [ - ":precache_java", - "//base:base_java_test_support", - "//third_party/android_support_test_runner:runner_java", - ] - java_files = [ - "javatests/src/org/chromium/components/precache/DeviceStateTest.java", - "javatests/src/org/chromium/components/precache/MockDeviceState.java", - ] -}
diff --git a/components/precache/android/java/src/org/chromium/components/precache/DeviceState.java b/components/precache/android/java/src/org/chromium/components/precache/DeviceState.java deleted file mode 100644 index 3315d79..0000000 --- a/components/precache/android/java/src/org/chromium/components/precache/DeviceState.java +++ /dev/null
@@ -1,106 +0,0 @@ -// 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. - -package org.chromium.components.precache; - -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.os.BatteryManager; - -import org.chromium.base.VisibleForTesting; - -/** - * Utility class that provides information about the current state of the device. - */ -public class DeviceState { - private static DeviceState sDeviceState; - - // Saved battery level percentage. - private int mSavedBatteryPercentage; - - /** Disallow Construction of DeviceState objects. Use {@link #getInstance()} instead to create - * a singleton instance. - */ - protected DeviceState() {} - - public static DeviceState getInstance() { - if (sDeviceState == null) sDeviceState = new DeviceState(); - return sDeviceState; - } - - protected NetworkInfoDelegateFactory mNetworkInfoDelegateFactory = - new NetworkInfoDelegateFactory(); - - @VisibleForTesting - void setNetworkInfoDelegateFactory(NetworkInfoDelegateFactory factory) { - mNetworkInfoDelegateFactory = factory; - } - - /** @return integer representing the current status of the battery. */ - @VisibleForTesting - int getStickyBatteryStatus(Context context) { - IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); - // Call registerReceiver on context.getApplicationContext(), not on context itself, because - // context could be a BroadcastReceiver context, which would throw an - // android.content.ReceiverCallNotAllowedException. - Intent batteryStatus = context.getApplicationContext().registerReceiver(null, iFilter); - - if (batteryStatus == null) { - return BatteryManager.BATTERY_STATUS_UNKNOWN; - } - return batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, - BatteryManager.BATTERY_STATUS_UNKNOWN); - } - - /** @return whether the device is connected to power. */ - public boolean isPowerConnected(Context context) { - int status = getStickyBatteryStatus(context); - return status == BatteryManager.BATTERY_STATUS_CHARGING - || status == BatteryManager.BATTERY_STATUS_FULL; - } - - /** - * @return the previously saved battery level percentage. - * @param context the application context - */ - public int getSavedBatteryPercentage() { - return mSavedBatteryPercentage; - } - - /** - * Saves the current battery level percentage to be retrieved later. - */ - public void saveCurrentBatteryPercentage(Context context) { - mSavedBatteryPercentage = getCurrentBatteryPercentage(context); - } - - /** - * @return the current battery level as percentage. - * @param context the application context - */ - public int getCurrentBatteryPercentage(Context context) { - IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); - Intent batteryStatus = context.registerReceiver(null, iFilter); - if (batteryStatus == null) return 0; - int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); - int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); - if (level == -1 || scale == -1) return 0; - if (scale == 0) return 0; - - return Math.round(100 * level / (float) scale); - } - - /** @return whether the currently active network is unmetered. */ - public boolean isUnmeteredNetworkAvailable(Context context) { - NetworkInfoDelegate networkInfo = - mNetworkInfoDelegateFactory.getNetworkInfoDelegate(context); - return (networkInfo.isValid() - && networkInfo.isAvailable() - && networkInfo.isConnected() - && !networkInfo.isRoaming() - && !networkInfo.isActiveNetworkMetered()); - } -} -
diff --git a/components/precache/android/java/src/org/chromium/components/precache/NetworkInfoDelegate.java b/components/precache/android/java/src/org/chromium/components/precache/NetworkInfoDelegate.java deleted file mode 100644 index f5abcd5..0000000 --- a/components/precache/android/java/src/org/chromium/components/precache/NetworkInfoDelegate.java +++ /dev/null
@@ -1,56 +0,0 @@ -// 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. - -package org.chromium.components.precache; - -import android.content.Context; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; - -import org.chromium.base.VisibleForTesting; - -/** - * Wrapper class for NetworkInfo and ConnectivityManager. - */ -public class NetworkInfoDelegate { - private NetworkInfo mNetworkInfo; - private ConnectivityManager mConnectivityManager; - - @VisibleForTesting - NetworkInfoDelegate() {} - - public NetworkInfoDelegate(Context context) { - getNetworkInfo(context); - } - - protected void getNetworkInfo(Context context) { - mConnectivityManager = - (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); - } - - protected boolean isValid() { - return mNetworkInfo != null; - } - - protected int getType() { - return mNetworkInfo.getType(); - } - - protected boolean isAvailable() { - return mNetworkInfo.isAvailable(); - } - - protected boolean isConnected() { - return mNetworkInfo.isConnected(); - } - - protected boolean isRoaming() { - return mNetworkInfo.isRoaming(); - } - - protected boolean isActiveNetworkMetered() { - return mConnectivityManager.isActiveNetworkMetered(); - } -}
diff --git a/components/precache/android/java/src/org/chromium/components/precache/NetworkInfoDelegateFactory.java b/components/precache/android/java/src/org/chromium/components/precache/NetworkInfoDelegateFactory.java deleted file mode 100644 index f274f39..0000000 --- a/components/precache/android/java/src/org/chromium/components/precache/NetworkInfoDelegateFactory.java +++ /dev/null
@@ -1,16 +0,0 @@ -// 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. - -package org.chromium.components.precache; - -import android.content.Context; - -/** - * Factory for creating network info delegates. - */ -public class NetworkInfoDelegateFactory { - NetworkInfoDelegate getNetworkInfoDelegate(Context context) { - return new NetworkInfoDelegate(context); - } -}
diff --git a/components/precache/android/javatests/src/org/chromium/components/precache/DeviceStateTest.java b/components/precache/android/javatests/src/org/chromium/components/precache/DeviceStateTest.java deleted file mode 100644 index 511655cf..0000000 --- a/components/precache/android/javatests/src/org/chromium/components/precache/DeviceStateTest.java +++ /dev/null
@@ -1,184 +0,0 @@ -// 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. - -package org.chromium.components.precache; - -import android.content.Context; -import android.net.ConnectivityManager; -import android.os.BatteryManager; -import android.support.test.filters.SmallTest; -import android.test.InstrumentationTestCase; - -import org.chromium.base.test.util.AdvancedMockContext; -import org.chromium.base.test.util.Feature; - -/** - * Tests for {@link DeviceState}. - */ -public class DeviceStateTest extends InstrumentationTestCase { - - /** - * Factory to create {@link MockNetworkInfoDelegate} instances. - */ - static class MockNetworkInfoDelegateFactory extends NetworkInfoDelegateFactory { - private final boolean mIsValid; - private final int mType; - private final boolean mIsAvailable; - private final boolean mIsConnected; - private final boolean mIsRoaming; - private final boolean mIsActiveNetworkMetered; - - MockNetworkInfoDelegateFactory(boolean valid, int type, boolean available, - boolean connected, boolean roaming, boolean activeNetworkMetered) { - mIsValid = valid; - mType = type; - mIsAvailable = available; - mIsConnected = connected; - mIsRoaming = roaming; - mIsActiveNetworkMetered = activeNetworkMetered; - } - - @Override - NetworkInfoDelegate getNetworkInfoDelegate(Context context) { - return new MockNetworkInfoDelegate(mIsValid, mType, mIsAvailable, mIsConnected, - mIsRoaming, mIsActiveNetworkMetered); - } - } - - /** - * Mock of {@link NetworkInfoDelegate}. - */ - static class MockNetworkInfoDelegate extends NetworkInfoDelegate { - private final boolean mIsValid; - private final int mType; - private final boolean mIsAvailable; - private final boolean mIsConnected; - private final boolean mIsRoaming; - private final boolean mIsActiveNetworkMetered; - - MockNetworkInfoDelegate(boolean valid, int type, boolean available, boolean connected, - boolean roaming, boolean activeNetworkMetered) { - mIsValid = valid; - mType = type; - mIsAvailable = available; - mIsConnected = connected; - mIsRoaming = roaming; - mIsActiveNetworkMetered = activeNetworkMetered; - } - - @Override - protected void getNetworkInfo(Context context) {} - - @Override - protected boolean isValid() { - return mIsValid; - } - - @Override - protected int getType() { - return mType; - } - - @Override - protected boolean isAvailable() { - return mIsAvailable; - } - - @Override - protected boolean isConnected() { - return mIsConnected; - } - - @Override - protected boolean isRoaming() { - return mIsRoaming; - } - - @Override - protected boolean isActiveNetworkMetered() { - return mIsActiveNetworkMetered; - } - } - - /** - * Mock of {@link DeviceState}. - */ - static class MockDeviceState extends DeviceState { - int mBatteryStatus; - - @Override - int getStickyBatteryStatus(Context context) { - return mBatteryStatus; - } - - public void setStickyBatteryStatus(int status) { - mBatteryStatus = status; - } - } - - @SmallTest - @Feature({"Precache"}) - public void testPowerConnected() { - AdvancedMockContext context = new AdvancedMockContext(); - MockDeviceState deviceState = new MockDeviceState(); - - deviceState.setStickyBatteryStatus(BatteryManager.BATTERY_STATUS_NOT_CHARGING); - assertFalse(deviceState.isPowerConnected(context)); - - deviceState.setStickyBatteryStatus(BatteryManager.BATTERY_STATUS_CHARGING); - assertTrue(deviceState.isPowerConnected(context)); - - deviceState.setStickyBatteryStatus(BatteryManager.BATTERY_STATUS_FULL); - assertTrue(deviceState.isPowerConnected(context)); - } - - @SmallTest - @Feature({"Precache"}) - public void testUnmeteredNetworkAvailable() { - AdvancedMockContext context = new AdvancedMockContext(); - DeviceState deviceState = DeviceState.getInstance(); - - // Expect WiFi to be reported as available because there is valid {@link NetworkInfo}, - // the connection is WiFi, it's available and connected, and not roaming or metered. - deviceState.setNetworkInfoDelegateFactory( - new MockNetworkInfoDelegateFactory( - true, ConnectivityManager.TYPE_WIFI, true, true, false, false)); - assertTrue(deviceState.isUnmeteredNetworkAvailable(context)); - - // Expect WiFi to be reported as unavailable because one of the aforementioned required - // conditions is not met. - deviceState.setNetworkInfoDelegateFactory( - new MockNetworkInfoDelegateFactory( - false, ConnectivityManager.TYPE_WIFI, true, true, false, false)); - assertFalse(deviceState.isUnmeteredNetworkAvailable(context)); - - deviceState.setNetworkInfoDelegateFactory( - new MockNetworkInfoDelegateFactory(true, 0, false, true, false, false)); - assertFalse(deviceState.isUnmeteredNetworkAvailable(context)); - - deviceState.setNetworkInfoDelegateFactory( - new MockNetworkInfoDelegateFactory( - true, ConnectivityManager.TYPE_WIFI, false, true, false, false)); - assertFalse(deviceState.isUnmeteredNetworkAvailable(context)); - - deviceState.setNetworkInfoDelegateFactory( - new MockNetworkInfoDelegateFactory( - true, ConnectivityManager.TYPE_WIFI, true, false, false, false)); - assertFalse(deviceState.isUnmeteredNetworkAvailable(context)); - - deviceState.setNetworkInfoDelegateFactory( - new MockNetworkInfoDelegateFactory( - true, ConnectivityManager.TYPE_WIFI, true, true, true, false)); - assertFalse(deviceState.isUnmeteredNetworkAvailable(context)); - - deviceState.setNetworkInfoDelegateFactory( - new MockNetworkInfoDelegateFactory( - true, ConnectivityManager.TYPE_WIFI, true, true, false, true)); - assertFalse(deviceState.isUnmeteredNetworkAvailable(context)); - - deviceState.setNetworkInfoDelegateFactory( - new MockNetworkInfoDelegateFactory(true, 0, false, false, true, true)); - assertFalse(deviceState.isUnmeteredNetworkAvailable(context)); - } -}
diff --git a/components/precache/android/javatests/src/org/chromium/components/precache/MockDeviceState.java b/components/precache/android/javatests/src/org/chromium/components/precache/MockDeviceState.java deleted file mode 100644 index 241d047..0000000 --- a/components/precache/android/javatests/src/org/chromium/components/precache/MockDeviceState.java +++ /dev/null
@@ -1,38 +0,0 @@ -// 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. - -package org.chromium.components.precache; - -import android.content.Context; - -/** - * Mock of the DeviceState class. - */ -public class MockDeviceState extends DeviceState { - private final int mStickyBatteryStatus; - private final boolean mPowerIsConnected; - private final boolean mUnmeteredAvailable; - - public MockDeviceState( - int stickyBatteryStatus, boolean powerIsConnected, boolean unmeteredAvailable) { - mStickyBatteryStatus = stickyBatteryStatus; - mPowerIsConnected = powerIsConnected; - mUnmeteredAvailable = unmeteredAvailable; - } - - @Override - int getStickyBatteryStatus(Context context) { - return mStickyBatteryStatus; - } - - @Override - public boolean isPowerConnected(Context context) { - return mPowerIsConnected; - } - - @Override - public boolean isUnmeteredNetworkAvailable(Context context) { - return mUnmeteredAvailable; - } -}
diff --git a/components/precache/content/BUILD.gn b/components/precache/content/BUILD.gn deleted file mode 100644 index bca9748e5..0000000 --- a/components/precache/content/BUILD.gn +++ /dev/null
@@ -1,50 +0,0 @@ -# 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. - -static_library("content") { - sources = [ - "precache_manager.cc", - "precache_manager.h", - ] - - configs += [ "//components/precache/core:precache_config" ] - - deps = [ - "//base", - "//components/data_reduction_proxy/core/browser", - "//components/history/core/browser", - "//components/keyed_service/core", - "//components/precache/core", - "//components/precache/core:proto", - "//components/prefs", - "//components/sync", - "//components/variations", - "//content/public/browser", - "//net", - "//sql", - "//url", - ] -} - -source_set("unit_tests") { - testonly = true - sources = [ - "precache_manager_unittest.cc", - ] - deps = [ - ":content", - "//base", - "//base/test:test_support", - "//components/history/core/browser", - "//components/precache/core", - "//components/precache/core:proto", - "//components/variations:test_support", - "//content/public/browser", - "//content/test:test_support", - "//net:test_support", - "//sql", - "//testing/gmock", - "//testing/gtest", - ] -}
diff --git a/components/precache/content/DEPS b/components/precache/content/DEPS deleted file mode 100644 index 5a18477..0000000 --- a/components/precache/content/DEPS +++ /dev/null
@@ -1,18 +0,0 @@ -include_rules = [ - "+components/data_reduction_proxy", - "+components/keyed_service", - "+components/sync/driver", - "+components/variations", - "+content/public/browser", - "+net/base", - "+net/disk_cache", - "+net/http", - "+net/url_request", -] - -specific_include_rules = { - '.*_[a-z]*test\.cc': [ - "+content/public/test", - "+net/test", - ], -}
diff --git a/components/precache/content/precache_manager.cc b/components/precache/content/precache_manager.cc deleted file mode 100644 index 16283f64..0000000 --- a/components/precache/content/precache_manager.cc +++ /dev/null
@@ -1,505 +0,0 @@ -// 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 "components/precache/content/precache_manager.h" - -#include <string> -#include <utility> -#include <vector> - -#include "base/bind.h" -#include "base/command_line.h" -#include "base/logging.h" -#include "base/memory/ref_counted.h" -#include "base/metrics/field_trial.h" -#include "base/metrics/histogram_macros.h" -#include "base/metrics/user_metrics.h" -#include "base/metrics/user_metrics_action.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/time/time.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" -#include "components/history/core/browser/history_service.h" -#include "components/precache/core/precache_database.h" -#include "components/precache/core/precache_switches.h" -#include "components/precache/core/proto/precache.pb.h" -#include "components/precache/core/proto/unfinished_work.pb.h" -#include "components/prefs/pref_service.h" -#include "components/sync/driver/sync_service.h" -#include "components/variations/metrics_util.h" -#include "components/variations/variations_associated_data.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/storage_partition.h" -#include "net/base/network_change_notifier.h" -#include "net/http/http_cache.h" -#include "net/url_request/url_request_context.h" -#include "net/url_request/url_request_context_getter.h" - -using content::BrowserThread; - -namespace precache { - -const char kPrecacheFieldTrialName[] = "Precache"; -const char kMinCacheSizeParam[] = "min_cache_size"; - -namespace { - -const char kPrecacheFieldTrialEnabledGroup[] = "Enabled"; -const char kPrecacheFieldTrialControlGroup[] = "Control"; -const char kConfigURLParam[] = "config_url"; -const char kManifestURLPrefixParam[] = "manifest_url_prefix"; -const char kDataReductionProxyParam[] = "disable_if_data_reduction_proxy"; -const size_t kNumTopHosts = 100; - -} // namespace - -size_t NumTopHosts() { - return kNumTopHosts; -} - -PrecacheManager::PrecacheManager( - content::BrowserContext* browser_context, - const syncer::SyncService* const sync_service, - const history::HistoryService* const history_service, - const data_reduction_proxy::DataReductionProxySettings* - data_reduction_proxy_settings, - const base::FilePath& db_path, - std::unique_ptr<PrecacheDatabase> precache_database) - : browser_context_(browser_context), - sync_service_(sync_service), - history_service_(history_service), - data_reduction_proxy_settings_(data_reduction_proxy_settings), - is_precaching_(false) { - precache_database_ = std::move(precache_database); - BrowserThread::PostTask( - BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&PrecacheDatabase::Init), - base::Unretained(precache_database_.get()), db_path)); -} - -PrecacheManager::~PrecacheManager() { - // DeleteSoon posts a non-nestable task to the task runner, so any previously - // posted tasks that rely on an Unretained precache_database_ will finish - // before it is deleted. - BrowserThread::DeleteSoon(BrowserThread::DB, FROM_HERE, - precache_database_.release()); -} - -bool PrecacheManager::IsInExperimentGroup() const { - // Verify IsPrecachingAllowed() before calling FieldTrialList::FindFullName(). - // This is because field trials are only assigned when requested. This allows - // us to create Control and Experiment groups that are limited to users for - // whom PrecachingAllowed() is true, thus accentuating the impact of - // precaching. - return IsPrecachingAllowed() && - (base::StartsWith( - base::FieldTrialList::FindFullName(kPrecacheFieldTrialName), - kPrecacheFieldTrialEnabledGroup, base::CompareCase::SENSITIVE) || - base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnablePrecache)); -} - -bool PrecacheManager::IsInControlGroup() const { - // Verify IsPrecachingAllowed() before calling FindFullName(). See - // PrecacheManager::IsInExperimentGroup() for an explanation of why. - return IsPrecachingAllowed() && - base::StartsWith( - base::FieldTrialList::FindFullName(kPrecacheFieldTrialName), - kPrecacheFieldTrialControlGroup, base::CompareCase::SENSITIVE); -} - -bool PrecacheManager::IsPrecachingAllowed() const { - return PrecachingAllowed() == AllowedType::ALLOWED; -} - -PrecacheManager::AllowedType PrecacheManager::PrecachingAllowed() const { - bool disable_if_proxy = !variations::GetVariationParamValue( - kPrecacheFieldTrialName, kDataReductionProxyParam).empty(); - if (disable_if_proxy && - (!data_reduction_proxy_settings_ || - data_reduction_proxy_settings_->IsDataReductionProxyEnabled())) - return AllowedType::DISALLOWED; - - if (!(sync_service_ && sync_service_->IsEngineInitialized())) - return AllowedType::PENDING; - - // SyncService delegates to SyncPrefs, which must be called on the UI thread. - if (history_service_ && !sync_service_->IsLocalSyncEnabled() && - sync_service_->GetActiveDataTypes().Has(syncer::SESSIONS) && - !sync_service_->GetEncryptedDataTypes().Has(syncer::SESSIONS)) { - return AllowedType::ALLOWED; - } - - return AllowedType::DISALLOWED; -} - -void PrecacheManager::OnCacheBackendReceived(int net_error_code) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - if (net_error_code != net::OK) { - // Assume there is no cache. - cache_backend_ = nullptr; - OnCacheSizeReceived(0); - return; - } - DCHECK(cache_backend_); - int result = cache_backend_->CalculateSizeOfAllEntries(base::Bind( - &PrecacheManager::OnCacheSizeReceived, base::Unretained(this))); - if (result == net::ERR_IO_PENDING) { - // Wait for the callback. - } else if (result >= 0) { - // The result is the expected bytes already. - OnCacheSizeReceived(result); - } else { - // Error occurred. Couldn't get the size. Assume there is no cache. - OnCacheSizeReceived(0); - } - cache_backend_ = nullptr; -} - -void PrecacheManager::OnCacheSizeReceived(int cache_size_bytes) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - base::Bind(&PrecacheManager::OnCacheSizeReceivedInUIThread, - base::Unretained(this), cache_size_bytes)); -} - -void PrecacheManager::OnCacheSizeReceivedInUIThread(int cache_size_bytes) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - UMA_HISTOGRAM_MEMORY_KB("Precache.CacheSize.AllEntries", - cache_size_bytes / 1024); - - if (cache_size_bytes < min_cache_size_bytes_) { - OnDone(); // Do not continue. - } else { - BrowserThread::PostTaskAndReplyWithResult( - BrowserThread::DB, FROM_HERE, - base::Bind(&PrecacheDatabase::GetUnfinishedWork, - base::Unretained(precache_database_.get())), - base::Bind(&PrecacheManager::OnGetUnfinishedWorkDone, AsWeakPtr())); - } -} - -void PrecacheManager::PrecacheIfCacheIsBigEnough( - scoped_refptr<net::URLRequestContextGetter> url_request_context_getter) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - CHECK(url_request_context_getter); - - // Continue with OnGetUnfinishedWorkDone only if the size of the cache is - // at least min_cache_size_bytes_. - // Class disk_cache::Backend does not expose its maximum size. However, caches - // are usually full, so we can use the size of all the entries stored in the - // cache (via CalculateSizeOfAllEntries) as a proxy of its maximum size. - net::URLRequestContext* context = - url_request_context_getter->GetURLRequestContext(); - if (!context) { - OnCacheSizeReceived(0); - return; - } - net::HttpTransactionFactory* factory = context->http_transaction_factory(); - if (!factory) { - OnCacheSizeReceived(0); - return; - } - net::HttpCache* cache = factory->GetCache(); - if (!cache) { - // There is no known cache. Assume that there is no cache. - // TODO(jamartin): I'm not sure this can be an actual posibility. Consider - // making this a CHECK(cache). - OnCacheSizeReceived(0); - return; - } - const int net_error_code = cache->GetBackend( - &cache_backend_, base::Bind(&PrecacheManager::OnCacheBackendReceived, - base::Unretained(this))); - if (net_error_code != net::ERR_IO_PENDING) { - // No need to wait for the callback. The callback hasn't been called with - // the appropriate code, so we call it directly. - OnCacheBackendReceived(net_error_code); - } -} - -void PrecacheManager::StartPrecaching( - const PrecacheCompletionCallback& precache_completion_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - if (is_precaching_) { - DLOG(WARNING) << "Cannot start precaching because precaching is already " - "in progress."; - return; - } - precache_completion_callback_ = precache_completion_callback; - - is_precaching_ = true; - BrowserThread::PostTask( - BrowserThread::DB, FROM_HERE, - base::Bind(&PrecacheDatabase::SetLastPrecacheTimestamp, - base::Unretained(precache_database_.get()), - base::Time::Now())); - - // Ignore boolean return value. In all documented failure cases, it sets the - // int to a reasonable value. - base::StringToInt(variations::GetVariationParamValue(kPrecacheFieldTrialName, - kMinCacheSizeParam), - &min_cache_size_bytes_); - if (min_cache_size_bytes_ <= 0) { - // Skip looking up the cache size, because it doesn't matter. - OnCacheSizeReceivedInUIThread(0); - return; - } - - scoped_refptr<net::URLRequestContextGetter> url_request_context_getter( - content::BrowserContext::GetDefaultStoragePartition(browser_context_) - ->GetURLRequestContext()); - if (!url_request_context_getter) { - OnCacheSizeReceivedInUIThread(0); - return; - } - - BrowserThread::PostTask( - BrowserThread::IO, FROM_HERE, - base::Bind(&PrecacheManager::PrecacheIfCacheIsBigEnough, AsWeakPtr(), - std::move(url_request_context_getter))); -} - -void PrecacheManager::OnGetUnfinishedWorkDone( - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work) { - // Reset progress on a prefetch that has taken too long to complete. - if (unfinished_work->has_start_time() && - base::Time::Now() - - base::Time::FromInternalValue(unfinished_work->start_time()) > - base::TimeDelta::FromHours(6)) { - PrecacheFetcher::RecordCompletionStatistics( - *unfinished_work, unfinished_work->top_host_size(), - unfinished_work->resource_size()); - unfinished_work.reset(new PrecacheUnfinishedWork); - } - // If this prefetch is new, set the start time. - if (!unfinished_work->has_start_time()) - unfinished_work->set_start_time(base::Time::Now().ToInternalValue()); - unfinished_work_ = std::move(unfinished_work); - bool needs_top_hosts = unfinished_work_->top_host_size() == 0; - - base::RecordAction(base::UserMetricsAction("Precache.Fetch.Begin")); - - if (IsInExperimentGroup()) { - BrowserThread::PostTask( - BrowserThread::DB, FROM_HERE, - base::Bind(&PrecacheDatabase::DeleteExpiredPrecacheHistory, - base::Unretained(precache_database_.get()), - base::Time::Now())); - - // Request NumTopHosts() top hosts. Note that PrecacheFetcher is further - // bound by the value of PrecacheConfigurationSettings.top_sites_count, as - // retrieved from the server. - if (needs_top_hosts) { - history_service_->TopHosts( - NumTopHosts(), - base::Bind(&PrecacheManager::OnHostsReceived, AsWeakPtr())); - } else { - InitializeAndStartFetcher(); - } - } else if (IsInControlGroup()) { - // Calculate TopHosts solely for metrics purposes. - if (needs_top_hosts) { - history_service_->TopHosts( - NumTopHosts(), - base::Bind(&PrecacheManager::OnHostsReceivedThenDone, AsWeakPtr())); - } else { - OnDone(); - } - } else { - if (PrecachingAllowed() != AllowedType::PENDING) { - // We are not waiting on the sync engine to be initialized. The user - // either is not in the field trial, or does not have sync enabled. - // Pretend that precaching started, so that the PrecacheServiceLauncher - // doesn't try to start it again. - } - - OnDone(); - } -} - -void PrecacheManager::CancelPrecaching() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!is_precaching_) { - // Do nothing if precaching is not in progress. - return; - } - is_precaching_ = false; - // If cancellation occurs after StartPrecaching but before OnHostsReceived, - // is_precaching will be true, but the precache_fetcher_ will not yet be - // constructed. - if (precache_fetcher_) { - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work = - precache_fetcher_->CancelPrecaching(); - if (unfinished_work) { - BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, - base::Bind(&PrecacheDatabase::SaveUnfinishedWork, - precache_database_->GetWeakPtr(), - base::Passed(&unfinished_work))); - } - // Destroying the |precache_fetcher_| will cancel any fetch in progress. - precache_fetcher_.reset(); - } - precache_completion_callback_.Reset(); -} - -bool PrecacheManager::IsPrecaching() const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - return is_precaching_; -} - -void PrecacheManager::UpdatePrecacheMetricsAndState( - const GURL& url, - const GURL& referrer, - const base::Time& fetch_time, - const net::HttpResponseInfo& info, - int64_t size, - bool is_user_traffic, - const base::Callback<void(base::Time)>& register_synthetic_trial) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BrowserThread::PostTaskAndReplyWithResult( - BrowserThread::DB, FROM_HERE, - base::Bind(&PrecacheDatabase::GetLastPrecacheTimestamp, - base::Unretained(precache_database_.get())), - base::Bind(&PrecacheManager::RecordStatsForFetch, AsWeakPtr(), url, - referrer, fetch_time, info, size, register_synthetic_trial)); - - if (is_user_traffic && IsPrecaching()) - CancelPrecaching(); -} - -void PrecacheManager::RecordStatsForFetch( - const GURL& url, - const GURL& referrer, - const base::Time& fetch_time, - const net::HttpResponseInfo& info, - int64_t size, - const base::Callback<void(base::Time)>& register_synthetic_trial, - base::Time last_precache_time) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - register_synthetic_trial.Run(last_precache_time); - - if (size == 0 || url.is_empty() || !url.SchemeIsHTTPOrHTTPS()) { - // Ignore empty responses, empty URLs, or URLs that aren't HTTP or HTTPS. - return; - } - - if (!history_service_) - return; - - history_service_->HostRankIfAvailable( - referrer, - base::Bind(&PrecacheManager::RecordStatsForFetchInternal, AsWeakPtr(), - url, referrer.host(), fetch_time, info, size)); -} - -void PrecacheManager::RecordStatsForFetchInternal( - const GURL& url, - const std::string& referrer_host, - const base::Time& fetch_time, - const net::HttpResponseInfo& info, - int64_t size, - int host_rank) { - if (is_precaching_) { - // Assume that precache is responsible for all requests made while - // precaching is currently in progress. - // TODO(sclittle): Make PrecacheFetcher explicitly mark precache-motivated - // fetches, and use that to determine whether or not a fetch was motivated - // by precaching. - BrowserThread::PostTask( - BrowserThread::DB, FROM_HERE, - base::Bind(&PrecacheDatabase::RecordURLPrefetchMetrics, - base::Unretained(precache_database_.get()), info)); - } else { - bool is_connection_cellular = - net::NetworkChangeNotifier::IsConnectionCellular( - net::NetworkChangeNotifier::GetConnectionType()); - - BrowserThread::PostTask( - BrowserThread::DB, FROM_HERE, - base::Bind(&PrecacheDatabase::RecordURLNonPrefetch, - base::Unretained(precache_database_.get()), url, fetch_time, - info, size, host_rank, is_connection_cellular)); - } -} - -void PrecacheManager::ClearHistory() { - // PrecacheDatabase::ClearHistory must run after PrecacheDatabase::Init has - // finished. Using PostNonNestableTask guarantees this, by definition. See - // base::SequencedTaskRunner for details. - BrowserThread::PostNonNestableTask( - BrowserThread::DB, FROM_HERE, - base::Bind(&PrecacheDatabase::ClearHistory, - base::Unretained(precache_database_.get()))); -} - -void PrecacheManager::Shutdown() { - CancelPrecaching(); -} - -void PrecacheManager::OnDone() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - precache_fetcher_.reset(); - - // Run completion callback if not null. It's null if the client is in the - // Control group and CancelPrecaching is called before TopHosts computation - // finishes. - if (!precache_completion_callback_.is_null()) { - precache_completion_callback_.Run(!is_precaching_); - // Uninitialize the callback so that any scoped_refptrs in it are released. - precache_completion_callback_.Reset(); - } - - is_precaching_ = false; -} - -void PrecacheManager::OnHostsReceived( - const history::TopHostsList& host_counts) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - for (const auto& host_count : host_counts) { - TopHost* top_host = unfinished_work_->add_top_host(); - top_host->set_hostname(host_count.first); - top_host->set_visits(host_count.second); - } - InitializeAndStartFetcher(); -} - -void PrecacheManager::InitializeAndStartFetcher() { - if (!is_precaching_) { - // Don't start precaching if it was canceled while waiting for the list of - // hosts. - return; - } - // Start precaching. - precache_fetcher_.reset(new PrecacheFetcher( - content::BrowserContext::GetDefaultStoragePartition(browser_context_) - ->GetURLRequestContext(), - GURL(variations::GetVariationParamValue(kPrecacheFieldTrialName, - kConfigURLParam)), - variations::GetVariationParamValue(kPrecacheFieldTrialName, - kManifestURLPrefixParam), - std::move(unfinished_work_), - metrics::HashName( - base::FieldTrialList::FindFullName(kPrecacheFieldTrialName)), - precache_database_->GetWeakPtr(), - content::BrowserThread::GetTaskRunnerForThread( - content::BrowserThread::DB), - this)); - precache_fetcher_->Start(); -} - -void PrecacheManager::OnHostsReceivedThenDone( - const history::TopHostsList& host_counts) { - OnDone(); -} - -} // namespace precache
diff --git a/components/precache/content/precache_manager.h b/components/precache/content/precache_manager.h deleted file mode 100644 index afd5e6c..0000000 --- a/components/precache/content/precache_manager.h +++ /dev/null
@@ -1,254 +0,0 @@ -// 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 COMPONENTS_PRECACHE_CONTENT_PRECACHE_MANAGER_H_ -#define COMPONENTS_PRECACHE_CONTENT_PRECACHE_MANAGER_H_ - -#include <stddef.h> -#include <stdint.h> - -#include <list> -#include <memory> -#include <string> -#include <utility> -#include <vector> - -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "components/history/core/browser/history_types.h" -#include "components/keyed_service/core/keyed_service.h" -#include "components/precache/core/precache_fetcher.h" -#include "net/disk_cache/disk_cache.h" -#include "net/http/http_cache.h" -#include "url/gurl.h" - -namespace base { -class FilePath; -class Time; -} - -namespace content { -class BrowserContext; -} - -namespace data_reduction_proxy { -class DataReductionProxySettings; -} - -namespace history { -class HistoryService; -} - -namespace net { -class HttpResponseInfo; -} - -namespace syncer { -class SyncService; -} - -namespace precache { - -class PrecacheDatabase; -class PrecacheUnfinishedWork; - -extern const char kPrecacheFieldTrialName[]; - -// Visible for test. -extern const char kMinCacheSizeParam[]; -size_t NumTopHosts(); - -// Class that manages all precaching-related activities. Owned by the -// BrowserContext that it is constructed for. Use -// PrecacheManagerFactory::GetForBrowserContext to get an instance of this -// class. All methods must be called on the UI thread unless indicated -// otherwise. -// TODO(sclittle): Delete precache history when browsing history is deleted. -// http://crbug.com/326549 -class PrecacheManager : public KeyedService, - public PrecacheFetcher::PrecacheDelegate, - public base::SupportsWeakPtr<PrecacheManager> { - public: - typedef base::Callback<void(bool)> PrecacheCompletionCallback; - - PrecacheManager(content::BrowserContext* browser_context, - const syncer::SyncService* sync_service, - const history::HistoryService* history_service, - const data_reduction_proxy::DataReductionProxySettings* - data_reduction_proxy_settings, - const base::FilePath& db_path, - std::unique_ptr<PrecacheDatabase> precache_database); - ~PrecacheManager() override; - - // Returns true if the client is in the experiment group -- that is, - // precaching is allowed based on user settings, and enabled as part of a - // field trial or by commandline flag. Virtual for testing. - virtual bool IsInExperimentGroup() const; - - // Returns true if the client is in the control group -- that is, precaching - // is allowed based on user settings, and the browser is in the control group - // of the field trial. Virtual for testing. - virtual bool IsInControlGroup() const; - - // Returns true if precaching is allowed based on user settings. Virtual for - // testing. - virtual bool IsPrecachingAllowed() const; - - // Starts precaching resources that the user is predicted to fetch in the - // future. If precaching is already currently in progress, then this method - // does nothing. The |precache_completion_callback| will be passed true when - // precaching finishes, and passed false when precaching abort due to failed - // preconditions, but will not be run if precaching is canceled. - void StartPrecaching( - const PrecacheCompletionCallback& precache_completion_callback); - - // Cancels precaching if it is in progress. - void CancelPrecaching(); - - // Returns true if precaching is currently in progress, or false otherwise. - bool IsPrecaching() const; - - // Posts a task to the DB thread to delete all history entries from the - // database. Does not wait for completion of this task. - void ClearHistory(); - - // Update precache about an URL being fetched. Metrics related to precache are - // updated and any ongoing precache will be cancelled if this is an user - // initiated request. Should be called on UI thread. - void UpdatePrecacheMetricsAndState( - const GURL& url, - const GURL& referrer, - const base::Time& fetch_time, - const net::HttpResponseInfo& info, - int64_t size, - bool is_user_traffic, - const base::Callback<void(base::Time)>& register_synthetic_trial); - - private: - friend class PrecacheManagerTest; - FRIEND_TEST_ALL_PREFIXES(PrecacheManagerTest, DeleteExpiredPrecacheHistory); - FRIEND_TEST_ALL_PREFIXES(PrecacheManagerTest, - RecordStatsForFetchDuringPrecaching); - FRIEND_TEST_ALL_PREFIXES(PrecacheManagerTest, RecordStatsForFetchHTTP); - FRIEND_TEST_ALL_PREFIXES(PrecacheManagerTest, RecordStatsForFetchHTTPS); - FRIEND_TEST_ALL_PREFIXES(PrecacheManagerTest, RecordStatsForFetchInTopHosts); - FRIEND_TEST_ALL_PREFIXES(PrecacheManagerTest, - RecordStatsForFetchWithEmptyURL); - FRIEND_TEST_ALL_PREFIXES(PrecacheManagerTest, RecordStatsForFetchWithNonHTTP); - FRIEND_TEST_ALL_PREFIXES(PrecacheManagerTest, - RecordStatsForFetchWithSizeZero); - - enum class AllowedType { - ALLOWED, - DISALLOWED, - PENDING - }; - - // From KeyedService. - void Shutdown() override; - - // From PrecacheFetcher::PrecacheDelegate. - void OnDone() override; - - // Registers the precache synthetic field trial for users whom the precache - // task was run recently. |last_precache_time| is the last time precache task - // was run. - void RegisterSyntheticFieldTrial(const base::Time last_precache_time); - - // Callback when fetching unfinished work from storage is done. - void OnGetUnfinishedWorkDone( - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work); - - // From history::HistoryService::TopHosts. - void OnHostsReceived(const history::TopHostsList& host_counts); - - // Initializes and Starts a PrecacheFetcher with unfinished work. - void InitializeAndStartFetcher(); - - // From history::HistoryService::TopHosts. Used for the control group, which - // gets the list of TopHosts for metrics purposes, but otherwise does nothing. - void OnHostsReceivedThenDone(const history::TopHostsList& host_counts); - - // Chain of callbacks for StartPrecaching that make sure that we only precache - // if there is a cache big enough. - void PrecacheIfCacheIsBigEnough( - scoped_refptr<net::URLRequestContextGetter> url_request_context_getter); - void OnCacheBackendReceived(int net_error_code); - void OnCacheSizeReceived(int cache_size_bytes); - void OnCacheSizeReceivedInUIThread(int cache_size_bytes); - - // Returns true if precaching is allowed for the browser context. - AllowedType PrecachingAllowed() const; - - // Update precache-related metrics in response to a URL being fetched. - void RecordStatsForFetch( - const GURL& url, - const GURL& referrer, - const base::Time& fetch_time, - const net::HttpResponseInfo& info, - int64_t size, - const base::Callback<void(base::Time)>& register_synthetic_trial, - base::Time last_precache_time); - - // Update precache-related metrics in response to a URL being fetched. Called - // by RecordStatsForFetch() by way of an asynchronous HistoryService callback. - void RecordStatsForFetchInternal(const GURL& url, - const std::string& referrer_host, - const base::Time& fetch_time, - const net::HttpResponseInfo& info, - int64_t size, - int host_rank); - - // The browser context that owns this PrecacheManager. - content::BrowserContext* const browser_context_; - - // The sync service corresponding to the browser context. Used to determine - // whether precache can run. May be null. - const syncer::SyncService* const sync_service_; - - // The history service corresponding to the browser context. Used to determine - // the list of top hosts. May be null. - const history::HistoryService* const history_service_; - - // The data reduction proxy settings object corresponding to the browser - // context. Used to determine if the proxy is enabled. - const data_reduction_proxy::DataReductionProxySettings* const - data_reduction_proxy_settings_; - - // The PrecacheFetcher used to precache resources. Should only be used on the - // UI thread. - std::unique_ptr<PrecacheFetcher> precache_fetcher_; - - // The callback that will be run if precaching finishes without being - // canceled. - PrecacheCompletionCallback precache_completion_callback_; - - // The PrecacheDatabase for tracking precache metrics. Should only be used on - // the DB thread. - std::unique_ptr<PrecacheDatabase> precache_database_; - - // Flag indicating whether or not precaching is currently in progress. - bool is_precaching_; - - // Pointer to the backend of the cache. Required to get the size of the cache. - // It is not owned and it is reset on demand via callbacks. - // It should only be accessed from the IO thread. - disk_cache::Backend* cache_backend_; - - // The minimum cache size allowed for precaching. Initialized by - // StartPrecaching and read by OnCacheSizeReceivedInUIThread. - int min_cache_size_bytes_; - - // Work that hasn't yet finished. - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work_; - - DISALLOW_COPY_AND_ASSIGN(PrecacheManager); -}; - -} // namespace precache - -#endif // COMPONENTS_PRECACHE_CONTENT_PRECACHE_MANAGER_H_
diff --git a/components/precache/content/precache_manager_unittest.cc b/components/precache/content/precache_manager_unittest.cc deleted file mode 100644 index 67ef094..0000000 --- a/components/precache/content/precache_manager_unittest.cc +++ /dev/null
@@ -1,682 +0,0 @@ -// 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 "components/precache/content/precache_manager.h" - -#include <stddef.h> - -#include <map> -#include <memory> -#include <set> -#include <string> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/command_line.h" -#include "base/compiler_specific.h" -#include "base/files/file_path.h" -#include "base/files/scoped_temp_dir.h" -#include "base/location.h" -#include "base/run_loop.h" -#include "base/single_thread_task_runner.h" -#include "base/test/histogram_tester.h" -#include "base/threading/thread_task_runner_handle.h" -#include "components/history/core/browser/history_constants.h" -#include "components/history/core/browser/history_service.h" -#include "components/history/core/browser/history_types.h" -#include "components/precache/core/precache_database.h" -#include "components/precache/core/precache_switches.h" -#include "components/precache/core/proto/unfinished_work.pb.h" -#include "components/variations/variations_params_manager.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/storage_partition.h" -#include "content/public/test/test_browser_context.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "net/base/test_completion_callback.h" -#include "net/disk_cache/simple/simple_backend_impl.h" -#include "net/http/http_response_headers.h" -#include "net/http/http_response_info.h" -#include "net/http/http_status_code.h" -#include "net/test/gtest_util.h" -#include "net/url_request/test_url_fetcher_factory.h" -#include "net/url_request/url_request_status.h" -#include "net/url_request/url_request_test_util.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace precache { - -namespace { - -using ::testing::_; -using ::testing::ContainerEq; -using ::testing::UnorderedElementsAre; -using ::testing::Invoke; -using ::testing::IsEmpty; -using ::testing::Pair; -using ::testing::SaveArg; - -const char kConfigURL[] = "http://config-url.com"; -const char kManifestURLPrefix[] = "http://manifest-url-prefix.com/"; -const char kGoodManifestURL[] = - "http://manifest-url-prefix.com/good-manifest.com"; -const char kEvilManifestURL[] = - "http://manifest-url-prefix.com/evil-manifest.com"; - -class TestURLFetcherCallback { - public: - std::unique_ptr<net::FakeURLFetcher> CreateURLFetcher( - const GURL& url, - net::URLFetcherDelegate* delegate, - const std::string& response_data, - net::HttpStatusCode response_code, - net::URLRequestStatus::Status status) { - std::unique_ptr<net::FakeURLFetcher> fetcher(new net::FakeURLFetcher( - url, delegate, response_data, response_code, status)); - - requested_urls_.insert(url); - return fetcher; - } - - const std::multiset<GURL>& requested_urls() const { - return requested_urls_; - } - - private: - // Multiset with one entry for each URL requested. - std::multiset<GURL> requested_urls_; -}; - -class MockHistoryService : public history::HistoryService { - public: - MockHistoryService() { - ON_CALL(*this, HostRankIfAvailable(_, _)) - .WillByDefault(Invoke( - [](const GURL& url, const base::Callback<void(int)>& callback) { - callback.Run(history::kMaxTopHosts); - })); - } - - MOCK_CONST_METHOD2(TopHosts, - void(size_t num_hosts, const TopHostsCallback& callback)); - - MOCK_CONST_METHOD2(HostRankIfAvailable, - void(const GURL& url, - const base::Callback<void(int)>& callback)); -}; - -ACTION_P(ReturnHosts, starting_hosts) { - arg1.Run(starting_hosts); -} - -class TestPrecacheCompletionCallback { - public: - TestPrecacheCompletionCallback() : was_on_done_called_(false) {} - - void OnDone(bool precaching_started) { was_on_done_called_ = true; } - - PrecacheManager::PrecacheCompletionCallback GetCallback() { - return base::Bind(&TestPrecacheCompletionCallback::OnDone, - base::Unretained(this)); - } - - bool was_on_done_called() const { - return was_on_done_called_; - } - - private: - bool was_on_done_called_; -}; - -class PrecacheManagerUnderTest : public PrecacheManager { - public: - PrecacheManagerUnderTest( - content::BrowserContext* browser_context, - const syncer::SyncService* sync_service, - const history::HistoryService* history_service, - const data_reduction_proxy::DataReductionProxySettings* - data_reduction_proxy_settings, - const base::FilePath& db_path, - std::unique_ptr<PrecacheDatabase> precache_database) - : PrecacheManager(browser_context, - sync_service, - history_service, - data_reduction_proxy_settings, - db_path, - std::move(precache_database)), - control_group_(false) {} - bool IsInExperimentGroup() const override { return !control_group_; } - bool IsInControlGroup() const override { return control_group_; } - bool IsPrecachingAllowed() const override { return true; } - void SetInControlGroup(bool in_control_group) { - control_group_ = in_control_group; - } - - private: - bool control_group_; -}; - -} // namespace - -class PrecacheManagerTest : public testing::Test { - public: - PrecacheManagerTest() - : factory_(nullptr, - base::Bind(&TestURLFetcherCallback::CreateURLFetcher, - base::Unretained(&url_callback_))) {} - - ~PrecacheManagerTest() { - // precache_manager_'s constructor releases a PrecacheDatabase and deletes - // it on the DB thread. PrecacheDatabase already has a pending Init call - // which will assert in debug builds because the directory passed to it is - // deleted. So manually ensure that the task is run before browser_context_ - // is destructed. - base::RunLoop().RunUntilIdle(); - } - - protected: - void SetUp() override { - base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kPrecacheConfigSettingsURL, kConfigURL); - base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kPrecacheManifestURLPrefix, kManifestURLPrefix); - - ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); - precache_database_ = new PrecacheDatabase; - Reset(precache_database_); - base::RunLoop().RunUntilIdle(); - - // Make the fetch of the precache configuration settings fail. Precaching - // should still complete normally in this case. - factory_.SetFakeResponse(GURL(kConfigURL), "", - net::HTTP_INTERNAL_SERVER_ERROR, - net::URLRequestStatus::FAILED); - info_.headers = new net::HttpResponseHeaders(""); - } - - // precache_manager_ assumes ownership of precache_database. - void Reset(PrecacheDatabase* precache_database) { - base::FilePath db_path = scoped_temp_dir_.GetPath().Append( - base::FilePath(FILE_PATH_LITERAL("precache_database"))); - precache_manager_.reset(new PrecacheManagerUnderTest( - &browser_context_, nullptr /* sync_service */, &history_service_, - nullptr /* data_reduction_proxy_settings */, db_path, - base::WrapUnique(precache_database))); - } - - void Flush() { precache_database_->Flush(); } - - void RecordStatsForFetch(const GURL& url, - const std::string& referrer_host, - const base::Time& fetch_time, - const net::HttpResponseInfo& info, - int64_t size, - base::Time last_precache_time) { - precache_manager_->RecordStatsForFetch( - url, GURL(referrer_host), fetch_time, info, size, - base::Bind(&PrecacheManagerTest::RegisterSyntheticFieldTrial, - base::Unretained(this)), - last_precache_time); - } - - void RecordStatsForPrecacheFetch(const GURL& url, - const std::string& referrer_host, - const base::Time& fetch_time, - const net::HttpResponseInfo& info, - int64_t size, - base::Time last_precache_time) { - RecordStatsForFetch(url, referrer_host, fetch_time, info, size, - last_precache_time); - precache_database_->RecordURLPrefetch(url, referrer_host, fetch_time, - info.was_cached, size); - } - - MOCK_METHOD1(RegisterSyntheticFieldTrial, - void(base::Time last_precache_time)); - - // Must be declared first so that it is destroyed last. - content::TestBrowserThreadBundle test_browser_thread_bundle_; - base::ScopedTempDir scoped_temp_dir_; - PrecacheDatabase* precache_database_; - content::TestBrowserContext browser_context_; - std::unique_ptr<PrecacheManagerUnderTest> precache_manager_; - TestURLFetcherCallback url_callback_; - net::FakeURLFetcherFactory factory_; - TestPrecacheCompletionCallback precache_callback_; - testing::NiceMock<MockHistoryService> history_service_; - base::HistogramTester histograms_; - net::HttpResponseInfo info_; - variations::testing::VariationParamsManager variation_params_; -}; - -TEST_F(PrecacheManagerTest, StartAndFinishPrecaching) { - EXPECT_FALSE(precache_manager_->IsPrecaching()); - - MockHistoryService::TopHostsCallback top_hosts_callback; - EXPECT_CALL(history_service_, TopHosts(NumTopHosts(), _)) - .WillOnce(SaveArg<1>(&top_hosts_callback)); - - factory_.SetFakeResponse(GURL(kConfigURL), "", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodManifestURL), "", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - precache_manager_->StartPrecaching(precache_callback_.GetCallback()); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(precache_manager_->IsPrecaching()); - - top_hosts_callback.Run( - history::TopHostsList(1, std::make_pair("good-manifest.com", 1))); - base::RunLoop().RunUntilIdle(); // For PrecacheFetcher. - EXPECT_FALSE(precache_manager_->IsPrecaching()); - EXPECT_TRUE(precache_callback_.was_on_done_called()); - - std::multiset<GURL> expected_requested_urls; - expected_requested_urls.insert(GURL(kConfigURL)); - expected_requested_urls.insert(GURL(kGoodManifestURL)); - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); -} - -TEST_F(PrecacheManagerTest, StartPrecachingWithGoodSizedCache) { - variation_params_.SetVariationParams(kPrecacheFieldTrialName, - {{kMinCacheSizeParam, "1"}}); - - // Let's store something in the cache so we pass the min_cache_size threshold. - disk_cache::Backend* cache_backend; - { - // Get the CacheBackend. - net::TestCompletionCallback cb; - net::HttpCache* cache = - content::BrowserContext::GetDefaultStoragePartition(&browser_context_) - ->GetURLRequestContext() - ->GetURLRequestContext() - ->http_transaction_factory() - ->GetCache(); - CHECK_NE(nullptr, cache); - int rv = cache->GetBackend(&cache_backend, cb.callback()); - CHECK_EQ(net::OK, cb.GetResult(rv)); - CHECK_NE(nullptr, cache_backend); - CHECK_EQ(cache_backend, cache->GetCurrentBackend()); - } - disk_cache::Entry* entry = nullptr; - { - // Create a cache Entry. - net::TestCompletionCallback cb; - int rv = cache_backend->CreateEntry("key", &entry, cb.callback()); - CHECK_EQ(net::OK, cb.GetResult(rv)); - CHECK_NE(nullptr, entry); - } - { - // Store some data in the cache Entry. - const std::string data(1, 'a'); - scoped_refptr<net::StringIOBuffer> buffer(new net::StringIOBuffer(data)); - net::TestCompletionCallback cb; - int rv = entry->WriteData(0, 0, buffer.get(), buffer->size(), cb.callback(), - false); - entry->Close(); - CHECK_EQ(buffer->size(), cb.GetResult(rv)); - } - { - // Make sure everything went according to plan. - net::TestCompletionCallback cb; - int rv = cache_backend->CalculateSizeOfAllEntries(cb.callback()); - CHECK_LE(1, cb.GetResult(rv)); - } - EXPECT_FALSE(precache_manager_->IsPrecaching()); - - precache_manager_->StartPrecaching(precache_callback_.GetCallback()); - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(precache_manager_->IsPrecaching()); - // Now it should be waiting for the top hosts. -} - -TEST_F(PrecacheManagerTest, StartPrecachingStopsOnSmallCaches) { - // We don't have any entry in the cache, so the reported cache_size = 0 and - // thus it will fall below the threshold of 1. - variation_params_.SetVariationParams(kPrecacheFieldTrialName, - {{kMinCacheSizeParam, "1"}}); - EXPECT_FALSE(precache_manager_->IsPrecaching()); - - precache_manager_->StartPrecaching(precache_callback_.GetCallback()); - base::RunLoop().RunUntilIdle(); - - EXPECT_FALSE(precache_manager_->IsPrecaching()); - EXPECT_TRUE(precache_callback_.was_on_done_called()); - EXPECT_TRUE(url_callback_.requested_urls().empty()); -} - -TEST_F(PrecacheManagerTest, StartAndFinishPrecachingWithUnfinishedHosts) { - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("evil-manifest.com"); - unfinished_work->set_start_time(base::Time::Now().ToInternalValue()); - precache_database_->SaveUnfinishedWork(std::move(unfinished_work)); - - EXPECT_FALSE(precache_manager_->IsPrecaching()); - - factory_.SetFakeResponse(GURL(kConfigURL), "", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse( - GURL(kEvilManifestURL), "", - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - - ASSERT_TRUE(precache_database_->GetLastPrecacheTimestamp().is_null()); - - precache_manager_->StartPrecaching(precache_callback_.GetCallback()); - EXPECT_TRUE(precache_manager_->IsPrecaching()); - - base::RunLoop().RunUntilIdle(); // For PrecacheFetcher. - EXPECT_FALSE(precache_manager_->IsPrecaching()); - EXPECT_TRUE(precache_callback_.was_on_done_called()); - - // The LastPrecacheTimestamp has been set. - EXPECT_FALSE(precache_database_->GetLastPrecacheTimestamp().is_null()); - - std::multiset<GURL> expected_requested_urls; - expected_requested_urls.insert(GURL(kConfigURL)); - expected_requested_urls.insert(GURL(kEvilManifestURL)); - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); -} - -TEST_F(PrecacheManagerTest, - StartAndCancelPrecachingBeforeUnfinishedWorkRetrieved) { - EXPECT_FALSE(precache_manager_->IsPrecaching()); - - precache_manager_->StartPrecaching(precache_callback_.GetCallback()); - EXPECT_TRUE(precache_manager_->IsPrecaching()); - precache_manager_->CancelPrecaching(); - EXPECT_FALSE(precache_manager_->IsPrecaching()); - - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(precache_callback_.was_on_done_called()); -} - -TEST_F(PrecacheManagerTest, StartAndCancelPrecachingBeforeTopHostsCompleted) { - EXPECT_FALSE(precache_manager_->IsPrecaching()); - - MockHistoryService::TopHostsCallback top_hosts_callback; - EXPECT_CALL(history_service_, TopHosts(NumTopHosts(), _)) - .WillOnce(SaveArg<1>(&top_hosts_callback)); - - precache_manager_->StartPrecaching(precache_callback_.GetCallback()); - EXPECT_TRUE(precache_manager_->IsPrecaching()); - - precache_manager_->CancelPrecaching(); - EXPECT_FALSE(precache_manager_->IsPrecaching()); - base::RunLoop().RunUntilIdle(); - - top_hosts_callback.Run( - history::TopHostsList(1, std::make_pair("starting-url.com", 1))); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(precache_manager_->IsPrecaching()); - EXPECT_FALSE(precache_callback_.was_on_done_called()); -} - -TEST_F(PrecacheManagerTest, StartAndCancelPrecachingBeforeURLsReceived) { - EXPECT_FALSE(precache_manager_->IsPrecaching()); - - MockHistoryService::TopHostsCallback top_hosts_callback; - EXPECT_CALL(history_service_, TopHosts(NumTopHosts(), _)) - .WillOnce(SaveArg<1>(&top_hosts_callback)); - - precache_manager_->StartPrecaching(precache_callback_.GetCallback()); - EXPECT_TRUE(precache_manager_->IsPrecaching()); - - precache_manager_->CancelPrecaching(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(precache_manager_->IsPrecaching()); - top_hosts_callback.Run( - history::TopHostsList(1, std::make_pair("starting-url.com", 1))); - base::RunLoop().RunUntilIdle(); // For PrecacheFetcher. - EXPECT_FALSE(precache_manager_->IsPrecaching()); - EXPECT_FALSE(precache_callback_.was_on_done_called()); - EXPECT_TRUE(url_callback_.requested_urls().empty()); -} - -TEST_F(PrecacheManagerTest, StartAndCancelPrecachingAfterURLsReceived) { - EXPECT_FALSE(precache_manager_->IsPrecaching()); - - PrecacheManifest good_manifest; - good_manifest.add_resource()->set_url("http://good-resource.com"); - - EXPECT_CALL(history_service_, TopHosts(NumTopHosts(), _)) - .WillOnce(ReturnHosts( - history::TopHostsList(1, std::make_pair("starting-url.com", 1)))); - - precache_manager_->StartPrecaching(precache_callback_.GetCallback()); - - EXPECT_TRUE(precache_manager_->IsPrecaching()); - // Run a task to get unfinished work, and to get hosts. - // We need to call run_loop.Run as many times as needed to go through the - // chain of callbacks :-(. - for (int i = 0; i < 4; ++i) { - base::RunLoop run_loop; - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - run_loop.QuitClosure()); - run_loop.Run(); - } - // base::RunLoop().RunUntilIdle(); - precache_manager_->CancelPrecaching(); - EXPECT_FALSE(precache_manager_->IsPrecaching()); - - base::RunLoop().RunUntilIdle(); // For PrecacheFetcher. - EXPECT_FALSE(precache_manager_->IsPrecaching()); - EXPECT_FALSE(precache_callback_.was_on_done_called()); - - std::multiset<GURL> expected_requested_urls; - expected_requested_urls.insert(GURL(kConfigURL)); - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); -} - -// TODO(rajendrant): Add unittests for -// PrecacheUtil::UpdatePrecacheMetricsAndState() for more test coverage. -TEST_F(PrecacheManagerTest, RecordStatsForFetchWithSizeZero) { - // Fetches with size 0 should be ignored. - RecordStatsForPrecacheFetch(GURL("http://url.com"), "", base::Time(), info_, - 0, base::Time()); - base::RunLoop().RunUntilIdle(); - histograms_.ExpectTotalCount("Precache.Freshness.Prefetch", 0); -} - -TEST_F(PrecacheManagerTest, RecordStatsForFetchWithNonHTTP) { - // Fetches for URLs with schemes other than HTTP or HTTPS should be ignored. - RecordStatsForPrecacheFetch(GURL("ftp://ftp.com"), "", base::Time(), info_, - 1000, base::Time()); - base::RunLoop().RunUntilIdle(); - histograms_.ExpectTotalCount("Precache.Freshness.Prefetch", 0); -} - -TEST_F(PrecacheManagerTest, RecordStatsForFetchWithEmptyURL) { - // Fetches for empty URLs should be ignored. - RecordStatsForPrecacheFetch(GURL(), "", base::Time(), info_, 1000, - base::Time()); - base::RunLoop().RunUntilIdle(); - histograms_.ExpectTotalCount("Precache.Freshness.Prefetch", 0); -} - -TEST_F(PrecacheManagerTest, RecordStatsForFetchDuringPrecaching) { - EXPECT_CALL(history_service_, TopHosts(NumTopHosts(), _)) - .WillOnce(ReturnHosts(history::TopHostsList())); - - precache_manager_->StartPrecaching(precache_callback_.GetCallback()); - - EXPECT_TRUE(precache_manager_->IsPrecaching()); - RecordStatsForPrecacheFetch(GURL("http://url.com"), std::string(), - base::Time(), info_, 1000, base::Time()); - base::RunLoop().RunUntilIdle(); - precache_manager_->CancelPrecaching(); - - // For PrecacheFetcher and RecordURLPrecached. - base::RunLoop().RunUntilIdle(); - EXPECT_THAT( - histograms_.GetTotalCountsForPrefix("Precache."), - UnorderedElementsAre(Pair("Precache.CacheStatus.Prefetch", 1), - Pair("Precache.CacheSize.AllEntries", 1), - Pair("Precache.DownloadedPrecacheMotivated", 1), - Pair("Precache.Fetch.PercentCompleted", 1), - Pair("Precache.Fetch.ResponseBytes.Network", 1), - Pair("Precache.Fetch.ResponseBytes.Total", 1), - Pair("Precache.Fetch.TimeToComplete", 1), - Pair("Precache.Freshness.Prefetch", 1))); -} - -TEST_F(PrecacheManagerTest, RegistersSyntheticFieldTrial) { - base::Time now = base::Time::Now(); - - EXPECT_CALL(history_service_, TopHosts(NumTopHosts(), _)) - .WillOnce(ReturnHosts(history::TopHostsList())); - EXPECT_CALL(*this, RegisterSyntheticFieldTrial(now)); - - precache_manager_->StartPrecaching(precache_callback_.GetCallback()); - - EXPECT_TRUE(precache_manager_->IsPrecaching()); - RecordStatsForPrecacheFetch(GURL("http://url.com"), std::string(), - base::Time(), info_, 1000, - now /* last_precache_time */); - base::RunLoop().RunUntilIdle(); - precache_manager_->CancelPrecaching(); -} - -TEST_F(PrecacheManagerTest, RecordStatsForFetchHTTP) { - RecordStatsForFetch(GURL("http://http-url.com"), "", base::Time(), info_, - 1000, base::Time()); - base::RunLoop().RunUntilIdle(); - - EXPECT_THAT(histograms_.GetTotalCountsForPrefix("Precache."), - UnorderedElementsAre( - Pair("Precache.DownloadedNonPrecache", 1), - Pair("Precache.CacheStatus.NonPrefetch", 1), - Pair("Precache.CacheStatus.NonPrefetch.NonTopHosts", 1))); -} - -TEST_F(PrecacheManagerTest, RecordStatsForFetchHTTPS) { - RecordStatsForFetch(GURL("https://https-url.com"), "", base::Time(), info_, - 1000, base::Time()); - base::RunLoop().RunUntilIdle(); - - EXPECT_THAT(histograms_.GetTotalCountsForPrefix("Precache."), - UnorderedElementsAre( - Pair("Precache.DownloadedNonPrecache", 1), - Pair("Precache.CacheStatus.NonPrefetch", 1), - Pair("Precache.CacheStatus.NonPrefetch.NonTopHosts", 1))); -} - -TEST_F(PrecacheManagerTest, RecordStatsForFetchInTopHosts) { - EXPECT_CALL(history_service_, - HostRankIfAvailable(GURL("http://referrer.com"), _)) - .WillOnce(Invoke( - [](const GURL& url, const base::Callback<void(int)>& callback) { - callback.Run(0); - })); - RecordStatsForFetch(GURL("http://http-url.com"), "http://referrer.com", - base::Time(), info_, 1000, base::Time()); - base::RunLoop().RunUntilIdle(); - - EXPECT_THAT(histograms_.GetTotalCountsForPrefix("Precache."), - UnorderedElementsAre( - Pair("Precache.DownloadedNonPrecache", 1), - Pair("Precache.CacheStatus.NonPrefetch", 1), - Pair("Precache.CacheStatus.NonPrefetch.TopHosts", 1))); -} - -TEST_F(PrecacheManagerTest, DeleteExpiredPrecacheHistory) { - // TODO(twifkak): Split this into multiple tests. - base::HistogramTester::CountsMap expected_histogram_count_map; - - // This test has to use Time::Now() because StartPrecaching uses Time::Now(). - const base::Time kCurrentTime = base::Time::Now(); - EXPECT_CALL(history_service_, TopHosts(NumTopHosts(), _)) - .Times(2) - .WillRepeatedly(ReturnHosts(history::TopHostsList())); - - precache_manager_->StartPrecaching(precache_callback_.GetCallback()); - EXPECT_TRUE(precache_manager_->IsPrecaching()); - - // Precache a bunch of URLs, with different fetch times. - RecordStatsForPrecacheFetch(GURL("http://old-fetch.com"), std::string(), - kCurrentTime - base::TimeDelta::FromDays(61), - info_, 1000, base::Time()); - RecordStatsForPrecacheFetch(GURL("http://recent-fetch.com"), std::string(), - kCurrentTime - base::TimeDelta::FromDays(59), - info_, 1000, base::Time()); - RecordStatsForPrecacheFetch(GURL("http://yesterday-fetch.com"), std::string(), - kCurrentTime - base::TimeDelta::FromDays(1), - info_, 1000, base::Time()); - expected_histogram_count_map["Precache.CacheStatus.Prefetch"] += 3; - expected_histogram_count_map["Precache.CacheSize.AllEntries"]++; - expected_histogram_count_map["Precache.DownloadedPrecacheMotivated"] += 3; - expected_histogram_count_map["Precache.Fetch.PercentCompleted"]++; - expected_histogram_count_map["Precache.Fetch.ResponseBytes.Network"]++; - expected_histogram_count_map["Precache.Fetch.ResponseBytes.Total"]++; - expected_histogram_count_map["Precache.Fetch.TimeToComplete"]++; - expected_histogram_count_map["Precache.Freshness.Prefetch"] += 3; - base::RunLoop().RunUntilIdle(); - - precache_manager_->CancelPrecaching(); - base::RunLoop().RunUntilIdle(); - - // Disable pause-resume. - precache_database_->DeleteUnfinishedWork(); - base::RunLoop().RunUntilIdle(); - - // For PrecacheFetcher and RecordURLPrecached. - base::RunLoop().RunUntilIdle(); - EXPECT_THAT(histograms_.GetTotalCountsForPrefix("Precache."), - ContainerEq(expected_histogram_count_map)); - - // The expired precache will be deleted during precaching this time. - precache_manager_->StartPrecaching(precache_callback_.GetCallback()); - EXPECT_TRUE(precache_manager_->IsPrecaching()); - base::RunLoop().RunUntilIdle(); - - // The precache fetcher runs until done, which records these histograms, - // and then cancels precaching, which records these histograms again. - // In practice - expected_histogram_count_map["Precache.CacheSize.AllEntries"]++; - expected_histogram_count_map["Precache.Fetch.PercentCompleted"]++; - expected_histogram_count_map["Precache.Fetch.ResponseBytes.Network"]++; - expected_histogram_count_map["Precache.Fetch.ResponseBytes.Total"]++; - // For PrecacheFetcher and RecordURLPrecached. - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(precache_manager_->IsPrecaching()); - - // A fetch for the same URL as the expired precache was served from the cache, - // but it isn't reported as saved bytes because it had expired in the precache - // history. - info_.was_cached = true; // From now on all fetches are cached. - RecordStatsForFetch(GURL("http://old-fetch.com"), "", kCurrentTime, info_, - 1000, base::Time()); - expected_histogram_count_map["Precache.Fetch.TimeToComplete"]++; - expected_histogram_count_map["Precache.CacheStatus.NonPrefetch"]++; - expected_histogram_count_map - ["Precache.CacheStatus.NonPrefetch.NonTopHosts"]++; - expected_histogram_count_map["Precache.TimeSinceLastPrecache"] += 1; - - base::RunLoop().RunUntilIdle(); - EXPECT_THAT(histograms_.GetTotalCountsForPrefix("Precache."), - ContainerEq(expected_histogram_count_map)); - - // The other precaches should not have expired, so the following fetches from - // the cache should count as saved bytes. - RecordStatsForFetch(GURL("http://recent-fetch.com"), "", kCurrentTime, info_, - 1000, base::Time()); - RecordStatsForFetch(GURL("http://yesterday-fetch.com"), "", kCurrentTime, - info_, 1000, base::Time()); - expected_histogram_count_map["Precache.CacheStatus.NonPrefetch"] += 2; - expected_histogram_count_map - ["Precache.CacheStatus.NonPrefetch.FromPrecache"] += 2; - expected_histogram_count_map - ["Precache.CacheStatus.NonPrefetch.NonTopHosts"] += 2; - expected_histogram_count_map["Precache.Saved"] += 2; - expected_histogram_count_map["Precache.TimeSinceLastPrecache"] += 2; - expected_histogram_count_map["Precache.Saved.Freshness"] = 2; - - base::RunLoop().RunUntilIdle(); - EXPECT_THAT(histograms_.GetTotalCountsForPrefix("Precache."), - ContainerEq(expected_histogram_count_map)); -} - -} // namespace precache
diff --git a/components/precache/core/BUILD.gn b/components/precache/core/BUILD.gn deleted file mode 100644 index 00bde867..0000000 --- a/components/precache/core/BUILD.gn +++ /dev/null
@@ -1,90 +0,0 @@ -# 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("//third_party/protobuf/proto_library.gni") - -# These values are duplicated in the GYP build in: -# //components/precache/precache_defines.gypi -precache_config_settings_url = - "https://www.gstatic.com/chrome/wifiprefetch/precache_config" -precache_manifest_url_prefix = - "https://www.gstatic.com/chrome/wifiprefetch/hosts/" - -config("precache_config") { - defines = [ - "PRECACHE_CONFIG_SETTINGS_URL=\"$precache_config_settings_url\"", - "PRECACHE_MANIFEST_URL_PREFIX=\"$precache_manifest_url_prefix\"", - ] -} - -static_library("core") { - sources = [ - "fetcher_pool.h", - "precache_database.cc", - "precache_database.h", - "precache_fetcher.cc", - "precache_fetcher.h", - "precache_manifest_util.cc", - "precache_manifest_util.h", - "precache_referrer_host_table.cc", - "precache_referrer_host_table.h", - "precache_session_table.cc", - "precache_session_table.h", - "precache_switches.cc", - "precache_switches.h", - "precache_url_table.cc", - "precache_url_table.h", - ] - - # Note the GYP build sets this as direct dependent settings, but this is - # only used to share the settings with the unit tests. Instead, we just - # set this config for the necessary targets manually. - configs += [ ":precache_config" ] - - deps = [ - ":proto", - "//base", - "//components/data_use_measurement/core", - "//components/history/core/browser", - "//components/prefs", - "//net", - "//sql", - "//url", - ] -} - -proto_library("proto") { - sources = [ - "proto/precache.proto", - "proto/quota.proto", - "proto/timestamp.proto", - "proto/unfinished_work.proto", - ] -} - -source_set("unit_tests") { - testonly = true - sources = [ - "fetcher_pool_unittest.cc", - "precache_database_unittest.cc", - "precache_fetcher_unittest.cc", - "precache_referrer_host_table_unittest.cc", - "precache_session_table_unittest.cc", - "precache_url_table_unittest.cc", - ] - - configs += [ ":precache_config" ] - - deps = [ - ":core", - ":proto", - "//base", - "//base/test:test_support", - "//components/history/core/browser", - "//net:test_support", - "//sql", - "//testing/gmock", - "//testing/gtest", - ] -}
diff --git a/components/precache/core/DEPS b/components/precache/core/DEPS deleted file mode 100644 index 952a6db9..0000000 --- a/components/precache/core/DEPS +++ /dev/null
@@ -1,7 +0,0 @@ -include_rules = [ - "+components/data_use_measurement/core", - "+net/base", - "+net/http", - "+net/url_request", - "+sql", -]
diff --git a/components/precache/core/fetcher_pool.h b/components/precache/core/fetcher_pool.h deleted file mode 100644 index 97cf194..0000000 --- a/components/precache/core/fetcher_pool.h +++ /dev/null
@@ -1,87 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PRECACHE_CORE_FETCHER_POOL_H_ -#define COMPONENTS_PRECACHE_CORE_FETCHER_POOL_H_ - -#include <memory> -#include <unordered_map> - -#include "base/gtest_prod_util.h" -#include "base/logging.h" - -namespace precache { - -// FetcherPool that accepts a limited number of elements. -// -// FetcherPool is particularly suited for having multiple URLFetchers running -// in parallel. -// -// It doesn't enqueue the elements above a defined capacity. The callsite must -// check for IsAvailable before calling Start. -// -// Example usage: -// std::list<GURL> pending_urls = ...; -// FetcherPool<net::URLFetcher> pool(max_parallel_fetches); -// std::function<void()> start_next_batch = -// [&pending_urls, &pool]() { -// while (!pending_urls.empty() && pool.IsAvailable()) { -// pool.Add(CreateAndStartUrlFetcher(pending_urls.front())); -// pending_urls.pop_front(); -// } -// }; -// // The URLFetcherDelegate of the created URLFetchers MUST call -// // pool.Release(url_fetcher) and start_next_batch() as part of -// // OnURLFetchComplete. -// start_next_batch(); -template <typename T> -class FetcherPool { - public: - explicit FetcherPool(size_t max_size) : max_size_(max_size){}; - virtual ~FetcherPool(){}; - - // Takes ownership and adds the given |element| to the pool. - // The element will live until its deletion. - void Add(std::unique_ptr<T> element) { - DCHECK(IsAvailable()) << "FetcherPool size exceeded. " - "Did you check IsAvailable?"; - DCHECK(element) << "The element cannot be null."; - DCHECK(elements_.find(element.get()) == elements_.end()) - << "The pool already contains the given element."; - elements_[element.get()] = std::move(element); - } - - // Deletes the given |element| from the pool. - void Delete(const T& element) { - DCHECK(elements_.find(&element) != elements_.end()) - << "The pool doesn't contain the given element."; - elements_.erase(&element); - } - - // Deletes all the elements in the pool. - void DeleteAll() { elements_.clear(); } - - // Returns true iff the pool is empty. - bool IsEmpty() const { return elements_.empty(); } - - // Returns true iff the pool can accept a new element. - bool IsAvailable() const { return max_size_ > elements_.size(); } - - const std::unordered_map<const T*, std::unique_ptr<T>>& elements() const { - return elements_; - } - - // Returns the maximum size of the pool. - size_t max_size() const { return max_size_; } - - private: - const size_t max_size_; - std::unordered_map<const T*, std::unique_ptr<T>> elements_; - - DISALLOW_COPY_AND_ASSIGN(FetcherPool); -}; - -} // namespace precache - -#endif // COMPONENTS_PRECACHE_CORE_FETCHER_POOL_H_
diff --git a/components/precache/core/fetcher_pool_unittest.cc b/components/precache/core/fetcher_pool_unittest.cc deleted file mode 100644 index f3d9de48..0000000 --- a/components/precache/core/fetcher_pool_unittest.cc +++ /dev/null
@@ -1,223 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/precache/core/fetcher_pool.h" - -#include <algorithm> -#include <array> -#include <functional> -#include <list> -#include <memory> -#include <string> - -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "base/run_loop.h" -#include "net/http/http_status_code.h" -#include "net/url_request/test_url_fetcher_factory.h" -#include "net/url_request/url_fetcher_delegate.h" -#include "net/url_request/url_request_status.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace precache { - -namespace { - -using net::FakeURLFetcher; -using net::HTTP_OK; -using net::URLFetcher; -using net::URLRequestStatus; -using ::testing::_; -using ::testing::Invoke; - -class MockURLFetcherDelegate : public net::URLFetcherDelegate { - public: - MockURLFetcherDelegate() {}; - virtual ~MockURLFetcherDelegate() {}; - - MOCK_METHOD1(OnURLFetchComplete, void(const URLFetcher*)); - MOCK_METHOD4(OnURLFetchDownloadProgress, - void(const URLFetcher* source, - int64_t current, - int64_t total, - int64_t current_network_bytes)); - MOCK_METHOD3(OnURLFetchUploadProgress, - void(const URLFetcher* source, int64_t current, int64_t total)); -}; - -TEST(FetcherPoolTest, AddDelete) { - // It also tests IsAvailable. - base::MessageLoop loop; - MockURLFetcherDelegate delegate; - std::unique_ptr<URLFetcher> url_fetcher( - new FakeURLFetcher(GURL("http://a.com"), &delegate, "irrelevant", HTTP_OK, - URLRequestStatus::SUCCESS)); - URLFetcher* url_fetcher_ptr = url_fetcher.get(); - - FetcherPool<URLFetcher> pool(1); - EXPECT_TRUE(pool.IsAvailable()); - EXPECT_TRUE(pool.IsEmpty()); - pool.Add(std::move(url_fetcher)); - url_fetcher_ptr->Start(); - EXPECT_FALSE(pool.IsAvailable()); - EXPECT_FALSE(pool.IsEmpty()); - EXPECT_CALL(delegate, OnURLFetchComplete(url_fetcher_ptr)); - - base::RunLoop().RunUntilIdle(); - - pool.Delete(*url_fetcher_ptr); - EXPECT_TRUE(pool.IsEmpty()); - EXPECT_TRUE(pool.IsAvailable()); -} - -TEST(FetcherPoolTest, Delete) { - const size_t kSize = 42; - base::MessageLoop loop; - MockURLFetcherDelegate delegate; - std::unique_ptr<URLFetcher> url_fetcher( - new FakeURLFetcher(GURL("http://a.com"), &delegate, "irrelevant", HTTP_OK, - URLRequestStatus::SUCCESS)); - URLFetcher* url_fetcher_ptr = url_fetcher.get(); - - FetcherPool<URLFetcher> pool(kSize); - pool.Add(std::move(url_fetcher)); - url_fetcher_ptr->Start(); - pool.Delete(*url_fetcher_ptr); - - EXPECT_TRUE(pool.IsEmpty()); - - EXPECT_CALL(delegate, OnURLFetchComplete(_)).Times(0); - base::RunLoop().RunUntilIdle(); -} - -TEST(FetcherPoolTest, ParallelURLFetchers) { - // It also tests IsEmpty. - const size_t kSize = 42; - base::MessageLoop loop; - MockURLFetcherDelegate delegate; - FetcherPool<URLFetcher> pool(kSize); - std::string urls[] = {"http://a.com", "http://b.com", "http://c.com"}; - // To make sure that nothing slip through while setting the expectations. - EXPECT_CALL(delegate, OnURLFetchComplete(_)).Times(0); - int num_requests_in_flight = 0; - for (const auto& url : urls) { - std::unique_ptr<URLFetcher> url_fetcher( - new FakeURLFetcher(GURL(url), &delegate, "irrelevant", HTTP_OK, - URLRequestStatus::SUCCESS)); - num_requests_in_flight++; - url_fetcher->Start(); - pool.Add(std::move(url_fetcher)); - EXPECT_FALSE(pool.IsEmpty()); - EXPECT_TRUE(pool.IsAvailable()); - } - EXPECT_CALL(delegate, OnURLFetchComplete(_)) - .Times(3) - .WillRepeatedly(Invoke([&pool](const URLFetcher* fetcher) { - EXPECT_TRUE(fetcher); - pool.Delete(*fetcher); - })); - - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(pool.IsEmpty()); - EXPECT_TRUE(pool.IsAvailable()); -} - -TEST(FetcherPoolTest, DeleteAll) { - const size_t kSize = 42; - base::MessageLoop loop; - MockURLFetcherDelegate delegate; - FetcherPool<URLFetcher> pool(kSize); - std::string urls[] = {"http://a.com", "http://b.com", "http://c.com"}; - EXPECT_CALL(delegate, OnURLFetchComplete(_)).Times(0); - for (const auto& url : urls) { - std::unique_ptr<URLFetcher> url_fetcher( - new FakeURLFetcher(GURL(url), &delegate, "irrelevant", HTTP_OK, - URLRequestStatus::SUCCESS)); - url_fetcher->Start(); - pool.Add(std::move(url_fetcher)); - } - - pool.DeleteAll(); - - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(pool.IsEmpty()); - EXPECT_TRUE(pool.IsAvailable()); -} - -#if GTEST_HAS_DEATH_TEST && !defined(NDEBUG) - -TEST(FetcherPoolTest, AddTooManyURLFetchers) { - MockURLFetcherDelegate delegate; - FetcherPool<URLFetcher> pool(0); - std::unique_ptr<URLFetcher> url_fetcher( - new FakeURLFetcher(GURL("http://queso.es"), &delegate, "irrelevant", - HTTP_OK, URLRequestStatus::SUCCESS)); - EXPECT_DEBUG_DEATH(pool.Add(std::move(url_fetcher)), - "FetcherPool size exceeded"); -} - -TEST(FetcherPoolTest, AddNullURLFetcher) { - FetcherPool<URLFetcher> pool(1); - std::unique_ptr<URLFetcher> null_ptr; - EXPECT_DEBUG_DEATH(pool.Add(std::move(null_ptr)), "cannot be null"); -} - -TEST(FetcherPoolTest, DeleteUnregisteredURLFetcher) { - MockURLFetcherDelegate delegate; - FetcherPool<URLFetcher> pool(1); - FakeURLFetcher url_fetcher(GURL("http://queso.es"), &delegate, "irrelevant", - HTTP_OK, URLRequestStatus::SUCCESS); - EXPECT_DEBUG_DEATH(pool.Delete(url_fetcher), - "doesn't contain the given element"); -} - -#endif // GTEST_HAS_DEATH_TEST && !defined(NDEBUG) - -TEST(FetcherPoolTest, ExampleUsage) { - base::MessageLoop loop; - FetcherPool<URLFetcher> pool(2); - MockURLFetcherDelegate delegate; - - std::list<GURL> pending_urls{ - {GURL("http://a.com"), GURL("http://b.com"), GURL("http://c.com")}}; - - std::function<void()> start_next_batch = [&pending_urls, &pool, &delegate]() { - while (!pending_urls.empty() && pool.IsAvailable()) { - // Called CreateAndStartUrlFetcher in the documentation. - std::unique_ptr<URLFetcher> fetcher( - new FakeURLFetcher(GURL(pending_urls.front()), &delegate, - "irrelevant", HTTP_OK, URLRequestStatus::SUCCESS)); - fetcher->Start(); - pending_urls.pop_front(); - pool.Add(std::move(fetcher)); - } - }; - - EXPECT_CALL(delegate, OnURLFetchComplete(_)).Times(0); // 3 and no more. - EXPECT_CALL(delegate, OnURLFetchComplete(_)) - .Times(pending_urls.size()) - .WillRepeatedly( - Invoke([&pool, &start_next_batch](const URLFetcher* fetcher) { - EXPECT_TRUE(fetcher); - pool.Delete(*fetcher); - start_next_batch(); - })); - - start_next_batch(); - EXPECT_FALSE(pool.IsEmpty()); - EXPECT_FALSE(pool.IsAvailable()); - - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(pool.IsEmpty()); - EXPECT_TRUE(pool.IsAvailable()); -} - -} // namespace - -} // namespace precache
diff --git a/components/precache/core/precache_database.cc b/components/precache/core/precache_database.cc deleted file mode 100644 index f30d8cb..0000000 --- a/components/precache/core/precache_database.cc +++ /dev/null
@@ -1,467 +0,0 @@ -// 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 "components/precache/core/precache_database.h" - -#include <utility> - -#include "base/bind.h" -#include "base/files/file_path.h" -#include "base/location.h" -#include "base/metrics/histogram_macros.h" -#include "base/single_thread_task_runner.h" -#include "base/threading/thread_task_runner_handle.h" -#include "base/time/time.h" -#include "components/history/core/browser/history_constants.h" -#include "components/precache/core/proto/unfinished_work.pb.h" -#include "net/http/http_response_headers.h" -#include "net/http/http_response_info.h" -#include "sql/connection.h" -#include "sql/transaction.h" -#include "url/gurl.h" - -namespace { - -// The number of days old that an entry in the precache URL table can be before -// it is considered "old" and is removed from the table. -const int kPrecacheHistoryExpiryPeriodDays = 60; - -const int kSecondsInMinute = 60; -const int kSecondsInHour = kSecondsInMinute * 60; - -} // namespace - -namespace precache { - -PrecacheDatabase::PrecacheDatabase() - : is_flush_posted_(false), weak_factory_(this) { - // A PrecacheDatabase can be constructed on any thread. - thread_checker_.DetachFromThread(); -} - -PrecacheDatabase::~PrecacheDatabase() { - // The destructor must not run on the UI thread, as it may trigger IO - // operations via sql::Connection's destructor. - DCHECK(thread_checker_.CalledOnValidThread()); -} - -bool PrecacheDatabase::Init(const base::FilePath& db_path) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(!db_); // Init must only be called once. - - db_.reset(new sql::Connection()); - db_->set_histogram_tag("Precache"); - - if (!db_->Open(db_path)) { - // Don't initialize the URL table if unable to access - // the database. - return false; - } - - if (!precache_url_table_.Init(db_.get()) || - !precache_referrer_host_table_.Init(db_.get()) || - !precache_session_table_.Init(db_.get())) { - // Raze and close the database connection to indicate that it's not usable, - // and so that the database will be created anew next time, in case it's - // corrupted. - db_->RazeAndClose(); - return false; - } - return true; -} - -void PrecacheDatabase::DeleteExpiredPrecacheHistory( - const base::Time& current_time) { - if (!IsDatabaseAccessible()) { - // Do nothing if unable to access the database. - return; - } - - // Delete old precache history that has expired. - base::Time delete_end = current_time - base::TimeDelta::FromDays( - kPrecacheHistoryExpiryPeriodDays); - buffered_writes_.push_back( - base::Bind(&PrecacheURLTable::DeleteAllPrecachedBefore, - base::Unretained(&precache_url_table_), delete_end)); - buffered_writes_.push_back( - base::Bind(&PrecacheReferrerHostTable::DeleteAllEntriesBefore, - base::Unretained(&precache_referrer_host_table_), delete_end)); - Flush(); -} - -void PrecacheDatabase::ClearHistory() { - if (!IsDatabaseAccessible()) { - // Do nothing if unable to access the database. - return; - } - - buffered_writes_.push_back(base::Bind( - &PrecacheURLTable::DeleteAll, base::Unretained(&precache_url_table_))); - buffered_writes_.push_back( - base::Bind(&PrecacheReferrerHostTable::DeleteAll, - base::Unretained(&precache_referrer_host_table_))); - Flush(); -} - -void PrecacheDatabase::SetLastPrecacheTimestamp(const base::Time& time) { - last_precache_timestamp_ = time; - - if (!IsDatabaseAccessible()) { - // Do nothing if unable to access the database. - return; - } - - buffered_writes_.push_back( - base::Bind(&PrecacheSessionTable::SetLastPrecacheTimestamp, - base::Unretained(&precache_session_table_), time)); - MaybePostFlush(); -} - -base::Time PrecacheDatabase::GetLastPrecacheTimestamp() { - if (last_precache_timestamp_.is_null() && IsDatabaseAccessible()) { - last_precache_timestamp_ = - precache_session_table_.GetLastPrecacheTimestamp(); - } - return last_precache_timestamp_; -} - -PrecacheReferrerHostEntry PrecacheDatabase::GetReferrerHost( - const std::string& referrer_host) { - DCHECK(thread_checker_.CalledOnValidThread()); - return precache_referrer_host_table_.GetReferrerHost(referrer_host); -} - -void PrecacheDatabase::GetURLListForReferrerHost( - int64_t referrer_host_id, - std::vector<GURL>* used_urls, - std::vector<GURL>* downloaded_urls) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK_NE(PrecacheReferrerHostEntry::kInvalidId, referrer_host_id); - - // Flush any pending writes to the URL and referrer host tables. - Flush(); - - precache_url_table_.GetURLListForReferrerHost(referrer_host_id, used_urls, - downloaded_urls); - precache_url_table_.SetDownloadReported(referrer_host_id); -} - -void PrecacheDatabase::RecordURLPrefetchMetrics( - const net::HttpResponseInfo& info) { - DCHECK(thread_checker_.CalledOnValidThread()); - - UMA_HISTOGRAM_ENUMERATION("Precache.CacheStatus.Prefetch", - info.cache_entry_status, - net::HttpResponseInfo::CacheEntryStatus::ENTRY_MAX); - - DCHECK(info.headers) << "The headers are required to get the freshness."; - if (info.headers) { - UMA_HISTOGRAM_CUSTOM_COUNTS( - "Precache.Freshness.Prefetch", - info.headers->GetFreshnessLifetimes(info.response_time) - .freshness.InSeconds(), - base::TimeDelta::FromMinutes(5).InSeconds() /* min */, - base::TimeDelta::FromDays(356).InSeconds() /* max */, - 100 /* bucket_count */); - } -} - -void PrecacheDatabase::RecordURLPrefetch(const GURL& url, - const std::string& referrer_host, - const base::Time& fetch_time, - bool was_cached, - int64_t size) { - DCHECK(thread_checker_.CalledOnValidThread()); - - if (!IsDatabaseAccessible()) { - // Don't track anything if unable to access the database. - return; - } - - if (buffered_urls_.find(url.spec()) != buffered_urls_.end()) { - // If the URL for this fetch is in the write buffer, then flush the write - // buffer. - Flush(); - } - - if (!was_cached) { - // The precache only counts as overhead if it was downloaded over the - // network. - UMA_HISTOGRAM_COUNTS("Precache.DownloadedPrecacheMotivated", - static_cast<base::HistogramBase::Sample>(size)); - } - - // Use the URL table to keep track of URLs. URLs that are fetched via network - // or already in the cache due to prior precaching are recorded as - // precache-motivated. URLs that came from the cache and not recorded as - // precached previously, were already in the cache because of user browsing. - // Therefore, this precache will not be considered as precache-motivated, - // since it had no significant effect (besides a possible revalidation and a - // change in the cache LRU priority). If a row for the URL already exists, - // then the timestamp is updated. - const PrecacheURLInfo info = precache_url_table_.GetURLInfo(url); - bool is_download_reported = info.is_download_reported; - if (info.is_precached && !was_cached) { - is_download_reported = false; - } - buffered_writes_.push_back( - base::Bind(&PrecacheDatabase::RecordURLPrefetchInternal, GetWeakPtr(), - url, referrer_host, !was_cached || info.is_precached, - fetch_time, is_download_reported)); - buffered_urls_.insert(url.spec()); - MaybePostFlush(); -} - -void PrecacheDatabase::RecordURLPrefetchInternal( - const GURL& url, - const std::string& referrer_host, - bool is_precached, - const base::Time& fetch_time, - bool is_download_reported) { - int64_t referrer_host_id = - precache_referrer_host_table_.GetReferrerHost(referrer_host).id; - if (referrer_host_id == PrecacheReferrerHostEntry::kInvalidId) { - referrer_host_id = precache_referrer_host_table_.UpdateReferrerHost( - referrer_host, 0, fetch_time); - } - DCHECK_NE(referrer_host_id, PrecacheReferrerHostEntry::kInvalidId); - precache_url_table_.AddURL(url, referrer_host_id, is_precached, fetch_time, - is_download_reported); -} - -void PrecacheDatabase::RecordURLNonPrefetch(const GURL& url, - const base::Time& fetch_time, - const net::HttpResponseInfo& info, - int64_t size, - int host_rank, - bool is_connection_cellular) { - UMA_HISTOGRAM_ENUMERATION("Precache.CacheStatus.NonPrefetch", - info.cache_entry_status, - net::HttpResponseInfo::CacheEntryStatus::ENTRY_MAX); - - if (host_rank != history::kMaxTopHosts) { - // The resource was loaded on a page that could have been affected by - // precaching. - UMA_HISTOGRAM_ENUMERATION( - "Precache.CacheStatus.NonPrefetch.TopHosts", info.cache_entry_status, - net::HttpResponseInfo::CacheEntryStatus::ENTRY_MAX); - } else { - // The resource was loaded on a page that could NOT have been affected by - // precaching. - UMA_HISTOGRAM_ENUMERATION( - "Precache.CacheStatus.NonPrefetch.NonTopHosts", info.cache_entry_status, - net::HttpResponseInfo::CacheEntryStatus::ENTRY_MAX); - } - - if (!IsDatabaseAccessible()) { - // Don't track anything if unable to access the database. - return; - } - - RecordTimeSinceLastPrecache(fetch_time); - - if (buffered_urls_.find(url.spec()) != buffered_urls_.end()) { - // If the URL for this fetch is in the write buffer, then flush the write - // buffer. - Flush(); - } - - const PrecacheURLInfo url_info = precache_url_table_.GetURLInfo(url); - - if (url_info.was_precached) { - UMA_HISTOGRAM_ENUMERATION( - "Precache.CacheStatus.NonPrefetch.FromPrecache", - info.cache_entry_status, - net::HttpResponseInfo::CacheEntryStatus::ENTRY_MAX); - } - - base::HistogramBase::Sample size_sample = - static_cast<base::HistogramBase::Sample>(size); - if (!info.was_cached) { - // The fetch was served over the network during user browsing, so count it - // as downloaded non-precache bytes. - UMA_HISTOGRAM_COUNTS("Precache.DownloadedNonPrecache", size_sample); - if (is_connection_cellular) { - UMA_HISTOGRAM_COUNTS("Precache.DownloadedNonPrecache.Cellular", - size_sample); - } - // Since the resource has been fetched during user browsing, mark the URL as - // used in the precache URL table, if any exists. The current fetch would - // have put this resource in the cache regardless of whether or not it was - // previously precached, so mark the URL as used. - buffered_writes_.push_back( - base::Bind(&PrecacheURLTable::SetURLAsNotPrecached, - base::Unretained(&precache_url_table_), url)); - buffered_urls_.insert(url.spec()); - MaybePostFlush(); - } else if (/* info.was_cached && */ url_info.is_precached && - !url_info.was_used) { - // The fetch was served from the cache, and since there's an entry for this - // URL in the URL table, this means that the resource was served from the - // cache only because precaching put it there. Thus, precaching was helpful, - // so count the fetch as saved bytes. - UMA_HISTOGRAM_COUNTS("Precache.Saved", size_sample); - if (is_connection_cellular) { - UMA_HISTOGRAM_COUNTS("Precache.Saved.Cellular", size_sample); - } - - DCHECK(info.headers) << "The headers are required to get the freshness."; - if (info.headers) { - // TODO(jamartin): Maybe report stale_while_validate as well. - UMA_HISTOGRAM_CUSTOM_COUNTS( - "Precache.Saved.Freshness", - info.headers->GetFreshnessLifetimes(info.response_time) - .freshness.InSeconds(), - base::TimeDelta::FromMinutes(5).InSeconds() /* min */, - base::TimeDelta::FromDays(356).InSeconds() /* max */, - 100 /* bucket_count */); - } - - buffered_writes_.push_back( - base::Bind(&PrecacheURLTable::SetPrecachedURLAsUsed, - base::Unretained(&precache_url_table_), url)); - buffered_urls_.insert(url.spec()); - MaybePostFlush(); - } -} - -void PrecacheDatabase::UpdatePrecacheReferrerHost( - const std::string& hostname, - int64_t manifest_id, - const base::Time& fetch_time) { - DCHECK(thread_checker_.CalledOnValidThread()); - - if (!IsDatabaseAccessible()) { - // Don't track anything if unable to access the database. - return; - } - - buffered_writes_.push_back( - base::Bind(&PrecacheDatabase::UpdatePrecacheReferrerHostInternal, - GetWeakPtr(), hostname, manifest_id, fetch_time)); - MaybePostFlush(); -} - -void PrecacheDatabase::UpdatePrecacheReferrerHostInternal( - const std::string& hostname, - int64_t manifest_id, - const base::Time& fetch_time) { - int64_t referrer_host_id = precache_referrer_host_table_.UpdateReferrerHost( - hostname, manifest_id, fetch_time); - - if (referrer_host_id != PrecacheReferrerHostEntry::kInvalidId) { - precache_url_table_.ClearAllForReferrerHost(referrer_host_id); - } -} - -void PrecacheDatabase::RecordTimeSinceLastPrecache( - const base::Time& fetch_time) { - const base::Time& last_precache_timestamp = GetLastPrecacheTimestamp(); - // It could still be null if the DB was not accessible. - if (!last_precache_timestamp.is_null()) { - // This is the timespan (in seconds) between the last call to - // PrecacheManager::StartPrecaching and the fetch time of a non-precache - // URL. Please note that the session started by that call to - // PrecacheManager::StartPrecaching may not have precached this particular - // URL or even any URL for that matter. - // The range was estimated to have the 95 percentile within the last bounded - // bucket. - UMA_HISTOGRAM_CUSTOM_COUNTS( - "Precache.TimeSinceLastPrecache", - (fetch_time - last_precache_timestamp).InSeconds(), kSecondsInMinute, - kSecondsInHour * 36, 100); - } -} - -bool PrecacheDatabase::IsDatabaseAccessible() const { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(db_); - - return db_->is_open(); -} - -void PrecacheDatabase::Flush() { - DCHECK(thread_checker_.CalledOnValidThread()); - if (buffered_writes_.empty()) { - // Do nothing if there's nothing to flush. - DCHECK(buffered_urls_.empty()); - return; - } - - if (IsDatabaseAccessible()) { - sql::Transaction transaction(db_.get()); - if (transaction.Begin()) { - for (std::vector<base::Closure>::const_iterator it = - buffered_writes_.begin(); - it != buffered_writes_.end(); ++it) { - it->Run(); - } - - transaction.Commit(); - } - } - - // Clear the buffer, even if the database is inaccessible or unable to begin a - // transaction. - buffered_writes_.clear(); - buffered_urls_.clear(); -} - -void PrecacheDatabase::PostedFlush() { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(is_flush_posted_); - is_flush_posted_ = false; - Flush(); -} - -void PrecacheDatabase::MaybePostFlush() { - DCHECK(thread_checker_.CalledOnValidThread()); - - if (buffered_writes_.empty() || is_flush_posted_) { - // There's no point in posting a flush if there's nothing to be flushed or - // if a flush has already been posted. - return; - } - - // Post a delayed task to flush the buffer in 1 second, so that multiple - // database writes can be buffered up and flushed together in the same - // transaction. - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&PrecacheDatabase::PostedFlush, - weak_factory_.GetWeakPtr()), - base::TimeDelta::FromSeconds(1)); - is_flush_posted_ = true; -} - -std::unique_ptr<PrecacheUnfinishedWork> -PrecacheDatabase::GetUnfinishedWork() { - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work = - precache_session_table_.GetUnfinishedWork(); - precache_session_table_.DeleteUnfinishedWork(); - return unfinished_work; -} - -void PrecacheDatabase::SaveUnfinishedWork( - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work) { - precache_session_table_.SaveUnfinishedWork( - std::move(unfinished_work)); -} - -void PrecacheDatabase::DeleteUnfinishedWork() { - precache_session_table_.DeleteUnfinishedWork(); -} - -void PrecacheDatabase::SaveQuota(const PrecacheQuota& quota) { - precache_session_table_.SaveQuota(quota); -} - -PrecacheQuota PrecacheDatabase::GetQuota() { - return precache_session_table_.GetQuota(); -} - -base::WeakPtr<PrecacheDatabase> PrecacheDatabase::GetWeakPtr() { - return weak_factory_.GetWeakPtr(); -} - -} // namespace precache
diff --git a/components/precache/core/precache_database.h b/components/precache/core/precache_database.h deleted file mode 100644 index 0597516..0000000 --- a/components/precache/core/precache_database.h +++ /dev/null
@@ -1,201 +0,0 @@ -// 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 COMPONENTS_PRECACHE_CORE_PRECACHE_DATABASE_H_ -#define COMPONENTS_PRECACHE_CORE_PRECACHE_DATABASE_H_ - -#include <stdint.h> - -#include <memory> -#include <string> -#include <vector> - -#include "base/callback.h" -#include "base/containers/hash_tables.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "components/precache/core/precache_fetcher.h" -#include "components/precache/core/precache_referrer_host_table.h" -#include "components/precache/core/precache_session_table.h" -#include "components/precache/core/precache_url_table.h" - -class GURL; - -namespace base { -class FilePath; -} - -namespace net { -class HttpResponseInfo; -} - -namespace sql { -class Connection; -} - -namespace precache { - -class PrecacheUnfinishedWork; - -// Class that tracks information related to precaching. This class may be -// constructed on any thread, but all calls to, and destruction of this class -// must be done on the the DB thread. -class PrecacheDatabase { - public: - // A PrecacheDatabase can be constructed on any thread. - PrecacheDatabase(); - - ~PrecacheDatabase(); - - // Initializes the precache database, using the specified database file path. - // Init must be called before any other methods. - bool Init(const base::FilePath& db_path); - - // Deletes precache history from the precache URL table that is more than 60 - // days older than |current_time|. - void DeleteExpiredPrecacheHistory(const base::Time& current_time); - - // Delete all history entries from the database. - void ClearHistory(); - - // Setter and getter for the last precache timestamp. - void SetLastPrecacheTimestamp(const base::Time& time); - base::Time GetLastPrecacheTimestamp(); - - // Report precache-related metrics in response to a URL being fetched, where - // the fetch was motivated by precaching. This is called from the network - // delegate, via precache_util. - void RecordURLPrefetchMetrics(const net::HttpResponseInfo& info); - - // Records the precache of an url |url| for top host |referrer_host|. This is - // called from PrecacheFetcher. - void RecordURLPrefetch(const GURL& url, - const std::string& referrer_host, - const base::Time& fetch_time, - bool was_cached, - int64_t size); - - // Report precache-related metrics in response to a URL being fetched, where - // the fetch was not motivated by precaching. |is_connection_cellular| - // indicates whether the current network connection is a cellular network. - // This is called from the network delegate, via precache_util. - void RecordURLNonPrefetch(const GURL& url, - const base::Time& fetch_time, - const net::HttpResponseInfo& info, - int64_t size, - int host_rank, - bool is_connection_cellular); - - // Returns the referrer host entry for the |referrer_host|. - PrecacheReferrerHostEntry GetReferrerHost(const std::string& referrer_host); - - // Populates the list of used and downloaded resources for referrer host with - // id |referrer_host_id|. It will also clear the reported downloaded_urls. - void GetURLListForReferrerHost(int64_t referrer_host_id, - std::vector<GURL>* used_urls, - std::vector<GURL>* downloaded_urls); - - // Updates the |manifest_id| and |fetch_time| for the referrer host - // |hostname|, and deletes the precached subresource URLs for this top host. - void UpdatePrecacheReferrerHost(const std::string& hostname, - int64_t manifest_id, - const base::Time& fetch_time); - - // Gets the state required to continue a precache session. - std::unique_ptr<PrecacheUnfinishedWork> GetUnfinishedWork(); - - // Stores the state required to continue a precache session so that the - // session can be resumed later. - void SaveUnfinishedWork( - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work); - - // Deletes unfinished work from the database. - void DeleteUnfinishedWork(); - - // Precache quota. - void SaveQuota(const PrecacheQuota& quota); - PrecacheQuota GetQuota(); - - base::WeakPtr<PrecacheDatabase> GetWeakPtr(); - - private: - friend class PrecacheDatabaseTest; - friend class PrecacheFetcherTest; - friend class PrecacheManagerTest; - - bool IsDatabaseAccessible() const; - - // Flushes any buffered write operations. |buffered_writes_| will be empty - // after calling this function. To maximize performance, all the buffered - // writes are run in a single database transaction. - void Flush(); - - // Same as Flush(), but also updates the flag |is_flush_posted_| to indicate - // that a flush is no longer posted. - void PostedFlush(); - - // Post a call to PostedFlush() on the current thread's MessageLoop, if - // |buffered_writes_| is non-empty and there isn't already a flush call - // posted. - void MaybePostFlush(); - - // Records the time since the last precache. - void RecordTimeSinceLastPrecache(const base::Time& fetch_time); - - void RecordURLPrefetchInternal(const GURL& url, - const std::string& referrer_host, - bool is_precached, - const base::Time& fetch_time, - bool is_download_reported); - - void UpdatePrecacheReferrerHostInternal(const std::string& hostname, - int64_t manifest_id, - const base::Time& fetch_time); - - std::unique_ptr<sql::Connection> db_; - - // Table that keeps track of URLs that are in the cache because of precaching, - // and wouldn't be in the cache otherwise. If |buffered_writes_| is non-empty, - // then this table will not be up to date until the next call to Flush(). - PrecacheURLTable precache_url_table_; - - // If |buffered_writes_| is non-empty, - // then this table will not be up to date until the next call to Flush(). - PrecacheReferrerHostTable precache_referrer_host_table_; - - // Table that persists state related to a precache session, including - // unfinished work to be done. - PrecacheSessionTable precache_session_table_; - - // A vector of write operations to be run on the database. - std::vector<base::Closure> buffered_writes_; - - // Set of URLs that have been modified in |buffered_writes_|. It's a hash set - // of strings, and not GURLs, because there is no hash function on GURL. - base::hash_set<std::string> buffered_urls_; - - // Flag indicating whether or not a call to Flush() has been posted to run in - // the future. - bool is_flush_posted_; - - // ThreadChecker used to ensure that all methods other than the constructor - // or destructor are called on the same thread. - base::ThreadChecker thread_checker_; - - // Time of the last precache. This is a cached copy of - // precache_session_table_.GetLastPrecacheTimestamp. - base::Time last_precache_timestamp_; - - // This must be the last member of this class. - base::WeakPtrFactory<PrecacheDatabase> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(PrecacheDatabase); -}; - -} // namespace precache - -#endif // COMPONENTS_PRECACHE_CORE_PRECACHE_DATABASE_H_
diff --git a/components/precache/core/precache_database_unittest.cc b/components/precache/core/precache_database_unittest.cc deleted file mode 100644 index 4fca60e..0000000 --- a/components/precache/core/precache_database_unittest.cc +++ /dev/null
@@ -1,685 +0,0 @@ -// 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 "components/precache/core/precache_database.h" - -#include <stdint.h> - -#include <map> -#include <memory> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/containers/hash_tables.h" -#include "base/files/file_path.h" -#include "base/files/scoped_temp_dir.h" -#include "base/message_loop/message_loop.h" -#include "base/metrics/histogram_base.h" -#include "base/test/histogram_tester.h" -#include "base/test/scoped_task_environment.h" -#include "base/time/time.h" -#include "components/history/core/browser/history_constants.h" -#include "net/http/http_response_headers.h" -#include "net/http/http_response_info.h" -#include "net/http/http_util.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace { - -using ::testing::ContainerEq; -using ::testing::ElementsAre; -using base::Bucket; -using net::HttpResponseInfo; - -const GURL kURL("http://url.com"); -const int kReferrerID = 1; -const base::Time kFetchTime = base::Time() + base::TimeDelta::FromHours(1000); -const base::Time kOldFetchTime = kFetchTime - base::TimeDelta::FromDays(1); -const base::Time kNewFetchTime = - base::Time() + base::TimeDelta::FromHours(2000); -const base::Time kPrecacheTime = - base::Time() + base::TimeDelta::FromHours(3000); -const int64_t kSize = 5000; -const int64_t kFreshnessBucket10K = 9089; -// One of the possible CacheEntryStatus for when the fetch was served from the -// network. -const HttpResponseInfo::CacheEntryStatus kFromNetwork = - HttpResponseInfo::CacheEntryStatus::ENTRY_UPDATED; - -std::map<GURL, base::Time> BuildURLTableMap(const GURL& url, - const base::Time& precache_time) { - std::map<GURL, base::Time> url_table_map; - url_table_map[url] = precache_time; - return url_table_map; -} - -HttpResponseInfo CreateHttpResponseInfo(bool was_cached, - bool network_accessed) { - HttpResponseInfo result; - result.was_cached = was_cached; - result.network_accessed = network_accessed; - if (was_cached) { - if (network_accessed) { - result.cache_entry_status = - HttpResponseInfo::CacheEntryStatus::ENTRY_VALIDATED; - } else { - result.cache_entry_status = - HttpResponseInfo::CacheEntryStatus::ENTRY_USED; - } - } else { // !was_cached. - result.cache_entry_status = kFromNetwork; - } - std::string header( - "HTTP/1.1 200 OK\n" - "cache-control: max-age=10000\n\n"); - result.headers = new net::HttpResponseHeaders( - net::HttpUtil::AssembleRawHeaders(header.c_str(), header.size())); - DCHECK_EQ( - 10000, - result.headers->GetFreshnessLifetimes(base::Time()).freshness.InSeconds()) - << "Error parsing the test headers: " << header; - return result; -} - -} // namespace - -namespace precache { - -class PrecacheDatabaseTest : public testing::Test { - public: - PrecacheDatabaseTest() - : scoped_task_environment_( - base::test::ScopedTaskEnvironment::MainThreadType::UI) {} - ~PrecacheDatabaseTest() override {} - - protected: - void SetUp() override { - precache_database_.reset(new PrecacheDatabase()); - - ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); - base::FilePath db_path = scoped_temp_dir_.GetPath().Append( - base::FilePath(FILE_PATH_LITERAL("precache_database"))); - ASSERT_TRUE(precache_database_->Init(db_path)); - } - - void TearDown() override { precache_url_table()->DeleteAll(); } - - std::map<GURL, base::Time> GetActualURLTableMap() { - // Flush any buffered writes so that the URL table will be up to date. - precache_database_->Flush(); - - std::map<GURL, base::Time> url_table_map; - precache_url_table()->GetAllDataForTesting(&url_table_map); - return url_table_map; - } - - PrecacheURLTable* precache_url_table() { - return &precache_database_->precache_url_table_; - } - - void Flush() { precache_database_->Flush(); } - - // Convenience methods for recording different types of URL fetches. These - // exist to improve the readability of the tests. - void RecordPrecacheFromNetwork(const GURL& url, - const base::Time& fetch_time, - int64_t size); - void RecordPrecacheFromCache(const GURL& url, - const base::Time& fetch_time, - int64_t size); - void RecordFetchFromNetwork(const GURL& url, - const base::Time& fetch_time, - int64_t size); - void RecordFetchFromNetwork(const GURL& url, - const base::Time& fetch_time, - int64_t size, - int host_rank); - void RecordFetchFromNetworkCellular(const GURL& url, - const base::Time& fetch_time, - int64_t size); - void RecordFetchFromCache(const GURL& url, - const base::Time& fetch_time, - int64_t size); - void RecordFetchFromCacheCellular(const GURL& url, - const base::Time& fetch_time, - int64_t size); - - // Must be declared first so that it is destroyed last. - base::ScopedTempDir scoped_temp_dir_; - - base::test::ScopedTaskEnvironment scoped_task_environment_; - - std::unique_ptr<PrecacheDatabase> precache_database_; - base::HistogramTester histograms_; - base::HistogramTester::CountsMap expected_histogram_counts_; - - void ExpectNewSample(const std::string& histogram_name, - base::HistogramBase::Sample sample) { - histograms_.ExpectUniqueSample(histogram_name, sample, 1); - expected_histogram_counts_[histogram_name]++; - } - - void ExpectNoOtherSamples() { - EXPECT_THAT(histograms_.GetTotalCountsForPrefix("Precache."), - ContainerEq(expected_histogram_counts_)); - } -}; - -void PrecacheDatabaseTest::RecordPrecacheFromNetwork( - const GURL& url, - const base::Time& fetch_time, - int64_t size) { - const HttpResponseInfo info = CreateHttpResponseInfo( - false /* was_cached */, false /* network_accessed */); - precache_database_->RecordURLPrefetchMetrics(info); - precache_database_->RecordURLPrefetch(url, std::string(), fetch_time, - info.was_cached, size); -} - -void PrecacheDatabaseTest::RecordPrecacheFromCache(const GURL& url, - const base::Time& fetch_time, - int64_t size) { - const HttpResponseInfo info = CreateHttpResponseInfo( - true /* was_cached */, false /* network_accessed */); - precache_database_->RecordURLPrefetchMetrics(info); - precache_database_->RecordURLPrefetch(url, std::string(), fetch_time, - info.was_cached, size); -} - -void PrecacheDatabaseTest::RecordFetchFromNetwork(const GURL& url, - const base::Time& fetch_time, - int64_t size) { - const HttpResponseInfo info = CreateHttpResponseInfo( - false /* was_cached */, false /* network_accessed */); - precache_database_->RecordURLNonPrefetch(url, fetch_time, info, size, - history::kMaxTopHosts, - false /* is_connection_cellular */); -} - -void PrecacheDatabaseTest::RecordFetchFromNetwork(const GURL& url, - const base::Time& fetch_time, - int64_t size, - int host_rank) { - const HttpResponseInfo info = CreateHttpResponseInfo( - false /* was_cached */, false /* network_accessed */); - precache_database_->RecordURLNonPrefetch(url, fetch_time, info, size, - host_rank, - false /* is_connection_cellular */); -} - -void PrecacheDatabaseTest::RecordFetchFromNetworkCellular( - const GURL& url, - const base::Time& fetch_time, - int64_t size) { - const HttpResponseInfo info = CreateHttpResponseInfo( - false /* was_cached */, false /* network_accessed */); - precache_database_->RecordURLNonPrefetch(url, fetch_time, info, size, - history::kMaxTopHosts, - true /* is_connection_cellular */); -} - -void PrecacheDatabaseTest::RecordFetchFromCache(const GURL& url, - const base::Time& fetch_time, - int64_t size) { - const HttpResponseInfo info = CreateHttpResponseInfo( - true /* was_cached */, false /* network_accessed */); - precache_database_->RecordURLNonPrefetch(url, fetch_time, info, size, - history::kMaxTopHosts, - false /* is_connection_cellular */); -} - -void PrecacheDatabaseTest::RecordFetchFromCacheCellular( - const GURL& url, - const base::Time& fetch_time, - int64_t size) { - const HttpResponseInfo info = CreateHttpResponseInfo( - true /* was_cached */, false /* network_accessed */); - precache_database_->RecordURLNonPrefetch(url, fetch_time, info, size, - history::kMaxTopHosts, - true /* is_connection_cellular */); -} - -namespace { - -TEST_F(PrecacheDatabaseTest, PrecacheOverNetwork) { - RecordPrecacheFromNetwork(kURL, kFetchTime, kSize); - - EXPECT_EQ(BuildURLTableMap(kURL, kFetchTime), GetActualURLTableMap()); - - ExpectNewSample("Precache.DownloadedPrecacheMotivated", kSize); - ExpectNewSample("Precache.CacheStatus.Prefetch", kFromNetwork); - ExpectNewSample("Precache.Freshness.Prefetch", kFreshnessBucket10K); - ExpectNoOtherSamples(); -} - -TEST_F(PrecacheDatabaseTest, PrecacheFromCacheWithURLTableEntry) { - precache_url_table()->AddURL(kURL, kReferrerID, true, kOldFetchTime, false); - RecordPrecacheFromCache(kURL, kFetchTime, kSize); - - // The URL table entry should have been updated to have |kFetchTime| as the - // timestamp. - EXPECT_EQ(BuildURLTableMap(kURL, kFetchTime), GetActualURLTableMap()); - - ExpectNewSample("Precache.CacheStatus.Prefetch", - net::HttpResponseInfo::ENTRY_USED); - ExpectNewSample("Precache.Freshness.Prefetch", kFreshnessBucket10K); - ExpectNoOtherSamples(); -} - -TEST_F(PrecacheDatabaseTest, PrecacheFromCacheWithoutURLTableEntry) { - RecordPrecacheFromCache(kURL, kFetchTime, kSize); - - EXPECT_TRUE(GetActualURLTableMap().empty()); - - ExpectNewSample("Precache.CacheStatus.Prefetch", - net::HttpResponseInfo::ENTRY_USED); - ExpectNewSample("Precache.Freshness.Prefetch", kFreshnessBucket10K); - ExpectNoOtherSamples(); -} - -TEST_F(PrecacheDatabaseTest, FetchOverNetwork_NonCellular) { - RecordFetchFromNetwork(kURL, kFetchTime, kSize); - - EXPECT_TRUE(GetActualURLTableMap().empty()); - - ExpectNewSample("Precache.DownloadedNonPrecache", kSize); - ExpectNewSample("Precache.CacheStatus.NonPrefetch", kFromNetwork); - ExpectNewSample("Precache.CacheStatus.NonPrefetch.NonTopHosts", kFromNetwork); - ExpectNoOtherSamples(); -} - -TEST_F(PrecacheDatabaseTest, FetchOverNetwork_NonCellular_TopHosts) { - RecordFetchFromNetwork(kURL, kFetchTime, kSize, 0 /* host_rank */); - - EXPECT_TRUE(GetActualURLTableMap().empty()); - - ExpectNewSample("Precache.DownloadedNonPrecache", kSize); - ExpectNewSample("Precache.CacheStatus.NonPrefetch", kFromNetwork); - ExpectNewSample("Precache.CacheStatus.NonPrefetch.TopHosts", kFromNetwork); - ExpectNoOtherSamples(); -} - -TEST_F(PrecacheDatabaseTest, FetchOverNetwork_Cellular) { - RecordFetchFromNetworkCellular(kURL, kFetchTime, kSize); - - EXPECT_TRUE(GetActualURLTableMap().empty()); - - ExpectNewSample("Precache.DownloadedNonPrecache", kSize); - ExpectNewSample("Precache.DownloadedNonPrecache.Cellular", kSize); - ExpectNewSample("Precache.CacheStatus.NonPrefetch", kFromNetwork); - ExpectNewSample("Precache.CacheStatus.NonPrefetch.NonTopHosts", kFromNetwork); - ExpectNoOtherSamples(); -} - -TEST_F(PrecacheDatabaseTest, FetchOverNetworkWithURLTableEntry) { - precache_url_table()->AddURL(kURL, kReferrerID, true, kOldFetchTime, false); - RecordFetchFromNetwork(kURL, kFetchTime, kSize); - - // The URL table entry should have been deleted. - EXPECT_TRUE(GetActualURLTableMap().empty()); - - ExpectNewSample("Precache.DownloadedNonPrecache", kSize); - ExpectNewSample("Precache.CacheStatus.NonPrefetch", kFromNetwork); - ExpectNewSample("Precache.CacheStatus.NonPrefetch.FromPrecache", - kFromNetwork); - ExpectNewSample("Precache.CacheStatus.NonPrefetch.NonTopHosts", kFromNetwork); - ExpectNoOtherSamples(); -} - -TEST_F(PrecacheDatabaseTest, FetchFromCacheWithURLTableEntry_NonCellular) { - precache_url_table()->AddURL(kURL, kReferrerID, true, kOldFetchTime, false); - RecordFetchFromCache(kURL, kFetchTime, kSize); - - // The URL table entry should have been deleted. - EXPECT_TRUE(GetActualURLTableMap().empty()); - - ExpectNewSample("Precache.CacheStatus.NonPrefetch", - HttpResponseInfo::CacheEntryStatus::ENTRY_USED); - ExpectNewSample("Precache.CacheStatus.NonPrefetch.FromPrecache", - HttpResponseInfo::CacheEntryStatus::ENTRY_USED); - ExpectNewSample("Precache.CacheStatus.NonPrefetch.NonTopHosts", - HttpResponseInfo::CacheEntryStatus::ENTRY_USED); - ExpectNewSample("Precache.Saved", kSize); - ExpectNewSample("Precache.Saved.Freshness", kFreshnessBucket10K); - ExpectNoOtherSamples(); -} - -TEST_F(PrecacheDatabaseTest, FetchFromCacheWithURLTableEntry_Cellular) { - precache_url_table()->AddURL(kURL, kReferrerID, true, kOldFetchTime, false); - RecordFetchFromCacheCellular(kURL, kFetchTime, kSize); - - // The URL table entry should have been deleted. - EXPECT_TRUE(GetActualURLTableMap().empty()); - - ExpectNewSample("Precache.CacheStatus.NonPrefetch", - HttpResponseInfo::CacheEntryStatus::ENTRY_USED); - ExpectNewSample("Precache.CacheStatus.NonPrefetch.FromPrecache", - HttpResponseInfo::CacheEntryStatus::ENTRY_USED); - ExpectNewSample("Precache.CacheStatus.NonPrefetch.NonTopHosts", - HttpResponseInfo::CacheEntryStatus::ENTRY_USED); - ExpectNewSample("Precache.Saved", kSize); - ExpectNewSample("Precache.Saved.Cellular", kSize); - ExpectNewSample("Precache.Saved.Freshness", kFreshnessBucket10K); - ExpectNoOtherSamples(); -} - -TEST_F(PrecacheDatabaseTest, FetchFromCacheWithoutURLTableEntry) { - RecordFetchFromCache(kURL, kFetchTime, kSize); - - EXPECT_TRUE(GetActualURLTableMap().empty()); - - ExpectNewSample("Precache.CacheStatus.NonPrefetch", - HttpResponseInfo::CacheEntryStatus::ENTRY_USED); - ExpectNewSample("Precache.CacheStatus.NonPrefetch.NonTopHosts", - HttpResponseInfo::CacheEntryStatus::ENTRY_USED); - ExpectNoOtherSamples(); -} - -TEST_F(PrecacheDatabaseTest, DeleteExpiredPrecacheHistory) { - const base::Time kToday = base::Time() + base::TimeDelta::FromDays(1000); - const base::Time k59DaysAgo = kToday - base::TimeDelta::FromDays(59); - const base::Time k61DaysAgo = kToday - base::TimeDelta::FromDays(61); - - precache_url_table()->AddURL(GURL("http://expired-precache.com"), kReferrerID, - true, k61DaysAgo, false); - precache_url_table()->AddURL(GURL("http://old-precache.com"), kReferrerID, - true, k59DaysAgo, false); - - precache_database_->DeleteExpiredPrecacheHistory(kToday); - - EXPECT_EQ(BuildURLTableMap(GURL("http://old-precache.com"), k59DaysAgo), - GetActualURLTableMap()); -} - -TEST_F(PrecacheDatabaseTest, SampleInteraction) { - const GURL kURL1("http://url1.com"); - const int64_t kSize1 = 1; - const GURL kURL2("http://url2.com"); - const int64_t kSize2 = 2; - const GURL kURL3("http://url3.com"); - const int64_t kSize3 = 3; - const GURL kURL4("http://url4.com"); - const int64_t kSize4 = 4; - const GURL kURL5("http://url5.com"); - const int64_t kSize5 = 5; - - RecordPrecacheFromNetwork(kURL1, kFetchTime, kSize1); - RecordPrecacheFromNetwork(kURL2, kFetchTime, kSize2); - RecordPrecacheFromNetwork(kURL3, kFetchTime, kSize3); - RecordPrecacheFromNetwork(kURL4, kFetchTime, kSize4); - - RecordFetchFromCacheCellular(kURL1, kFetchTime, kSize1); - RecordFetchFromCacheCellular(kURL1, kFetchTime, kSize1); - RecordFetchFromNetworkCellular(kURL2, kFetchTime, kSize2); - RecordFetchFromNetworkCellular(kURL5, kFetchTime, kSize5); - RecordFetchFromCacheCellular(kURL5, kFetchTime, kSize5); - - RecordPrecacheFromCache(kURL1, kFetchTime, kSize1); - RecordPrecacheFromNetwork(kURL2, kFetchTime, kSize2); - RecordPrecacheFromCache(kURL3, kFetchTime, kSize3); - RecordPrecacheFromCache(kURL4, kFetchTime, kSize4); - - RecordFetchFromCache(kURL1, kFetchTime, kSize1); - RecordFetchFromNetwork(kURL2, kFetchTime, kSize2); - RecordFetchFromCache(kURL3, kFetchTime, kSize3); - RecordFetchFromCache(kURL5, kFetchTime, kSize5); - - EXPECT_THAT(histograms_.GetAllSamples("Precache.DownloadedPrecacheMotivated"), - ElementsAre(Bucket(kSize1, 1), Bucket(kSize2, 2), - Bucket(kSize3, 1), Bucket(kSize4, 1))); - - EXPECT_THAT(histograms_.GetAllSamples("Precache.DownloadedNonPrecache"), - ElementsAre(Bucket(kSize2, 2), Bucket(kSize5, 1))); - - EXPECT_THAT( - histograms_.GetAllSamples("Precache.DownloadedNonPrecache.Cellular"), - ElementsAre(Bucket(kSize2, 1), Bucket(kSize5, 1))); - - EXPECT_THAT( - histograms_.GetAllSamples("Precache.CacheStatus.Prefetch"), - ElementsAre( - Bucket(HttpResponseInfo::CacheEntryStatus::ENTRY_USED, 3), - Bucket(HttpResponseInfo::CacheEntryStatus::ENTRY_UPDATED, 5))); - - EXPECT_THAT( - histograms_.GetAllSamples("Precache.CacheStatus.NonPrefetch"), - ElementsAre( - Bucket(HttpResponseInfo::CacheEntryStatus::ENTRY_USED, 6), - Bucket(HttpResponseInfo::CacheEntryStatus::ENTRY_UPDATED, 3))); - - EXPECT_THAT(histograms_.GetAllSamples("Precache.Saved"), - ElementsAre(Bucket(kSize1, 1), Bucket(kSize3, 1))); - - EXPECT_THAT(histograms_.GetAllSamples("Precache.Saved.Cellular"), - ElementsAre(Bucket(kSize1, 1))); -} - -TEST_F(PrecacheDatabaseTest, LastPrecacheTimestamp) { - // So that it starts recording TimeSinceLastPrecache. - const base::Time kStartTime = - base::Time() + base::TimeDelta::FromSeconds(100); - precache_database_->SetLastPrecacheTimestamp(kStartTime); - - RecordPrecacheFromNetwork(kURL, kStartTime, kSize); - RecordPrecacheFromNetwork(kURL, kStartTime, kSize); - RecordPrecacheFromNetwork(kURL, kStartTime, kSize); - RecordPrecacheFromNetwork(kURL, kStartTime, kSize); - - EXPECT_THAT(histograms_.GetAllSamples("Precache.TimeSinceLastPrecache"), - ElementsAre()); - - const base::Time kTimeA = kStartTime + base::TimeDelta::FromSeconds(7); - const base::Time kTimeB = kStartTime + base::TimeDelta::FromMinutes(42); - const base::Time kTimeC = kStartTime + base::TimeDelta::FromHours(20); - - RecordFetchFromCacheCellular(kURL, kTimeA, kSize); - RecordFetchFromCacheCellular(kURL, kTimeA, kSize); - RecordFetchFromNetworkCellular(kURL, kTimeB, kSize); - RecordFetchFromNetworkCellular(kURL, kTimeB, kSize); - RecordFetchFromCacheCellular(kURL, kTimeB, kSize); - RecordFetchFromCacheCellular(kURL, kTimeC, kSize); - - EXPECT_THAT(histograms_.GetAllSamples("Precache.TimeSinceLastPrecache"), - ElementsAre(Bucket(0, 2), Bucket(2406, 3), Bucket(69347, 1))); -} - -TEST_F(PrecacheDatabaseTest, PrecacheFreshnessPrefetch) { - auto info = CreateHttpResponseInfo(false /* was_cached */, - false /* network_accessed */); - RecordPrecacheFromNetwork(kURL, kFetchTime, kSize); - - EXPECT_THAT(histograms_.GetAllSamples("Precache.Freshness.Prefetch"), - ElementsAre(Bucket(kFreshnessBucket10K, 1))); -} - -TEST_F(PrecacheDatabaseTest, UpdateAndGetReferrerHost) { - // Invalid ID should be returned for referrer host that does not exist. - EXPECT_EQ(PrecacheReferrerHostEntry::kInvalidId, - precache_database_->GetReferrerHost(std::string()).id); - EXPECT_EQ(PrecacheReferrerHostEntry::kInvalidId, - precache_database_->GetReferrerHost("not_created_host.com").id); - - // Create a new entry. - precache_database_->UpdatePrecacheReferrerHost("foo.com", 1, kFetchTime); - Flush(); - auto actual_entry = precache_database_->GetReferrerHost("foo.com"); - EXPECT_EQ("foo.com", actual_entry.referrer_host); - EXPECT_EQ(1, actual_entry.manifest_id); - EXPECT_EQ(kFetchTime, actual_entry.time); - - // Update the existing entry. - precache_database_->UpdatePrecacheReferrerHost("foo.com", 2, kNewFetchTime); - Flush(); - actual_entry = precache_database_->GetReferrerHost("foo.com"); - EXPECT_EQ("foo.com", actual_entry.referrer_host); - EXPECT_EQ(2, actual_entry.manifest_id); - EXPECT_EQ(kNewFetchTime, actual_entry.time); -} - -TEST_F(PrecacheDatabaseTest, GetURLListForReferrerHost) { - precache_database_->UpdatePrecacheReferrerHost("foo.com", 1, kFetchTime); - precache_database_->UpdatePrecacheReferrerHost("bar.com", 2, kNewFetchTime); - precache_database_->UpdatePrecacheReferrerHost("foobar.com", 3, - kNewFetchTime); - precache_database_->UpdatePrecacheReferrerHost("empty.com", 3, kNewFetchTime); - - struct test_resource_info { - std::string url; - bool is_user_browsed; - bool is_network_fetched; - bool is_cellular_fetched; - bool expected_in_used; - }; - - const struct { - std::string hostname; - std::vector<test_resource_info> resource_info; - } tests[] = { - { - "foo.com", - { - {"http://foo.com/from-cache.js", true, false, false, true}, - {"http://some-cdn.com/from-network.js", true, true, false, false}, - {"http://foo.com/from-cache-cellular.js", true, false, true, - true}, - {"http://foo.com/from-network-cellular.js", true, true, true, - false}, - {"http://foo.com/not-browsed.js", false, false, false, false}, - }, - }, - { - "bar.com", - { - {"http://bar.com/a.js", true, false, false, true}, - {"http://some-cdn.com/b.js", true, false, true, true}, - {"http://bar.com/not-browsed.js", false, false, false, false}, - }, - }, - { - "foobar.com", - { - {"http://some-cdn.com/not-used.js", true, true, true, false}, - }, - }, - { - "empty.com", std::vector<test_resource_info>{}, - }, - }; - // Add precached resources. - for (const auto& test : tests) { - for (const auto& resource : test.resource_info) { - precache_database_->RecordURLPrefetch(GURL(resource.url), test.hostname, - kPrecacheTime, false, kSize); - } - } - // Update some resources as used due to user browsing. - for (const auto& test : tests) { - for (const auto& resource : test.resource_info) { - if (!resource.is_user_browsed) - continue; - if (!resource.is_network_fetched && !resource.is_cellular_fetched) { - RecordFetchFromCache(GURL(resource.url), kFetchTime, kSize); - } else if (!resource.is_network_fetched && resource.is_cellular_fetched) { - RecordFetchFromCacheCellular(GURL(resource.url), kFetchTime, kSize); - } else if (resource.is_network_fetched && !resource.is_cellular_fetched) { - RecordFetchFromNetwork(GURL(resource.url), kFetchTime, kSize); - } else if (resource.is_network_fetched && resource.is_cellular_fetched) { - RecordFetchFromNetworkCellular(GURL(resource.url), kFetchTime, kSize); - } - } - } - Flush(); - // Verify the used and downloaded resources. - for (const auto& test : tests) { - std::vector<GURL> expected_used_urls, expected_downloaded_urls; - for (const auto& resource : test.resource_info) { - if (resource.expected_in_used) { - expected_used_urls.push_back(GURL(resource.url)); - } - expected_downloaded_urls.push_back(GURL(resource.url)); - } - std::vector<GURL> actual_used_urls, actual_downloaded_urls; - auto referrer_id = precache_database_->GetReferrerHost(test.hostname).id; - EXPECT_NE(PrecacheReferrerHostEntry::kInvalidId, referrer_id); - precache_database_->GetURLListForReferrerHost( - referrer_id, &actual_used_urls, &actual_downloaded_urls); - EXPECT_THAT(actual_used_urls, ::testing::ContainerEq(expected_used_urls)); - EXPECT_THAT(actual_downloaded_urls, - ::testing::ContainerEq(expected_downloaded_urls)) - << "Host: " << test.hostname; - } - // Subsequent manifest updates should clear the used and downloaded resources. - for (const auto& test : tests) { - precache_database_->UpdatePrecacheReferrerHost(test.hostname, 100, - kNewFetchTime); - Flush(); - std::vector<GURL> actual_used_urls, actual_downloaded_urls; - auto referrer_id = precache_database_->GetReferrerHost(test.hostname).id; - EXPECT_NE(PrecacheReferrerHostEntry::kInvalidId, referrer_id); - precache_database_->GetURLListForReferrerHost( - referrer_id, &actual_used_urls, &actual_downloaded_urls); - EXPECT_THAT(actual_used_urls, ::testing::IsEmpty()); - EXPECT_THAT(actual_downloaded_urls, ::testing::IsEmpty()); - } - // Resources that were precached previously and not seen in user browsing - // should be still marked as precached. - std::map<GURL, base::Time> expected_url_table_map; - for (const auto& test : tests) { - for (const auto& resource : test.resource_info) { - if (!resource.is_user_browsed) - expected_url_table_map[GURL(resource.url)] = kPrecacheTime; - } - } - EXPECT_EQ(expected_url_table_map, GetActualURLTableMap()); -} - -TEST_F(PrecacheDatabaseTest, GetURLListForReferrerHostReportsDownloadedOnce) { - precache_database_->UpdatePrecacheReferrerHost("foo.com", 1, kFetchTime); - // Add two resources that shouldn't appear in downloaded. - Flush(); // We need to write the referrer_host_id. - const std::string already_reported_and_not_refetch = - "http://foo.com/already-reported-and-not-refetch.js"; - precache_database_->RecordURLPrefetch(GURL(already_reported_and_not_refetch), - "foo.com", kPrecacheTime, false, kSize); - const std::string already_reported_and_in_cache = - "http://foo.com/already-reported-and-in-cache.js"; - precache_database_->RecordURLPrefetch(GURL(already_reported_and_in_cache), - "foo.com", kPrecacheTime, false, kSize); - const std::string already_reported_but_refetch = - "http://foo.com/already-reported-but-refetch.js"; - precache_database_->RecordURLPrefetch(GURL(already_reported_but_refetch), - "foo.com", kPrecacheTime, false, kSize); - { - // Let's mark existing resources as is_download_reported = 1 by calling - // GetURLListForReferrerHost. - std::vector<GURL> unused_a, unused_b; - auto id = precache_database_->GetReferrerHost("foo.com").id; - ASSERT_NE(PrecacheReferrerHostEntry::kInvalidId, id); - precache_database_->GetURLListForReferrerHost(id, &unused_a, &unused_b); - } - - precache_database_->RecordURLPrefetch(GURL(already_reported_and_in_cache), - "foo.com", kPrecacheTime, - true /* was_cached */, kSize); - precache_database_->RecordURLPrefetch(GURL(already_reported_but_refetch), - "foo.com", kPrecacheTime, - false /* was_cached */, kSize); - Flush(); - - // Only the refetch resource should be reported as downloaded this time - // around. - std::vector<GURL> _, actual_downloaded_urls; - auto referrer_id = precache_database_->GetReferrerHost("foo.com").id; - EXPECT_NE(PrecacheReferrerHostEntry::kInvalidId, referrer_id); - precache_database_->GetURLListForReferrerHost(referrer_id, &_, - &actual_downloaded_urls); - EXPECT_THAT(actual_downloaded_urls, - ElementsAre(GURL(already_reported_but_refetch))); -} - -} // namespace - -} // namespace precache
diff --git a/components/precache/core/precache_fetcher.cc b/components/precache/core/precache_fetcher.cc deleted file mode 100644 index 00766ad..0000000 --- a/components/precache/core/precache_fetcher.cc +++ /dev/null
@@ -1,971 +0,0 @@ -// 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 "components/precache/core/precache_fetcher.h" - -#include <algorithm> -#include <limits> -#include <set> -#include <utility> -#include <vector> - -#include "base/base64.h" -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" -#include "base/command_line.h" -#include "base/compiler_specific.h" -#include "base/containers/hash_tables.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/memory/ref_counted.h" -#include "base/metrics/histogram_macros.h" -#include "base/optional.h" -#include "base/sha1.h" -#include "base/strings/string_piece.h" -#include "base/task_runner_util.h" -#include "components/data_use_measurement/core/data_use_user_data.h" -#include "components/precache/core/precache_database.h" -#include "components/precache/core/precache_manifest_util.h" -#include "components/precache/core/precache_switches.h" -#include "components/precache/core/proto/quota.pb.h" -#include "components/precache/core/proto/unfinished_work.pb.h" -#include "net/base/completion_callback.h" -#include "net/base/escape.h" -#include "net/base/io_buffer.h" -#include "net/base/load_flags.h" -#include "net/base/net_errors.h" -#include "net/base/url_util.h" -#include "net/http/http_response_headers.h" -#include "net/url_request/url_fetcher_response_writer.h" -#include "net/url_request/url_request_context_getter.h" -#include "net/url_request/url_request_status.h" - -namespace precache { - -// The following flags are for privacy reasons. For example, if a user clears -// their cookies, but a tracking beacon is prefetched and the beacon specifies -// its source URL in a URL param, the beacon site would be able to rebuild a -// profile of the user. All three flags should occur together, or not at all, -// per -// https://groups.google.com/a/chromium.org/d/topic/net-dev/vvcodRV6SdM/discussion. -const int kNoTracking = - net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | - net::LOAD_DO_NOT_SEND_AUTH_DATA; - -// The maximum number of URLFetcher requests that can be in flight in parallel. -// Note that OnManifestFetchComplete and OnResourceFetchComplete perform -// remove_if operations which are O(kMaxParallelFetches). Those should be -// optimized before increasing this value significantly. -const int kMaxParallelFetches = 10; - -namespace { - -// The maximum for the Precache.Fetch.ResponseBytes.* histograms. We set this to -// a number we expect to be in the 99th percentile for the histogram, give or -// take. -const int kMaxResponseBytes = 500 * 1024 * 1024; - -GURL GetDefaultConfigURL() { - const base::CommandLine& command_line = - *base::CommandLine::ForCurrentProcess(); - if (command_line.HasSwitch(switches::kPrecacheConfigSettingsURL)) { - return GURL( - command_line.GetSwitchValueASCII(switches::kPrecacheConfigSettingsURL)); - } - -#if defined(PRECACHE_CONFIG_SETTINGS_URL) - return GURL(PRECACHE_CONFIG_SETTINGS_URL); -#else - // The precache config settings URL could not be determined, so return an - // empty, invalid GURL. - return GURL(); -#endif -} - -std::string GetDefaultManifestURLPrefix() { - const base::CommandLine& command_line = - *base::CommandLine::ForCurrentProcess(); - if (command_line.HasSwitch(switches::kPrecacheManifestURLPrefix)) { - return command_line.GetSwitchValueASCII( - switches::kPrecacheManifestURLPrefix); - } - -#if defined(PRECACHE_MANIFEST_URL_PREFIX) - return PRECACHE_MANIFEST_URL_PREFIX; -#else - // The precache manifest URL prefix could not be determined, so return an - // empty string. - return std::string(); -#endif -} - -// Attempts to parse a protobuf message from the response string of a -// URLFetcher. If parsing is successful, the message parameter will contain the -// parsed protobuf and this function will return true. Otherwise, returns false. -bool ParseProtoFromFetchResponse(const net::URLFetcher& source, - ::google::protobuf::MessageLite* message) { - std::string response_string; - - if (!source.GetStatus().is_success()) { - DLOG(WARNING) << "Fetch failed: " << source.GetOriginalURL().spec(); - return false; - } - if (!source.GetResponseAsString(&response_string)) { - DLOG(WARNING) << "No response string present: " - << source.GetOriginalURL().spec(); - return false; - } - if (!message->ParseFromString(response_string)) { - DLOG(WARNING) << "Unable to parse proto served from " - << source.GetOriginalURL().spec(); - return false; - } - return true; -} - -// URLFetcherResponseWriter that ignores the response body, in order to avoid -// the unnecessary memory usage. Use it rather than the default if you don't -// care about parsing the response body. We use it below as a means to populate -// the cache with requested resource URLs. -class URLFetcherNullWriter : public net::URLFetcherResponseWriter { - public: - int Initialize(const net::CompletionCallback& callback) override { - return net::OK; - } - - int Write(net::IOBuffer* buffer, - int num_bytes, - const net::CompletionCallback& callback) override { - return num_bytes; - } - - int Finish(int net_error, const net::CompletionCallback& callback) override { - return net::OK; - } -}; - -// Returns the base64 encoded resource URL hashes. The resource URLs are hashed -// individually, and 8 bytes of each hash is appended together, which is then -// encoded to base64. -std::string GetResourceURLBase64Hash(const std::vector<GURL>& urls) { - // Each resource hash uses 8 bytes, instead of the 20 bytes of sha1 hash, as a - // tradeoff between sending more bytes and reducing hash collisions. - const size_t kHashBytesSize = 8; - std::string hashes; - hashes.reserve(urls.size() * kHashBytesSize); - - for (const auto& url : urls) { - const std::string& url_spec = url.spec(); - unsigned char sha1_hash[base::kSHA1Length]; - base::SHA1HashBytes( - reinterpret_cast<const unsigned char*>(url_spec.c_str()), - url_spec.size(), sha1_hash); - hashes.append(reinterpret_cast<const char*>(sha1_hash), kHashBytesSize); - } - base::Base64Encode(hashes, &hashes); - return hashes; -} - -// Retrieves the manifest info on the DB thread. Manifest info for each of the -// hosts in |hosts_to_fetch|, is added to |hosts_info|. -std::deque<ManifestHostInfo> RetrieveManifestInfo( - const base::WeakPtr<PrecacheDatabase>& precache_database, - std::vector<std::pair<std::string, int64_t>> hosts_to_fetch) { - std::deque<ManifestHostInfo> hosts_info; - if (!precache_database) - return hosts_info; - - for (const auto& host : hosts_to_fetch) { - auto referrer_host_info = precache_database->GetReferrerHost(host.first); - if (referrer_host_info.id != PrecacheReferrerHostEntry::kInvalidId) { - std::vector<GURL> used_urls, downloaded_urls; - precache_database->GetURLListForReferrerHost( - referrer_host_info.id, &used_urls, &downloaded_urls); - hosts_info.push_back( - ManifestHostInfo(referrer_host_info.manifest_id, host.first, - host.second, GetResourceURLBase64Hash(used_urls), - GetResourceURLBase64Hash(downloaded_urls))); - } else { - hosts_info.push_back( - ManifestHostInfo(PrecacheReferrerHostEntry::kInvalidId, host.first, - host.second, std::string(), std::string())); - } - } - return hosts_info; -} - -PrecacheQuota RetrieveQuotaInfo( - const base::WeakPtr<PrecacheDatabase>& precache_database) { - PrecacheQuota quota; - if (precache_database) { - quota = precache_database->GetQuota(); - } - return quota; -} - -// Returns true if the |quota| time has expired. -bool IsQuotaTimeExpired(const PrecacheQuota& quota, - const base::Time& time_now) { - // Quota expires one day after the start time. - base::Time start_time = base::Time::FromInternalValue(quota.start_time()); - return start_time > time_now || - start_time + base::TimeDelta::FromDays(1) < time_now; -} - -// Models the expected number of requests for the resource, given that -// resource_weight_ratio is the probability of a request given a visit to the -// host, and host_visits is the number of visits to the host in 30 days. -double NaiveResourceWeight(double resource_weight_ratio, int64_t host_visits) { - return resource_weight_ratio * host_visits; -} - -// Models the probability of at least one request for the resource, given that -// resource_weight_ratio is the probability of a request given a visit to the -// host, and host_visits is the number of visits to the host in 30 days. -double GeometricResourceWeight(double resource_weight_ratio, - int64_t host_visits) { - return 1 - pow(1 - resource_weight_ratio, host_visits); -} - -} // namespace - -// Returns the weight of the resource. When global ranking is enabled, the -// fetches are sorted by descending weight. Parameters: -// function: Which combination function to use. -// resource_weight_ratio: The weight_ratio of the resource. -// host_visits: The count of visits to the given host in the past 30 days. -double ResourceWeight( - PrecacheConfigurationSettings::ResourceWeightFunction function, - double resource_weight_ratio, - int64_t host_visits) { - switch (function) { - case PrecacheConfigurationSettings::FUNCTION_NAIVE: - return NaiveResourceWeight(resource_weight_ratio, host_visits); - case PrecacheConfigurationSettings::FUNCTION_GEOMETRIC: - return GeometricResourceWeight(resource_weight_ratio, host_visits); - default: - DLOG(FATAL) << "Unknown function " << function; - return 0; - } -} - -PrecacheFetcher::Fetcher::Fetcher( - net::URLRequestContextGetter* request_context, - const GURL& url, - const std::string& referrer, - const base::Callback<void(const Fetcher&)>& callback, - bool is_resource_request, - size_t max_bytes, - bool revalidation_only) - : request_context_(request_context), - url_(url), - referrer_(referrer), - callback_(callback), - is_resource_request_(is_resource_request), - max_bytes_(max_bytes), - revalidation_only_(revalidation_only), - response_bytes_(0), - network_response_bytes_(0), - was_cached_(false) { - DCHECK(url.is_valid()); - if (is_resource_request_) - LoadFromCache(); - else - LoadFromNetwork(); -} - -PrecacheFetcher::Fetcher::~Fetcher() {} - -void PrecacheFetcher::Fetcher::LoadFromCache() { - fetch_stage_ = FetchStage::CACHE; - net::NetworkTrafficAnnotationTag traffic_annotation = - net::DefineNetworkTrafficAnnotation("wifi_prefetch_from_cache", R"( - semantics { - sender: "Wifi Prefetch" - description: - "Speeds up mobile web page loads by downloading some common static " - "assets (such as JS and CSS) for sites that the user browses " - "frequently, in advance of the browser needing them. Only applies " - "to users with tab sync enabled." - trigger: - "Background service that runs when the device is plugged into " - "power, on unmetered wifi, and Chromium is not in the foreground." - data: - "Local cache fetches; no data is sent over the network." - destination: OTHER - } - policy { - cookies_allowed: false - setting: - "Users can disable this feature by several settings: Disabling tab " - "sync via unchecking 'Open tabs' in Chromium settings under " - "'Advanced sync settings'; Disabling predicting required downloads " - "via unchecking 'Use a prediction service to load pages more " - "quickly' in Chromium settings under Privacy; Enabling 'Data " - "Saver' in Chromium settings on Android." - chrome_policy { - NetworkPredictionOptions { - policy_options {mode: MANDATORY} - NetworkPredictionOptions: 2 - } - } - })"); - cache_url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, this, - traffic_annotation); - data_use_measurement::DataUseUserData::AttachToFetcher( - cache_url_fetcher_.get(), - data_use_measurement::DataUseUserData::PRECACHE); - cache_url_fetcher_->SetRequestContext(request_context_); - cache_url_fetcher_->SetLoadFlags(net::LOAD_ONLY_FROM_CACHE | - net::LOAD_SKIP_CACHE_VALIDATION | - kNoTracking); - std::unique_ptr<URLFetcherNullWriter> null_writer(new URLFetcherNullWriter); - cache_url_fetcher_->SaveResponseWithWriter(std::move(null_writer)); - cache_url_fetcher_->Start(); -} - -void PrecacheFetcher::Fetcher::LoadFromNetwork() { - fetch_stage_ = FetchStage::NETWORK; - if (is_resource_request_) { - net::NetworkTrafficAnnotationTag traffic_annotation = - net::DefineNetworkTrafficAnnotation( - "wifi_prefetch_resource_from_network", R"( - semantics { - sender: "Wifi Prefetch" - description: - "Speeds up mobile web page loads by downloading common static " - "assets (such as JS and CSS) for sites that the user browses " - "frequently, in advance of the browser needing them. Only " - "applies to users with tab sync enabled." - trigger: - "Background service that runs when the device is plugged into " - "power, on unmetered wifi, and Chromium is not in the " - "foreground." - data: "Link to the requested resrouce." - destination: WEBSITE - } - policy { - cookies_allowed: false - setting: - "Users can disable this feature by several settings: Disabling " - "tab sync via unchecking 'Open tabs' in Chromium settings " - "under 'Advanced sync settings'; Disabling predicting required " - "downloads via unchecking 'Use a prediction service to load " - "pages more quickly' in Chromium settings under Privacy; " - "Enabling 'Data Saver' in Chromium settings on Android." - chrome_policy { - NetworkPredictionOptions { - policy_options {mode: MANDATORY} - NetworkPredictionOptions: 2 - } - } - })"); - network_url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, - this, traffic_annotation); - } else { - net::NetworkTrafficAnnotationTag traffic_annotation = - net::DefineNetworkTrafficAnnotation("wifi_prefetch_sites_from_network", - R"( - semantics { - sender: "Wifi Prefetch" - description: - "Speeds up mobile web page loads by downloading common static " - "assets (such as JS and CSS) for sites that the user browses " - "frequently, in advance of the browser needing them. The first " - "step is to download the list of common static assets from " - "Google. Only applies to users with tab sync enabled." - trigger: - "Background service that runs when the device is plugged into " - "power, on unmetered wifi, and Chromium is not in the foreground." - data: "A list of the top hosts that the user visits." - destination: GOOGLE_OWNED_SERVICE - } - policy { - cookies_allowed: false - setting: - "Users can disable this feature by several settings: Disabling " - "tab sync via unchecking 'Open tabs' in Chromium settings under " - "'Advanced sync settings'; Disabling predicting required " - "downloads via unchecking 'Use a prediction service to load " - "pages more quickly' in Chromium settings under Privacy; " - "Enabling 'Data Saver' in Chromium settings on Android." - chrome_policy { - NetworkPredictionOptions { - policy_options {mode: MANDATORY} - NetworkPredictionOptions: 2 - } - } - })"); - network_url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, - this, traffic_annotation); - } - - data_use_measurement::DataUseUserData::AttachToFetcher( - network_url_fetcher_.get(), - data_use_measurement::DataUseUserData::PRECACHE); - network_url_fetcher_->SetRequestContext(request_context_); - if (is_resource_request_) { - // LOAD_VALIDATE_CACHE allows us to refresh Date headers for resources - // already in the cache. The Date headers are updated from 304s as well as - // 200s. - network_url_fetcher_->SetLoadFlags(net::LOAD_VALIDATE_CACHE | kNoTracking); - // We don't need a copy of the response body for resource requests. The - // request is issued only to populate the browser cache. - std::unique_ptr<URLFetcherNullWriter> null_writer(new URLFetcherNullWriter); - network_url_fetcher_->SaveResponseWithWriter(std::move(null_writer)); - } else { - // Config and manifest requests do not need to be revalidated. It's okay if - // they expire from the cache minutes after we request them. - network_url_fetcher_->SetLoadFlags(kNoTracking); - } - network_url_fetcher_->Start(); -} - -void PrecacheFetcher::Fetcher::OnURLFetchDownloadProgress( - const net::URLFetcher* source, - int64_t current, - int64_t total, - int64_t current_network_bytes) { - // If network bytes going over the per-resource download cap. - if (fetch_stage_ == FetchStage::NETWORK && - // |current_network_bytes| is guaranteed to be non-negative, so this cast - // is safe. - static_cast<size_t>(current_network_bytes) > max_bytes_) { - // Call the completion callback, to attempt the next download, or to trigger - // cleanup in precache_delegate_->OnDone(). - response_bytes_ = current; - network_response_bytes_ = current_network_bytes; - was_cached_ = source->WasCached(); - - UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.NetworkWasted", - network_response_bytes_, 1, - 1024 * 1024 /* 1 MB */, 100); - // Cancel the download. - network_url_fetcher_.reset(); - callback_.Run(*this); - } -} - -void PrecacheFetcher::Fetcher::OnURLFetchComplete( - const net::URLFetcher* source) { - CHECK(source); - if (fetch_stage_ == FetchStage::CACHE && - ((source->GetStatus().error() == net::ERR_CACHE_MISS && - !revalidation_only_) || - (source->GetResponseHeaders() && - source->GetResponseHeaders()->HasValidators()))) { - // If the resource was not found in the cache, request it from the - // network. - // - // If the resource was found in the cache, but contains validators, - // request a refresh. The presence of validators increases the chance that - // we get a 304 response rather than a full one, thus allowing us to - // refresh the cache with minimal network load. - LoadFromNetwork(); - return; - } - - // If any of: - // - The request was for a config or manifest. - // - The resource was a cache hit without validators. - // - The response came from the network. - // Then Fetcher is done with this URL and can return control to the caller. - response_bytes_ = source->GetReceivedResponseContentLength(); - network_response_bytes_ = source->GetTotalReceivedBytes(); - was_cached_ = source->WasCached(); - callback_.Run(*this); -} - -// static -void PrecacheFetcher::RecordCompletionStatistics( - const PrecacheUnfinishedWork& unfinished_work, - size_t remaining_manifest_urls_to_fetch, - size_t remaining_resource_urls_to_fetch) { - // These may be unset in tests. - if (!unfinished_work.has_start_time()) - return; - base::TimeDelta time_to_fetch = - base::Time::Now() - - base::Time::FromInternalValue(unfinished_work.start_time()); - UMA_HISTOGRAM_CUSTOM_TIMES("Precache.Fetch.TimeToComplete", time_to_fetch, - base::TimeDelta::FromSeconds(1), - base::TimeDelta::FromHours(4), 50); - - int num_total_resources = unfinished_work.num_resource_urls(); - int percent_completed = - num_total_resources == 0 - ? 101 // Overflow bucket. - : (100 * (static_cast<double>(num_total_resources - - remaining_resource_urls_to_fetch) / - num_total_resources)); - - UMA_HISTOGRAM_PERCENTAGE("Precache.Fetch.PercentCompleted", - percent_completed); - UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Total", - unfinished_work.total_bytes(), 1, - kMaxResponseBytes, 100); - UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Network", - unfinished_work.network_bytes(), 1, - kMaxResponseBytes, 100); - - if (unfinished_work.has_min_weight_fetched()) { - UMA_HISTOGRAM_COUNTS_1000("Precache.Fetch.MinWeight", - unfinished_work.min_weight_fetched() * 1000); - } -} - -// static -std::string PrecacheFetcher::GetResourceURLBase64HashForTesting( - const std::vector<GURL>& urls) { - return GetResourceURLBase64Hash(urls); -} - -PrecacheFetcher::PrecacheFetcher( - net::URLRequestContextGetter* request_context, - const GURL& config_url, - const std::string& manifest_url_prefix, - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work, - uint32_t experiment_id, - const base::WeakPtr<PrecacheDatabase>& precache_database, - const scoped_refptr<base::SingleThreadTaskRunner>& db_task_runner, - PrecacheFetcher::PrecacheDelegate* precache_delegate) - : request_context_(request_context), - config_url_(config_url), - manifest_url_prefix_(manifest_url_prefix), - precache_database_(precache_database), - db_task_runner_(std::move(db_task_runner)), - precache_delegate_(precache_delegate), - pool_(kMaxParallelFetches), - experiment_id_(experiment_id) { - DCHECK(request_context_.get()); // Request context must be non-NULL. - DCHECK(precache_delegate_); // Precache delegate must be non-NULL. - - DCHECK_NE(GURL(), GetDefaultConfigURL()) - << "Could not determine the precache config settings URL."; - DCHECK_NE(std::string(), GetDefaultManifestURLPrefix()) - << "Could not determine the default precache manifest URL prefix."; - DCHECK(unfinished_work); - - // Copy resources to member variable as a convenience. - // TODO(rajendrant): Consider accessing these directly from the proto, by - // keeping track of the current resource index. - for (const auto& resource : unfinished_work->resource()) { - if (resource.has_url() && resource.has_top_host_name()) { - resources_to_fetch_.emplace_back( - GURL(resource.url()), resource.top_host_name(), resource.weight()); - } - } - unfinished_work_ = std::move(unfinished_work); -} - -PrecacheFetcher::~PrecacheFetcher() { -} - -std::unique_ptr<PrecacheUnfinishedWork> PrecacheFetcher::CancelPrecaching() { - // This could get called multiple times, and it should be handled gracefully. - if (!unfinished_work_) - return nullptr; - - unfinished_work_->clear_resource(); - if (unfinished_work_->has_config_settings()) { - // If config fetch is incomplete, |top_hosts_to_fetch_| will be empty and - // top hosts should be left as is in |unfinished_work_|. - unfinished_work_->clear_top_host(); - for (const auto& top_host : top_hosts_fetching_) - unfinished_work_->add_top_host()->set_hostname(top_host.hostname); - for (const auto& top_host : top_hosts_to_fetch_) - unfinished_work_->add_top_host()->set_hostname(top_host.hostname); - } - for (const auto& resource : resources_fetching_) { - auto* new_resource = unfinished_work_->add_resource(); - new_resource->set_url(resource.url.spec()); - new_resource->set_top_host_name(resource.referrer); - new_resource->set_weight(resource.weight); - } - for (const auto& resource : resources_to_fetch_) { - auto* new_resource = unfinished_work_->add_resource(); - new_resource->set_url(resource.url.spec()); - new_resource->set_top_host_name(resource.referrer); - new_resource->set_weight(resource.weight); - } - top_hosts_fetching_.clear(); - top_hosts_to_fetch_.clear(); - resources_fetching_.clear(); - resources_to_fetch_.clear(); - pool_.DeleteAll(); - return std::move(unfinished_work_); -} - -void PrecacheFetcher::Start() { - if (unfinished_work_->has_config_settings()) { - DCHECK(unfinished_work_->has_start_time()); - DetermineManifests(); - return; - } - - GURL config_url = - config_url_.is_empty() ? GetDefaultConfigURL() : config_url_; - - DCHECK(config_url.is_valid()) << "Config URL not valid: " - << config_url.possibly_invalid_spec(); - - // Fetch the precache configuration settings from the server. - DCHECK(pool_.IsEmpty()) << "All parallel requests should be available"; - pool_.Add(base::MakeUnique<Fetcher>( - request_context_.get(), config_url, std::string(), - base::Bind(&PrecacheFetcher::OnConfigFetchComplete, AsWeakPtr()), - false /* is_resource_request */, std::numeric_limits<int32_t>::max(), - false /* revalidation_only */)); -} - -void PrecacheFetcher::StartNextResourceFetch() { - DCHECK(unfinished_work_->has_config_settings()); - while (!resources_to_fetch_.empty() && pool_.IsAvailable()) { - ResourceInfo& resource = resources_to_fetch_.front(); - const size_t max_bytes = std::min( - quota_.remaining(), - std::min(unfinished_work_->config_settings().max_bytes_per_resource(), - unfinished_work_->config_settings().max_bytes_total() - - unfinished_work_->total_bytes())); - pool_.Add(base::MakeUnique<Fetcher>( - request_context_.get(), resource.url, resource.referrer, - base::Bind(&PrecacheFetcher::OnResourceFetchComplete, AsWeakPtr()), - true /* is_resource_request */, max_bytes, - unfinished_work_->config_settings().revalidation_only())); - - resources_fetching_.push_back(std::move(resource)); - resources_to_fetch_.pop_front(); - } -} - -void PrecacheFetcher::StartNextManifestFetches() { - // We fetch as many manifests at a time as possible, as we need all resource - // URLs in memory in order to rank them. - while (!top_hosts_to_fetch_.empty() && pool_.IsAvailable()) { - ManifestHostInfo& top_host = top_hosts_to_fetch_.front(); - pool_.Add(base::MakeUnique<Fetcher>( - request_context_.get(), top_host.manifest_url, top_host.hostname, - base::Bind(&PrecacheFetcher::OnManifestFetchComplete, AsWeakPtr(), - top_host.visits), - false /* is_resource_request */, std::numeric_limits<int32_t>::max(), - false /* revalidation_only */)); - top_hosts_fetching_.push_back(std::move(top_host)); - top_hosts_to_fetch_.pop_front(); - } -} - -void PrecacheFetcher::NotifyDone(size_t remaining_manifest_urls_to_fetch, - size_t remaining_resource_urls_to_fetch) { - RecordCompletionStatistics(*unfinished_work_, - remaining_manifest_urls_to_fetch, - remaining_resource_urls_to_fetch); - precache_delegate_->OnDone(); -} - -void PrecacheFetcher::StartNextFetch() { - DCHECK(unfinished_work_->has_config_settings()); - - // If over the precache total size cap or daily quota, then stop prefetching. - if ((unfinished_work_->total_bytes() > - unfinished_work_->config_settings().max_bytes_total()) || - quota_.remaining() == 0) { - pool_.DeleteAll(); - NotifyDone(top_hosts_to_fetch_.size() + top_hosts_fetching_.size(), - resources_to_fetch_.size() + resources_fetching_.size()); - return; - } - - StartNextResourceFetch(); - StartNextManifestFetches(); - if (top_hosts_to_fetch_.empty() && resources_to_fetch_.empty() && - pool_.IsEmpty()) { - // There are no more URLs to fetch, so end the precache cycle. - NotifyDone(0, 0); - // OnDone may have deleted this PrecacheFetcher, so don't do anything after - // it is called. - } -} - -void PrecacheFetcher::OnConfigFetchComplete(const Fetcher& source) { - UpdateStats(source.response_bytes(), source.network_response_bytes()); - if (source.network_url_fetcher() == nullptr) { - pool_.DeleteAll(); // Cancel any other ongoing request. - } else { - // Attempt to parse the config proto. On failure, continue on with the - // default configuration. - ParseProtoFromFetchResponse( - *source.network_url_fetcher(), - unfinished_work_->mutable_config_settings()); - pool_.Delete(source); - DetermineManifests(); - } -} - -void PrecacheFetcher::DetermineManifests() { - DCHECK(unfinished_work_->has_config_settings()); - - std::vector<std::pair<std::string, int64_t>> top_hosts_to_fetch; - // Keep track of manifest URLs that are being fetched, in order to elide - // duplicates. - std::set<base::StringPiece> seen_top_hosts; - int64_t rank = 0; - - for (const auto& host : unfinished_work_->top_host()) { - ++rank; - if (rank > unfinished_work_->config_settings().top_sites_count()) - break; - if (seen_top_hosts.insert(host.hostname()).second) - top_hosts_to_fetch.emplace_back(host.hostname(), host.visits()); - } - - // Attempt to fetch manifests for starting hosts up to the maximum top sites - // count. If a manifest does not exist for a particular starting host, then - // the fetch will fail, and that starting host will be ignored. Starting - // hosts are not added if this is a continuation from a previous precache - // session. - if (resources_to_fetch_.empty()) { - for (const std::string& host : - unfinished_work_->config_settings().forced_site()) { - // We add a forced site with visits == 0, which means its resources will - // be downloaded last. TODO(twifkak): Consider removing support for - // forced_site. - if (seen_top_hosts.insert(host).second) - top_hosts_to_fetch.emplace_back(host, 0); - } - } - // We retrieve manifest usage and quota info from the local database before - // fetching the manifests. - PostTaskAndReplyWithResult( - db_task_runner_.get(), FROM_HERE, - base::Bind(&RetrieveManifestInfo, precache_database_, - std::move(top_hosts_to_fetch)), - base::Bind(&PrecacheFetcher::OnManifestInfoRetrieved, AsWeakPtr())); -} - -void PrecacheFetcher::OnManifestInfoRetrieved( - std::deque<ManifestHostInfo> manifests_info) { - const std::string prefix = manifest_url_prefix_.empty() - ? GetDefaultManifestURLPrefix() - : manifest_url_prefix_; - if (!GURL(prefix).is_valid()) { - // Don't attempt to fetch any manifests if the manifest URL prefix - // is invalid. - top_hosts_to_fetch_.clear(); - unfinished_work_->set_num_manifest_urls(manifests_info.size()); - NotifyDone(manifests_info.size(), resources_to_rank_.size()); - return; - } - - top_hosts_to_fetch_ = std::move(manifests_info); - for (auto& manifest : top_hosts_to_fetch_) { - manifest.manifest_url = - GURL(prefix + - net::EscapeQueryParamValue( - net::EscapeQueryParamValue(manifest.hostname, false), false)); - if (manifest.manifest_id != PrecacheReferrerHostEntry::kInvalidId) { - manifest.manifest_url = net::AppendOrReplaceQueryParameter( - manifest.manifest_url, "manifest", - std::to_string(manifest.manifest_id)); - manifest.manifest_url = net::AppendOrReplaceQueryParameter( - manifest.manifest_url, "used_resources", manifest.used_url_hash); - manifest.manifest_url = net::AppendOrReplaceQueryParameter( - manifest.manifest_url, "d", manifest.downloaded_url_hash); - DCHECK(manifest.manifest_url.is_valid()); - } - } - unfinished_work_->set_num_manifest_urls(top_hosts_to_fetch_.size()); - - PostTaskAndReplyWithResult( - db_task_runner_.get(), FROM_HERE, - base::Bind(&RetrieveQuotaInfo, precache_database_), - base::Bind(&PrecacheFetcher::OnQuotaInfoRetrieved, AsWeakPtr())); -} - -void PrecacheFetcher::OnQuotaInfoRetrieved(const PrecacheQuota& quota) { - quota_ = quota; - base::Time time_now = base::Time::Now(); - if (IsQuotaTimeExpired(quota_, time_now)) { - // This is a new day. Update daily quota, that starts today and expires by - // end of today. - - // If a previous day existed, report its usage. - if (quota_.has_start_time()) { - UMA_HISTOGRAM_CUSTOM_COUNTS( - "Precache.Fetch.ResponseBytes.Daily", - unfinished_work_->config_settings().daily_quota_total() - - quota_.remaining(), - 1, kMaxResponseBytes, 100); - } - - quota_.set_start_time(time_now.LocalMidnight().ToInternalValue()); - quota_.set_remaining( - unfinished_work_->config_settings().daily_quota_total()); - db_task_runner_->PostTask( - FROM_HERE, - base::Bind(&PrecacheDatabase::SaveQuota, precache_database_, quota_)); - } - StartNextFetch(); -} - -ManifestHostInfo::ManifestHostInfo(int64_t manifest_id, - const std::string& hostname, - int64_t visits, - const std::string& used_url_hash, - const std::string& downloaded_url_hash) - : manifest_id(manifest_id), - hostname(hostname), - visits(visits), - used_url_hash(used_url_hash), - downloaded_url_hash(downloaded_url_hash) {} - -ManifestHostInfo::~ManifestHostInfo() {} - -ManifestHostInfo::ManifestHostInfo(ManifestHostInfo&&) = default; - -ManifestHostInfo& ManifestHostInfo::operator=(ManifestHostInfo&&) = default; - -ResourceInfo::ResourceInfo(const GURL& url, - const std::string& referrer, - double weight) - : url(url), referrer(referrer), weight(weight) {} - -ResourceInfo::~ResourceInfo() {} - -ResourceInfo::ResourceInfo(ResourceInfo&&) = default; - -ResourceInfo& ResourceInfo::operator=(ResourceInfo&&) = default; - -void PrecacheFetcher::OnManifestFetchComplete(int64_t host_visits, - const Fetcher& source) { - DCHECK(unfinished_work_->has_config_settings()); - UpdateStats(source.response_bytes(), source.network_response_bytes()); - if (source.network_url_fetcher() == nullptr) { - pool_.DeleteAll(); // Cancel any other ongoing request. - } else { - PrecacheManifest manifest; - - if (ParseProtoFromFetchResponse(*source.network_url_fetcher(), &manifest)) { - const base::Optional<std::vector<bool>> resource_bitset = - GetResourceBitset(manifest, experiment_id_); - const int32_t included_resources_max = - unfinished_work_->config_settings().top_resources_count(); - int32_t included_resources = 0; - for (int i = 0; i < manifest.resource_size() && - included_resources < included_resources_max; - ++i) { - if ((!resource_bitset.has_value() || resource_bitset.value()[i]) && - manifest.resource(i).has_url()) { - GURL url(manifest.resource(i).url()); - if (url.is_valid()) { - double weight = ResourceWeight( - unfinished_work_->config_settings().resource_weight_function(), - manifest.resource(i).weight_ratio(), host_visits); - if (weight >= unfinished_work_->config_settings().min_weight()) { - resources_to_rank_.emplace_back(url, source.referrer(), weight); - ++included_resources; - } - } - } - } - db_task_runner_->PostTask( - FROM_HERE, base::Bind(&PrecacheDatabase::UpdatePrecacheReferrerHost, - precache_database_, source.referrer(), - manifest.id().id(), base::Time::Now())); - } - } - - top_hosts_fetching_.remove_if([&source](const ManifestHostInfo& top_host) { - return top_host.manifest_url == source.url(); - }); - - pool_.Delete(source); - - if (top_hosts_to_fetch_.empty() && top_hosts_fetching_.empty()) - QueueResourcesForFetch(); - - StartNextFetch(); -} - -void PrecacheFetcher::QueueResourcesForFetch() { - // Done fetching manifests. Now move resources_to_rank_ into - // resources_to_fetch_, so that StartNextFetch will begin fetching resources. - resources_to_fetch_ = std::move(resources_to_rank_); - - if (unfinished_work_->config_settings().global_ranking()) { - // Sort resources_to_fetch_ by descending weight. - std::stable_sort(resources_to_fetch_.begin(), resources_to_fetch_.end(), - [](const ResourceInfo& first, const ResourceInfo& second) { - return first.weight > second.weight; - }); - } - - // Truncate to size |total_resources_count|. - const size_t num_resources = std::min( - resources_to_fetch_.size(), - static_cast<size_t>( - unfinished_work_->config_settings().total_resources_count())); - resources_to_fetch_.erase(resources_to_fetch_.begin() + num_resources, - resources_to_fetch_.end()); - - // Save denominator for PercentCompleted UMA. - unfinished_work_->set_num_resource_urls(resources_to_fetch_.size()); -} - -void PrecacheFetcher::OnResourceFetchComplete(const Fetcher& source) { - UpdateStats(source.response_bytes(), source.network_response_bytes()); - - db_task_runner_->PostTask( - FROM_HERE, - base::Bind(&PrecacheDatabase::RecordURLPrefetch, precache_database_, - source.url(), source.referrer(), base::Time::Now(), - source.was_cached(), source.response_bytes())); - - auto resource = - std::find_if(resources_fetching_.begin(), resources_fetching_.end(), - [&source](const ResourceInfo& resource) { - return resource.url == source.url(); - }); - if (resource != resources_fetching_.end()) { - if (unfinished_work_->config_settings().global_ranking() && - (!unfinished_work_->has_min_weight_fetched() || - resource->weight < unfinished_work_->min_weight_fetched())) - unfinished_work_->set_min_weight_fetched(resource->weight); - - resources_fetching_.erase(resource); - } - - pool_.Delete(source); - - // The resource has already been put in the cache during the fetch process, so - // nothing more needs to be done for the resource. - StartNextFetch(); -} - -void PrecacheFetcher::UpdateStats(int64_t response_bytes, - int64_t network_response_bytes) { - DCHECK_LE(0, response_bytes); - DCHECK_LE(0, network_response_bytes); - - unfinished_work_->set_total_bytes( - unfinished_work_->total_bytes() + response_bytes); - unfinished_work_->set_network_bytes( - unfinished_work_->network_bytes() + network_response_bytes); - - if (!IsQuotaTimeExpired(quota_, base::Time::Now())) { - uint64_t used_bytes = static_cast<uint64_t>(network_response_bytes); - int64_t remaining = - static_cast<int64_t>(quota_.remaining()) - network_response_bytes; - if (remaining < 0) - remaining = 0; - quota_.set_remaining( - used_bytes > quota_.remaining() ? 0U : quota_.remaining() - used_bytes); - db_task_runner_->PostTask( - FROM_HERE, - base::Bind(&PrecacheDatabase::SaveQuota, precache_database_, quota_)); - } -} - -} // namespace precache
diff --git a/components/precache/core/precache_fetcher.h b/components/precache/core/precache_fetcher.h deleted file mode 100644 index 9868d1c0..0000000 --- a/components/precache/core/precache_fetcher.h +++ /dev/null
@@ -1,365 +0,0 @@ -// 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 COMPONENTS_PRECACHE_CORE_PRECACHE_FETCHER_H_ -#define COMPONENTS_PRECACHE_CORE_PRECACHE_FETCHER_H_ - -#include <stdint.h> - -#include <deque> -#include <list> -#include <memory> -#include <string> -#include <vector> - -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/single_thread_task_runner.h" -#include "base/time/time.h" -#include "components/precache/core/fetcher_pool.h" -#include "components/precache/core/proto/precache.pb.h" -#include "components/precache/core/proto/quota.pb.h" -#include "net/url_request/url_fetcher.h" -#include "net/url_request/url_fetcher_delegate.h" -#include "url/gurl.h" - -namespace base { -class SingleThreadTaskRunner; -} - -namespace net { -class URLRequestContextGetter; -} - -namespace precache { - -class PrecacheConfigurationSettings; -class PrecacheDatabase; -class PrecacheUnfinishedWork; - -// Visible for testing. -extern const int kNoTracking; -extern const int kMaxParallelFetches; - -// Information about the manifest for a host. -struct ManifestHostInfo { - ManifestHostInfo(int64_t manifest_id, - const std::string& hostname, - int64_t visits, - const std::string& used_url_hash, - const std::string& downloaded_url_hash); - ~ManifestHostInfo(); - ManifestHostInfo(ManifestHostInfo&&); - ManifestHostInfo& operator=(ManifestHostInfo&&); - // Copy constructor and assignment operator are implicitly deleted. - - int64_t manifest_id; - std::string hostname; - GURL manifest_url; - int64_t visits; - std::string used_url_hash; - std::string downloaded_url_hash; -}; - -// Information about a resource to be downloaded. -struct ResourceInfo { - ResourceInfo(const GURL& url, const std::string& referrer, double weight); - ~ResourceInfo(); - ResourceInfo(ResourceInfo&&); - ResourceInfo& operator=(ResourceInfo&&); - // Copy constructor and assignment operator are implicitly deleted. - - GURL url; // The resource being requested. - std::string referrer; // The host of the manifest requesting this resource. - double weight; // Estimate of the expected utility of this resource. -}; - -// Public interface to code that fetches resources that the user is likely to -// want to fetch in the future, putting them in the network stack disk cache. -// Precaching is intended to be done when Chrome is not actively in use, likely -// hours ahead of the time when the resources are actually needed. -// -// This class takes as input a prioritized list of URL domains that the user -// commonly visits, referred to as starting hosts. This class interacts with a -// server, sending it the list of starting hosts sequentially. For each starting -// host, the server returns a manifest of resource URLs that are good candidates -// for precaching. Every resource returned is fetched, and responses are cached -// as they are received. Destroying the PrecacheFetcher while it is precaching -// will cancel any fetch in progress and cancel precaching. -// -// The URLs of the server-side component must be specified in order for the -// PrecacheFetcher to work. This includes the URL that the precache -// configuration settings are fetched from and the prefix of URLs where precache -// manifests are fetched from. These can be set by using command line switches -// or by providing default values. -// -// Sample interaction: -// -// class MyPrecacheFetcherDelegate : public PrecacheFetcher::PrecacheDelegate { -// public: -// void PrecacheResourcesForTopURLs( -// net::URLRequestContextGetter* request_context, -// const std::list<GURL>& top_urls) { -// fetcher_.reset(new PrecacheFetcher(...)); -// fetcher_->Start(); -// } -// -// void Cancel() { -// std::unique_ptr<PrecacheUnfinishedWork> unfinished_work = -// fetcher_->CancelPrecaching(); -// fetcher_.reset(); -// } -// -// virtual void OnDone() { -// // Do something when precaching is done. -// } -// -// private: -// std::unique_ptr<PrecacheFetcher> fetcher_; -// }; -class PrecacheFetcher : public base::SupportsWeakPtr<PrecacheFetcher> { - public: - class PrecacheDelegate { - public: - // Called when the fetching of resources has finished, whether the resources - // were fetched or not. If the PrecacheFetcher is destroyed before OnDone is - // called, then precaching will be canceled and OnDone will not be called. - virtual void OnDone() = 0; - }; - - // Visible for testing. - class Fetcher; - - static void RecordCompletionStatistics( - const PrecacheUnfinishedWork& unfinished_work, - size_t remaining_manifest_urls_to_fetch, - size_t remaining_resource_urls_to_fetch); - - static std::string GetResourceURLBase64HashForTesting( - const std::vector<GURL>& urls); - - // Constructs a new PrecacheFetcher. The |unfinished_work| contains the - // prioritized list of hosts that the user commonly visits. These hosts are - // used by a server side component to construct a list of resource URLs that - // the user is likely to fetch. Takes ownership of |unfinished_work|. - // |precache_database| should be accessed only in |db_task_runner|. - PrecacheFetcher( - net::URLRequestContextGetter* request_context, - const GURL& config_url, - const std::string& manifest_url_prefix, - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work, - uint32_t experiment_id, - const base::WeakPtr<PrecacheDatabase>& precache_database, - const scoped_refptr<base::SingleThreadTaskRunner>& db_task_runner, - PrecacheDelegate* precache_delegate); - - virtual ~PrecacheFetcher(); - - // Starts fetching resources to precache. URLs are fetched sequentially. Can - // be called from any thread. Start should only be called once on a - // PrecacheFetcher instance. - void Start(); - - // Stops all precaching work. The PreacheFetcher should not be used after - // calling this method. - std::unique_ptr<PrecacheUnfinishedWork> CancelPrecaching(); - - private: - friend class PrecacheFetcherTest; - FRIEND_TEST_ALL_PREFIXES(PrecacheFetcherTest, - GloballyRankResourcesAfterPauseResume); - FRIEND_TEST_ALL_PREFIXES(PrecacheFetcherTest, FetcherPoolMaxLimitReached); - FRIEND_TEST_ALL_PREFIXES(PrecacheFetcherTest, - CancelPrecachingAfterAllManifestFetch); - FRIEND_TEST_ALL_PREFIXES(PrecacheFetcherTest, DailyQuota); - - // Notifies the precache delete that precaching is done, and report - // completion statistics. - void NotifyDone(size_t remaining_manifest_urls_to_fetch, - size_t remaining_resource_urls_to_fetch); - - // Fetches the next resource or manifest URL, if any remain. Fetching is done - // sequentially and depth-first: all resources are fetched for a manifest - // before the next manifest is fetched. This is done to limit the length of - // the |resource_urls_to_fetch_| list, reducing the memory usage. - void StartNextFetch(); - - void StartNextManifestFetches(); - void StartNextResourceFetch(); - - // Called when the precache configuration settings have been fetched. - // Determines the list of manifest URLs to fetch according to the list of - // |starting_hosts_| and information from the precache configuration settings. - // If the fetch of the configuration settings fails, then precaching ends. - void OnConfigFetchComplete(const Fetcher& source); - - // Constructs manifest URLs using a manifest URL prefix, and lists of hosts. - void DetermineManifests(); - - // Called when a precache manifest has been fetched. Builds the list of - // resource URLs to fetch according to the URLs in the manifest. If the fetch - // of a manifest fails, then it skips to the next manifest. - void OnManifestFetchComplete(int64_t host_visits, const Fetcher& source); - - // Moves the pending resource URLs into the to-be-fetched queue, and sorts and - // truncates if specified by the PrecacheConfigurationSettings. Called by - // OnManifestFetchComplete after the last manifest is fetched, so that - // StartNextFetch will begin fetching resource URLs. - void QueueResourcesForFetch(); - - // Called when a resource has been fetched. - void OnResourceFetchComplete(const Fetcher& source); - - // Adds up the response sizes. - void UpdateStats(int64_t response_bytes, int64_t network_response_bytes); - - // Callback invoked when the manifest info for all the top hosts is retrieved. - void OnManifestInfoRetrieved(std::deque<ManifestHostInfo> manifests_info); - - // Callback invoked when the quota is retrieved. - void OnQuotaInfoRetrieved(const PrecacheQuota& quota); - - // The request context used when fetching URLs. - const scoped_refptr<net::URLRequestContextGetter> request_context_; - - // The custom URL to use when fetching the config. If not provided, the - // default flag-specified URL will be used. - const GURL config_url_; - - // The custom URL prefix to use when fetching manifests. If not provided, the - // default flag-specified prefix will be used. - const std::string manifest_url_prefix_; - - // PrecacheDatabase should be accessed on the DB thread. - base::WeakPtr<PrecacheDatabase> precache_database_; - scoped_refptr<base::SingleThreadTaskRunner> db_task_runner_; - - // Non-owning pointer. Should not be NULL. - PrecacheDelegate* precache_delegate_; - - // Top hosts for which manifests still need to be fetched (i.e. no Fetcher has - // been created yet). - std::deque<ManifestHostInfo> top_hosts_to_fetch_; - - // Top hosts for which manifests are currently being fetched. - std::list<ManifestHostInfo> top_hosts_fetching_; - - // Resources to be fetched, in desired fetch order. Populated only after - // manifest fetching is complete. - std::deque<ResourceInfo> resources_to_fetch_; - - // Resources currently being fetched, in the order requested. - std::list<ResourceInfo> resources_fetching_; - - // Resources to be fetched, not yet ranked. Valid until manifest fetching is - // done, after which resources are sorted and places in resources_to_fetch_. - std::deque<ResourceInfo> resources_to_rank_; - - FetcherPool<Fetcher> pool_; - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work_; - - // Daily quota. - PrecacheQuota quota_; - - // The fieldtrial experiment ID. - uint32_t experiment_id_; - - DISALLOW_COPY_AND_ASSIGN(PrecacheFetcher); -}; - -// Visible for testing. -double ResourceWeight( - PrecacheConfigurationSettings::ResourceWeightFunction function, - double resource_weight_ratio, - int64_t host_visits); - -// Class that fetches a URL, and runs the specified callback when the fetch is -// complete. This class exists so that a different method can be run in -// response to different kinds of fetches, e.g. OnConfigFetchComplete when -// configuration settings are fetched, OnManifestFetchComplete when a manifest -// is fetched, etc. -// -// This class tries to increase freshness while limiting network usage, by using -// the following strategy: -// 1. Fetch the URL from the cache. -// 2a. If it's present and lacks revalidation headers, then stop. -// 2b. If it's not present, or it's present and has revalidation headers, then -// refetch over the network. -// -// This allows the precache to "refresh" cache entries by increasing their -// expiration date, but minimizes the network impact of doing so, by performing -// only conditional GETs. -// -// On completion it calls the given callback. This class cancels requests whose -// responses are or will be larger than max_bytes. In such cases, -// network_url_fetcher() will return nullptr. -class PrecacheFetcher::Fetcher : public net::URLFetcherDelegate { - public: - // Construct a new Fetcher. This will create and start a new URLFetcher - // immediately. Parameters: - // request_context: The request context to pass to the URLFetcher. - // url: The URL to fetch. - // referrer: The hostname of the manifest requesting this resource. Empty - // for config fetches. - // callback: Called when the fetch is finished or cancelled. - // is_resource_request: If true, the URL may be refreshed using - // LOAD_VALIDATE_CACHE. - // max_bytes: The number of bytes to download before cancelling. - // revalidation_only: If true, the URL is fetched only if it has an existing - // cache entry with conditional headers. - Fetcher(net::URLRequestContextGetter* request_context, - const GURL& url, - const std::string& referrer, - const base::Callback<void(const Fetcher&)>& callback, - bool is_resource_request, - size_t max_bytes, - bool revalidation_only); - ~Fetcher() override; - void OnURLFetchDownloadProgress(const net::URLFetcher* source, - int64_t current, - int64_t total, - int64_t current_network_bytes) override; - void OnURLFetchComplete(const net::URLFetcher* source) override; - int64_t response_bytes() const { return response_bytes_; } - int64_t network_response_bytes() const { return network_response_bytes_; } - const net::URLFetcher* network_url_fetcher() const { - return network_url_fetcher_.get(); - } - const GURL& url() const { return url_; } - const std::string& referrer() const { return referrer_; } - bool is_resource_request() const { return is_resource_request_; } - bool was_cached() const { return was_cached_; } - - private: - enum class FetchStage { CACHE, NETWORK }; - - void LoadFromCache(); - void LoadFromNetwork(); - - // The arguments to this Fetcher's constructor. - net::URLRequestContextGetter* const request_context_; - const GURL url_; - const std::string referrer_; - const base::Callback<void(const Fetcher&)> callback_; - const bool is_resource_request_; - const size_t max_bytes_; - const bool revalidation_only_; - - FetchStage fetch_stage_; - // The cache_url_fetcher_ is kept alive until Fetcher destruction for testing. - std::unique_ptr<net::URLFetcher> cache_url_fetcher_; - std::unique_ptr<net::URLFetcher> network_url_fetcher_; - int64_t response_bytes_; - int64_t network_response_bytes_; - bool was_cached_; - - DISALLOW_COPY_AND_ASSIGN(Fetcher); -}; - -} // namespace precache - -#endif // COMPONENTS_PRECACHE_CORE_PRECACHE_FETCHER_H_
diff --git a/components/precache/core/precache_fetcher_unittest.cc b/components/precache/core/precache_fetcher_unittest.cc deleted file mode 100644 index 178e96b..0000000 --- a/components/precache/core/precache_fetcher_unittest.cc +++ /dev/null
@@ -1,2057 +0,0 @@ -// 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 "components/precache/core/precache_fetcher.h" - -#include <stdint.h> - -#include <cstring> -#include <memory> -#include <set> -#include <string> -#include <utility> -#include <vector> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/command_line.h" -#include "base/compiler_specific.h" -#include "base/files/file_path.h" -#include "base/files/scoped_temp_dir.h" -#include "base/memory/ptr_util.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/run_loop.h" -#include "base/single_thread_task_runner.h" -#include "base/strings/stringprintf.h" -#include "base/test/histogram_tester.h" -#include "base/test/scoped_task_environment.h" -#include "base/threading/thread_task_runner_handle.h" -#include "components/precache/core/precache_database.h" -#include "components/precache/core/precache_switches.h" -#include "components/precache/core/proto/precache.pb.h" -#include "components/precache/core/proto/unfinished_work.pb.h" -#include "net/base/escape.h" -#include "net/base/load_flags.h" -#include "net/http/http_response_headers.h" -#include "net/http/http_response_info.h" -#include "net/http/http_status_code.h" -#include "net/url_request/test_url_fetcher_factory.h" -#include "net/url_request/url_request_status.h" -#include "net/url_request/url_request_test_util.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace precache { - -namespace { - -using ::testing::_; -using ::testing::ElementsAre; -using ::testing::NotNull; -using ::testing::Property; - -const char kConfigURL[] = "http://config-url.com"; -const char kManifestURLPrefix[] = "http://manifest-url-prefix.com/"; -const char kCustomConfigURL[] = "http://custom-config-url.com"; -const char kCustomManifestURLPrefix[] = - "http://custom-manifest-url-prefix.com/"; -const char kManifestFetchFailureURL[] = - "http://manifest-url-prefix.com/manifest-fetch-failure.com"; -const char kBadManifestURL[] = - "http://manifest-url-prefix.com/bad-manifest.com"; -const char kGoodManifestURL[] = - "http://manifest-url-prefix.com/good-manifest.com"; -const char kCustomGoodManifestURL[] = - "http://custom-manifest-url-prefix.com/good-manifest.com"; -const char kResourceFetchFailureURL[] = "http://resource-fetch-failure.com"; -const char kGoodResourceURL[] = "http://good-resource.com"; -const char kGoodResourceURLA[] = "http://good-resource.com/a"; -const char kGoodResourceURLB[] = "http://good-resource.com/b"; -const char kGoodResourceURLC[] = "http://good-resource.com/c"; -const char kGoodResourceURLD[] = "http://good-resource.com/d"; -const char kForcedStartingURLManifestURL[] = - "http://manifest-url-prefix.com/forced-starting-url.com"; -const uint32_t kExperimentID = 123; - -} // namespace - -class TestURLFetcherCallback { - public: - TestURLFetcherCallback() : total_response_bytes_(0) {} - - std::unique_ptr<net::FakeURLFetcher> CreateURLFetcher( - const GURL& url, - net::URLFetcherDelegate* delegate, - const std::string& response_data, - net::HttpStatusCode response_code, - net::URLRequestStatus::Status status) { - std::unique_ptr<net::FakeURLFetcher> fetcher(new net::FakeURLFetcher( - url, delegate, response_data, response_code, status)); - - total_response_bytes_ += response_data.size(); - requested_urls_.push_back(url); - - return fetcher; - } - - const std::vector<GURL>& requested_urls() const { return requested_urls_; } - - void clear_requested_urls() { requested_urls_.clear(); } - - int total_response_bytes() const { return total_response_bytes_; } - - private: - std::vector<GURL> requested_urls_; - int total_response_bytes_; -}; - -class TestPrecacheDelegate : public PrecacheFetcher::PrecacheDelegate { - public: - TestPrecacheDelegate() - : on_done_was_called_(false) {} - - void OnDone() override { - LOG(INFO) << "OnDone"; - on_done_was_called_ = true; - } - - bool was_on_done_called() const { - return on_done_was_called_; - } - - private: - bool on_done_was_called_; -}; - -class MockURLFetcherFactory : public net::URLFetcherFactory { - public: - typedef net::URLFetcher* DoURLFetcher( - int id, - const GURL& url, - net::URLFetcher::RequestType request_type, - net::URLFetcherDelegate* delegate); - - std::unique_ptr<net::URLFetcher> CreateURLFetcher( - int id, - const GURL& url, - net::URLFetcher::RequestType request_type, - net::URLFetcherDelegate* delegate, - net::NetworkTrafficAnnotationTag traffic_annotation) override { - return base::WrapUnique( - DoCreateURLFetcher(id, url, request_type, delegate)); - } - - // The method to mock out, instead of CreateURLFetcher. This is necessary - // because gmock can't handle move-only types such as scoped_ptr. - MOCK_METHOD4(DoCreateURLFetcher, DoURLFetcher); - - // A fake successful response. When the action runs, it saves off a pointer to - // the FakeURLFetcher in its output parameter for later inspection. - testing::Action<DoURLFetcher> RespondWith(const std::string& body, - net::FakeURLFetcher** fetcher) { - return RespondWith(body, [](net::FakeURLFetcher* fetcher) { - fetcher->set_response_code(net::HTTP_OK); - }, fetcher); - } - - // A fake custom response. When the action runs, it runs the given modifier to - // customize the FakeURLFetcher, and then saves off a pointer to the - // FakeURLFetcher in its output parameter for later inspection. The modifier - // should be a functor that takes a FakeURLFetcher* and returns void. - template <typename F> - testing::Action<DoURLFetcher> RespondWith(const std::string& body, - F modifier, - net::FakeURLFetcher** fetcher) { - return testing::MakeAction( - new FakeResponseAction<F>(body, modifier, fetcher)); - } - - private: - template <typename F> - class FakeResponseAction : public testing::ActionInterface<DoURLFetcher> { - public: - FakeResponseAction(const std::string& body, - F modifier, - net::FakeURLFetcher** fetcher) - : body_(body), modifier_(modifier), fetcher_(fetcher) {} - - net::URLFetcher* Perform( - const testing::tuple<int, - const GURL&, - net::URLFetcher::RequestType, - net::URLFetcherDelegate*>& args) { - auto* fetcher = new net::FakeURLFetcher( - testing::get<1>(args), testing::get<3>(args), body_, net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - modifier_(fetcher); - if (fetcher_) - *fetcher_ = fetcher; - return fetcher; - } - - private: - std::string body_; - F modifier_; - net::FakeURLFetcher** fetcher_; - }; -}; - -class PrecacheFetcherFetcherTest : public testing::Test { - public: - PrecacheFetcherFetcherTest() - : scoped_task_environment_( - base::test::ScopedTaskEnvironment::MainThreadType::UI), - request_context_(new net::TestURLRequestContextGetter( - base::ThreadTaskRunnerHandle::Get())), - scoped_url_fetcher_factory_(&factory_), - callback_(base::Bind(&PrecacheFetcherFetcherTest::Callback, - base::Unretained(this))) {} - - MOCK_METHOD1(Callback, void(const PrecacheFetcher::Fetcher&)); - - protected: - base::test::ScopedTaskEnvironment scoped_task_environment_; - scoped_refptr<net::TestURLRequestContextGetter> request_context_; - MockURLFetcherFactory factory_; - net::ScopedURLFetcherFactory scoped_url_fetcher_factory_; - base::Callback<void(const PrecacheFetcher::Fetcher&)> callback_; -}; - -void CacheMiss(net::FakeURLFetcher* fetcher) { - fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, - net::ERR_CACHE_MISS)); -} - -void HasETag(net::FakeURLFetcher* fetcher) { - std::string raw_headers("HTTP/1.1 200 OK\0ETag: foo\0\0", 27); - fetcher->set_response_headers( - make_scoped_refptr(new net::HttpResponseHeaders(raw_headers))); -} - -TEST_F(PrecacheFetcherFetcherTest, Config) { - GURL url(kConfigURL); - - net::FakeURLFetcher* fetcher = nullptr; - EXPECT_CALL(factory_, DoCreateURLFetcher(_, url, net::URLFetcher::GET, _)) - .WillOnce(factory_.RespondWith("", &fetcher)); - EXPECT_CALL(*this, - Callback(Property(&PrecacheFetcher::Fetcher::network_url_fetcher, - NotNull()))); - - PrecacheFetcher::Fetcher precache_fetcher( - request_context_.get(), url, url.host(), callback_, - false /* is_resource_request */, SIZE_MAX, false /* revalidation_only */); - - base::RunLoop().RunUntilIdle(); - - ASSERT_NE(nullptr, fetcher); - EXPECT_EQ(kNoTracking, fetcher->GetLoadFlags()); -} - -TEST_F(PrecacheFetcherFetcherTest, ResourceNotInCache) { - GURL url(kGoodResourceURL); - - net::FakeURLFetcher *fetcher1 = nullptr, *fetcher2 = nullptr; - EXPECT_CALL(factory_, DoCreateURLFetcher(_, url, net::URLFetcher::GET, _)) - .WillOnce(factory_.RespondWith("", CacheMiss, &fetcher1)) - .WillOnce(factory_.RespondWith("", &fetcher2)); - EXPECT_CALL(*this, - Callback(Property(&PrecacheFetcher::Fetcher::network_url_fetcher, - NotNull()))); - - PrecacheFetcher::Fetcher precache_fetcher( - request_context_.get(), url, url.host(), callback_, - true /* is_resource_request */, SIZE_MAX, false /* revalidation_only */); - - base::RunLoop().RunUntilIdle(); - - ASSERT_NE(nullptr, fetcher1); - EXPECT_EQ( - net::LOAD_ONLY_FROM_CACHE | net::LOAD_SKIP_CACHE_VALIDATION | kNoTracking, - fetcher1->GetLoadFlags()); - ASSERT_NE(nullptr, fetcher2); - EXPECT_EQ(net::LOAD_VALIDATE_CACHE | kNoTracking, fetcher2->GetLoadFlags()); -} - -TEST_F(PrecacheFetcherFetcherTest, ResourceHasValidators) { - GURL url(kGoodResourceURL); - - net::FakeURLFetcher *fetcher1 = nullptr, *fetcher2 = nullptr; - EXPECT_CALL(factory_, DoCreateURLFetcher(_, url, net::URLFetcher::GET, _)) - .WillOnce(factory_.RespondWith("", HasETag, &fetcher1)) - .WillOnce(factory_.RespondWith("", &fetcher2)); - EXPECT_CALL(*this, - Callback(Property(&PrecacheFetcher::Fetcher::network_url_fetcher, - NotNull()))); - - PrecacheFetcher::Fetcher precache_fetcher( - request_context_.get(), url, url.host(), callback_, - true /* is_resource_request */, SIZE_MAX, false /* revalidation_only */); - - base::RunLoop().RunUntilIdle(); - - ASSERT_NE(nullptr, fetcher1); - EXPECT_EQ( - net::LOAD_ONLY_FROM_CACHE | net::LOAD_SKIP_CACHE_VALIDATION | kNoTracking, - fetcher1->GetLoadFlags()); - ASSERT_NE(nullptr, fetcher2); - EXPECT_EQ(net::LOAD_VALIDATE_CACHE | kNoTracking, fetcher2->GetLoadFlags()); -} - -TEST_F(PrecacheFetcherFetcherTest, ResourceHasNoValidators) { - GURL url(kGoodResourceURL); - - net::FakeURLFetcher* fetcher = nullptr; - EXPECT_CALL(factory_, DoCreateURLFetcher(_, url, net::URLFetcher::GET, _)) - .WillOnce(factory_.RespondWith("", &fetcher)); - EXPECT_CALL(*this, - Callback(Property(&PrecacheFetcher::Fetcher::network_url_fetcher, - nullptr))); // It never reached the network. - - PrecacheFetcher::Fetcher precache_fetcher( - request_context_.get(), url, url.host(), callback_, - true /* is_resource_request */, SIZE_MAX, false /* revalidation_only */); - - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ( - net::LOAD_ONLY_FROM_CACHE | net::LOAD_SKIP_CACHE_VALIDATION | kNoTracking, - fetcher->GetLoadFlags()); -} - -TEST_F(PrecacheFetcherFetcherTest, RevalidationOnlyResourceNotInCache) { - GURL url(kGoodResourceURL); - - net::FakeURLFetcher* fetcher = nullptr; - EXPECT_CALL(factory_, DoCreateURLFetcher(_, url, net::URLFetcher::GET, _)) - .WillOnce(factory_.RespondWith("", CacheMiss, &fetcher)); - EXPECT_CALL(*this, - Callback(Property(&PrecacheFetcher::Fetcher::network_url_fetcher, - nullptr))); // It never reached the network. - - PrecacheFetcher::Fetcher precache_fetcher( - request_context_.get(), url, url.host(), callback_, - true /* is_resource_request */, SIZE_MAX, true /* revalidation_only */); - - base::RunLoop().RunUntilIdle(); - - ASSERT_NE(nullptr, fetcher); - EXPECT_EQ( - net::LOAD_ONLY_FROM_CACHE | net::LOAD_SKIP_CACHE_VALIDATION | kNoTracking, - fetcher->GetLoadFlags()); -} - -TEST_F(PrecacheFetcherFetcherTest, RevalidationOnlyResourceHasValidators) { - GURL url(kGoodResourceURL); - - net::FakeURLFetcher *fetcher1 = nullptr, *fetcher2 = nullptr; - EXPECT_CALL(factory_, DoCreateURLFetcher(_, url, net::URLFetcher::GET, _)) - .WillOnce(factory_.RespondWith("", HasETag, &fetcher1)) - .WillOnce(factory_.RespondWith("", &fetcher2)); - EXPECT_CALL(*this, - Callback(Property(&PrecacheFetcher::Fetcher::network_url_fetcher, - NotNull()))); - - PrecacheFetcher::Fetcher precache_fetcher( - request_context_.get(), url, url.host(), callback_, - true /* is_resource_request */, SIZE_MAX, true /* revalidation_only */); - - base::RunLoop().RunUntilIdle(); - - ASSERT_NE(nullptr, fetcher1); - EXPECT_EQ( - net::LOAD_ONLY_FROM_CACHE | net::LOAD_SKIP_CACHE_VALIDATION | kNoTracking, - fetcher1->GetLoadFlags()); - ASSERT_NE(nullptr, fetcher2); - EXPECT_EQ(net::LOAD_VALIDATE_CACHE | kNoTracking, fetcher2->GetLoadFlags()); -} - -TEST_F(PrecacheFetcherFetcherTest, RevalidationOnlyResourceHasNoValidators) { - GURL url(kGoodResourceURL); - - net::FakeURLFetcher* fetcher = nullptr; - EXPECT_CALL(factory_, DoCreateURLFetcher(_, url, net::URLFetcher::GET, _)) - .WillOnce(factory_.RespondWith("", &fetcher)); - EXPECT_CALL(*this, - Callback(Property(&PrecacheFetcher::Fetcher::network_url_fetcher, - nullptr))); // It never reached the network. - - PrecacheFetcher::Fetcher precache_fetcher( - request_context_.get(), url, url.host(), callback_, - true /* is_resource_request */, SIZE_MAX, true /* revalidation_only */); - - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ( - net::LOAD_ONLY_FROM_CACHE | net::LOAD_SKIP_CACHE_VALIDATION | kNoTracking, - fetcher->GetLoadFlags()); -} - -TEST_F(PrecacheFetcherFetcherTest, ResourceTooBig) { - GURL url(kGoodResourceURL); - - EXPECT_CALL(factory_, DoCreateURLFetcher(_, url, net::URLFetcher::GET, _)) - // Cache request will fail, so that a network request is made. Only - // network requests are byte-capped. - .WillOnce(factory_.RespondWith("", CacheMiss, nullptr)) - .WillOnce(factory_.RespondWith(std::string(100, '.'), nullptr)); - - // The callback should be called even though the download was cancelled, so - // that the next download can start. The network_url_fetcher within should be - // null, to signify that either the network was never reached (which will be - // flagged as an error due to the expectation above) or it was requested but - // cancelled (which is the desired behavior). - EXPECT_CALL(*this, - Callback(Property(&PrecacheFetcher::Fetcher::network_url_fetcher, - nullptr))); - - PrecacheFetcher::Fetcher precache_fetcher( - request_context_.get(), url, url.host(), callback_, - true /* is_resource_request */, 99 /* max_bytes */, - false /* revalidation_only */); - - base::RunLoop().RunUntilIdle(); -} - -class PrecacheFetcherTest : public testing::Test { - public: - PrecacheFetcherTest() - : scoped_task_environment_( - base::test::ScopedTaskEnvironment::MainThreadType::UI), - task_runner_(base::ThreadTaskRunnerHandle::Get()), - request_context_(new net::TestURLRequestContextGetter( - base::ThreadTaskRunnerHandle::Get())), - factory_(NULL, - base::Bind(&TestURLFetcherCallback::CreateURLFetcher, - base::Unretained(&url_callback_))), - expected_total_response_bytes_(0), - parallel_fetches_beyond_capacity_(false) {} - - void UpdatePrecacheReferrerHost(const std::string& hostname, - int64_t manifest_id) { - precache_database_.UpdatePrecacheReferrerHost(hostname, manifest_id, - base::Time()); - } - - void RecordURLPrefetch(const GURL& url, const std::string& referrer_host) { - precache_database_.RecordURLPrefetch(url, referrer_host, base::Time::Now(), - false /* was_cached */, - 1000 /* size */); - } - - void RecordURLNonPrefetch(const GURL& url) { - net::HttpResponseInfo info; - info.was_cached = true; - info.headers = new net::HttpResponseHeaders(std::string()); - precache_database_.RecordURLNonPrefetch(url, base::Time::Now(), info, - 1000 /* size */, 0 /* host_rank */, - false /* is_connection_cellular */); - } - - protected: - void SetUp() override { - ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); - base::FilePath db_path = scoped_temp_dir_.GetPath().Append( - base::FilePath(FILE_PATH_LITERAL("precache_database"))); - precache_database_.Init(db_path); - } - void SetDefaultFlags() { - base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kPrecacheConfigSettingsURL, kConfigURL); - base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kPrecacheManifestURLPrefix, kManifestURLPrefix); - } - - // Posts a task to check if more parallel fetches of precache manifest and - // resource URLs were attempted beyond the fetcher pool maximum defined - // capacity. The task will be posted repeatedly until such condition is met. - void CheckUntilParallelFetchesBeyondCapacity( - const PrecacheFetcher* precache_fetcher) { - if (!precache_fetcher->pool_.IsAvailable() && - (!precache_fetcher->top_hosts_to_fetch_.empty() || - !precache_fetcher->resources_to_fetch_.empty())) { - parallel_fetches_beyond_capacity_ = true; - return; - } - - // Check again after allowing the message loop to process some messages. - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind( - &PrecacheFetcherTest::CheckUntilParallelFetchesBeyondCapacity, - base::Unretained(this), precache_fetcher)); - } - - const scoped_refptr<base::SingleThreadTaskRunner>& task_runner() const { - return task_runner_; - } - - // To allow friend access. - void Flush() { precache_database_.Flush(); } - - // Must be declared first so that it is destroyed last. - base::test::ScopedTaskEnvironment scoped_task_environment_; - scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - scoped_refptr<net::TestURLRequestContextGetter> request_context_; - TestURLFetcherCallback url_callback_; - net::FakeURLFetcherFactory factory_; - TestPrecacheDelegate precache_delegate_; - base::ScopedTempDir scoped_temp_dir_; - PrecacheDatabase precache_database_; - int expected_total_response_bytes_; - - // True if more parallel fetches were attempted beyond the fetcher pool - // maximum capacity. - bool parallel_fetches_beyond_capacity_; -}; - -TEST_F(PrecacheFetcherTest, FullPrecache) { - SetDefaultFlags(); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - unfinished_work->add_top_host()->set_hostname("manifest-fetch-failure.com"); - unfinished_work->add_top_host()->set_hostname("bad-manifest.com"); - unfinished_work->add_top_host()->set_hostname("good-manifest.com"); - unfinished_work->add_top_host()->set_hostname("not-in-top-3.com"); - - PrecacheConfigurationSettings config; - config.set_top_sites_count(3); - config.add_forced_site("forced-starting-url.com"); - // Duplicate starting URL, the manifest for this should only be fetched once. - config.add_forced_site("good-manifest.com"); - - PrecacheManifest good_manifest; - good_manifest.add_resource()->set_url(kResourceFetchFailureURL); - good_manifest.add_resource(); // Resource with no URL, should not be fetched. - good_manifest.add_resource()->set_url(kGoodResourceURL); - - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kManifestFetchFailureURL), "", - net::HTTP_INTERNAL_SERVER_ERROR, - net::URLRequestStatus::FAILED); - factory_.SetFakeResponse(GURL(kBadManifestURL), "bad protobuf", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodManifestURL), - good_manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kResourceFetchFailureURL), - "", net::HTTP_INTERNAL_SERVER_ERROR, - net::URLRequestStatus::FAILED); - factory_.SetFakeResponse(GURL(kGoodResourceURL), "good", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kForcedStartingURLManifestURL), - PrecacheManifest().SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - - // Destroy the PrecacheFetcher after it has finished, to record metrics. - } - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kConfigURL); - expected_requested_urls.emplace_back(kManifestFetchFailureURL); - expected_requested_urls.emplace_back(kBadManifestURL); - expected_requested_urls.emplace_back(kGoodManifestURL); - expected_requested_urls.emplace_back(kForcedStartingURLManifestURL); - expected_requested_urls.emplace_back(kResourceFetchFailureURL); - expected_requested_urls.emplace_back(kGoodResourceURL); - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - histogram.ExpectUniqueSample("Precache.Fetch.PercentCompleted", 100, 1); - histogram.ExpectUniqueSample("Precache.Fetch.ResponseBytes.Total", - url_callback_.total_response_bytes(), 1); - histogram.ExpectTotalCount("Precache.Fetch.TimeToComplete", 1); -} - -class PrecacheFetcherResourceSelectionTest - : public PrecacheFetcherTest, - public testing::WithParamInterface<PrecacheResourceSelection> { - public: - // These bitsets are asymmetric and multibyte, in order to test the orderings. - - // Set bits for kGoodResourceURL, kGoodResourceURLC and kGoodResourceURLD. - static PrecacheResourceSelection DeprecatedBitset() { - PrecacheResourceSelection ret; - ret.set_deprecated_bitset(0b110000000001); - return ret; - } - - // Set bits for kGoodResourceURL, kGoodResourceURLC and kGoodResourceURLD. - static PrecacheResourceSelection Bitset() { - PrecacheResourceSelection ret; - ret.set_bitset("\x01\x0c"); - return ret; - } -}; - -TEST_P(PrecacheFetcherResourceSelectionTest, Basic) { - SetDefaultFlags(); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("good-manifest.com"); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - - PrecacheConfigurationSettings config; - - PrecacheManifest good_manifest; - PrecacheResourceSelection resource_selection; - good_manifest.add_resource()->set_url(kGoodResourceURL); - good_manifest.add_resource()->set_url(kGoodResourceURLA); - for (int i = 0; i < 8; ++i) - good_manifest.add_resource()->set_url(kGoodResourceURLB); - good_manifest.add_resource()->set_url(kGoodResourceURLC); - good_manifest.add_resource()->set_url(kGoodResourceURLD); - - (*good_manifest.mutable_experiments() - ->mutable_resources_by_experiment_group())[kExperimentID] = GetParam(); - - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodManifestURL), - good_manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodResourceURL), "good", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodResourceURLC), "good URL B", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodResourceURLD), "good URL D", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - - // Destroy the PrecacheFetcher after it has finished, to record metrics. - } - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kConfigURL); - expected_requested_urls.emplace_back(kGoodManifestURL); - expected_requested_urls.emplace_back(kGoodResourceURL); - expected_requested_urls.emplace_back(kGoodResourceURLC); - expected_requested_urls.emplace_back(kGoodResourceURLD); - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - histogram.ExpectUniqueSample("Precache.Fetch.PercentCompleted", 100, 1); - histogram.ExpectUniqueSample("Precache.Fetch.ResponseBytes.Total", - url_callback_.total_response_bytes(), 1); - histogram.ExpectTotalCount("Precache.Fetch.TimeToComplete", 1); -} - -TEST_P(PrecacheFetcherResourceSelectionTest, MissingBitset) { - SetDefaultFlags(); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("good-manifest.com"); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - - PrecacheConfigurationSettings config; - - PrecacheManifest good_manifest; - PrecacheResourceSelection resource_selection; - good_manifest.add_resource()->set_url(kGoodResourceURL); - good_manifest.add_resource()->set_url(kGoodResourceURLA); - good_manifest.add_resource()->set_url(kGoodResourceURLB); - good_manifest.add_resource()->set_url(kGoodResourceURLC); - good_manifest.add_resource()->set_url(kGoodResourceURLD); - - // Set bits for a different experiment group. - (*good_manifest.mutable_experiments() - ->mutable_resources_by_experiment_group())[kExperimentID + 1] = - GetParam(); - - // Resource selection bitset for the experiment group will be missing and all - // resources will be fetched. - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodManifestURL), - good_manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodResourceURL), "good", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodResourceURLA), "good URL A", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodResourceURLB), "good URL B", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodResourceURLC), "good URL C", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodResourceURLD), "good URL D", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - - // Destroy the PrecacheFetcher after it has finished, to record metrics. - } - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kConfigURL); - expected_requested_urls.emplace_back(kGoodManifestURL); - expected_requested_urls.emplace_back(kGoodResourceURL); - expected_requested_urls.emplace_back(kGoodResourceURLA); - expected_requested_urls.emplace_back(kGoodResourceURLB); - expected_requested_urls.emplace_back(kGoodResourceURLC); - expected_requested_urls.emplace_back(kGoodResourceURLD); - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - histogram.ExpectUniqueSample("Precache.Fetch.PercentCompleted", 100, 1); - histogram.ExpectUniqueSample("Precache.Fetch.ResponseBytes.Total", - url_callback_.total_response_bytes(), 1); - histogram.ExpectTotalCount("Precache.Fetch.TimeToComplete", 1); -} - -INSTANTIATE_TEST_CASE_P( - PrecacheFetcherResourceSelectionTest, - PrecacheFetcherResourceSelectionTest, - testing::Values(PrecacheFetcherResourceSelectionTest::DeprecatedBitset(), - PrecacheFetcherResourceSelectionTest::Bitset())); - -TEST_F(PrecacheFetcherTest, PrecachePauseResume) { - SetDefaultFlags(); - - PrecacheConfigurationSettings config; - config.set_top_sites_count(3); - - std::unique_ptr<PrecacheUnfinishedWork> initial_work( - new PrecacheUnfinishedWork()); - initial_work->add_top_host()->set_hostname("manifest1.com"); - initial_work->add_top_host()->set_hostname("manifest2.com"); - initial_work->set_start_time( - (base::Time::Now() - base::TimeDelta::FromHours(1)).ToInternalValue()); - - PrecacheFetcher first_fetcher(request_context_.get(), GURL(), std::string(), - std::move(initial_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), - &precache_delegate_); - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - first_fetcher.Start(); - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work = - first_fetcher.CancelPrecaching(); - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kConfigURL); - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kBadManifestURL), "bad protobuf", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL("http://manifest-url-prefix.com/manifest1.com"), - "bad protobuf", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL("http://manifest-url-prefix.com/manifest2.com"), - "bad protobuf", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodResourceURL), "good", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - url_callback_.clear_requested_urls(); - PrecacheFetcher second_fetcher(request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), - &precache_delegate_); - second_fetcher.Start(); - base::RunLoop().RunUntilIdle(); - expected_requested_urls.emplace_back( - "http://manifest-url-prefix.com/manifest1.com"); - expected_requested_urls.emplace_back( - "http://manifest-url-prefix.com/manifest2.com"); - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); -} - -TEST_F(PrecacheFetcherTest, ResumeWithConfigOnly) { - SetDefaultFlags(); - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->mutable_config_settings()->add_forced_site( - "good-manifest.com"); - unfinished_work->set_start_time(base::Time::Now().ToInternalValue()); - PrecacheManifest good_manifest; - good_manifest.add_resource()->set_url(kGoodResourceURL); - - factory_.SetFakeResponse(GURL(kGoodManifestURL), - good_manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodResourceURL), "good", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - } - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kGoodManifestURL); - expected_requested_urls.emplace_back(kGoodResourceURL); - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); -} - - -TEST_F(PrecacheFetcherTest, CustomURLs) { - SetDefaultFlags(); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("good-manifest.com"); - - PrecacheConfigurationSettings config; - - PrecacheManifest good_manifest; - good_manifest.add_resource()->set_url(kGoodResourceURL); - - factory_.SetFakeResponse(GURL(kCustomConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kCustomGoodManifestURL), - good_manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodResourceURL), "good", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(kCustomConfigURL), kCustomManifestURLPrefix, - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kCustomConfigURL); - expected_requested_urls.emplace_back(kCustomGoodManifestURL); - expected_requested_urls.emplace_back(kGoodResourceURL); - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); -} - -TEST_F(PrecacheFetcherTest, ConfigFetchFailure) { - SetDefaultFlags(); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("good-manifest.com"); - - factory_.SetFakeResponse(GURL(kConfigURL), "", - net::HTTP_INTERNAL_SERVER_ERROR, - net::URLRequestStatus::FAILED); - factory_.SetFakeResponse(GURL(kGoodManifestURL), "", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), std::move(unfinished_work), - kExperimentID, precache_database_.GetWeakPtr(), task_runner(), - &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kConfigURL); - expected_requested_urls.emplace_back(kGoodManifestURL); - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); -} - -TEST_F(PrecacheFetcherTest, BadConfig) { - SetDefaultFlags(); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("good-manifest.com"); - - factory_.SetFakeResponse(GURL(kConfigURL), "bad protobuf", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodManifestURL), "", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), std::move(unfinished_work), - kExperimentID, precache_database_.GetWeakPtr(), task_runner(), - &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kConfigURL); - expected_requested_urls.emplace_back(kGoodManifestURL); - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); -} - -TEST_F(PrecacheFetcherTest, Cancel) { - SetDefaultFlags(); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("starting-url.com"); - - PrecacheConfigurationSettings config; - config.set_top_sites_count(1); - - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - // Destroy the PrecacheFetcher, to cancel precaching. No metrics - // should be recorded because this should not cause OnDone to be - // called on the precache delegate. - } - - base::RunLoop().RunUntilIdle(); - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kConfigURL); - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_FALSE(precache_delegate_.was_on_done_called()); - - histogram.ExpectTotalCount("Precache.Fetch.TimeToComplete", 0); -} - -#if defined(PRECACHE_CONFIG_SETTINGS_URL) - -// If the default precache configuration settings URL is defined, then test that -// it works with the PrecacheFetcher. -TEST_F(PrecacheFetcherTest, PrecacheUsingDefaultConfigSettingsURL) { - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("starting-url.com"); - - PrecacheConfigurationSettings config; - config.set_top_sites_count(0); - - factory_.SetFakeResponse(GURL(PRECACHE_CONFIG_SETTINGS_URL), - config.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), std::move(unfinished_work), - kExperimentID, precache_database_.GetWeakPtr(), task_runner(), - &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(PRECACHE_CONFIG_SETTINGS_URL); - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); -} - -#endif // PRECACHE_CONFIG_SETTINGS_URL - -#if defined(PRECACHE_MANIFEST_URL_PREFIX) - -// If the default precache manifest URL prefix is defined, then test that it -// works with the PrecacheFetcher. -TEST_F(PrecacheFetcherTest, PrecacheUsingDefaultManifestURLPrefix) { - base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kPrecacheConfigSettingsURL, kConfigURL); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("starting-url.com"); - - PrecacheConfigurationSettings config; - config.set_top_sites_count(1); - - GURL manifest_url(PRECACHE_MANIFEST_URL_PREFIX "starting-url.com"); - - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(manifest_url, PrecacheManifest().SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), std::move(unfinished_work), - kExperimentID, precache_database_.GetWeakPtr(), task_runner(), - &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kConfigURL); - expected_requested_urls.push_back(manifest_url); - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); -} - -#endif // PRECACHE_MANIFEST_URL_PREFIX - -TEST_F(PrecacheFetcherTest, TopResourcesCount) { - SetDefaultFlags(); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - unfinished_work->add_top_host()->set_hostname("good-manifest.com"); - - PrecacheConfigurationSettings config; - config.set_top_resources_count(3); - - PrecacheManifest good_manifest; - good_manifest.add_resource()->set_url("http://good-manifest.com/retrieved"); - good_manifest.add_resource()->set_url("http://good-manifest.com/retrieved"); - good_manifest.add_resource()->set_url("http://good-manifest.com/retrieved"); - good_manifest.add_resource()->set_url("http://good-manifest.com/skipped"); - good_manifest.add_resource()->set_url("http://good-manifest.com/skipped"); - - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodManifestURL), - good_manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL("http://good-manifest.com/retrieved"), "good", - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - - // Destroy the PrecacheFetcher after it has finished, to record metrics. - } - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kConfigURL); - expected_requested_urls.emplace_back(kGoodManifestURL); - expected_requested_urls.emplace_back("http://good-manifest.com/retrieved"); - expected_requested_urls.emplace_back("http://good-manifest.com/retrieved"); - expected_requested_urls.emplace_back("http://good-manifest.com/retrieved"); - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - histogram.ExpectUniqueSample("Precache.Fetch.PercentCompleted", 100, 1); - histogram.ExpectUniqueSample("Precache.Fetch.ResponseBytes.Total", - url_callback_.total_response_bytes(), 1); - histogram.ExpectTotalCount("Precache.Fetch.TimeToComplete", 1); -} - -TEST_F(PrecacheFetcherTest, TopResourcesCount_ResourceBitset) { - SetDefaultFlags(); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - unfinished_work->add_top_host()->set_hostname("good-manifest.com"); - - PrecacheConfigurationSettings config; - config.set_top_resources_count(2); - - PrecacheManifest good_manifest; - good_manifest.add_resource()->set_url("http://good-manifest.com/retrieved"); - good_manifest.add_resource()->set_url("http://good-manifest.com/skipped"); - good_manifest.add_resource()->set_url("http://good-manifest.com/retrieved"); - good_manifest.add_resource()->set_url("http://good-manifest.com/skipped"); - good_manifest.add_resource()->set_url("http://good-manifest.com/retrieved"); - (*good_manifest.mutable_experiments() - ->mutable_resources_by_experiment_group())[kExperimentID] - .set_deprecated_bitset(0b10101); - - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(kGoodManifestURL), - good_manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL("http://good-manifest.com/retrieved"), "good", - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - - // Destroy the PrecacheFetcher after it has finished, to record metrics. - } - - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kConfigURL); - expected_requested_urls.emplace_back(kGoodManifestURL); - expected_requested_urls.emplace_back("http://good-manifest.com/retrieved"); - expected_requested_urls.emplace_back("http://good-manifest.com/retrieved"); - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - histogram.ExpectUniqueSample("Precache.Fetch.PercentCompleted", 100, 1); - histogram.ExpectUniqueSample("Precache.Fetch.ResponseBytes.Total", - url_callback_.total_response_bytes(), 1); - histogram.ExpectTotalCount("Precache.Fetch.TimeToComplete", 1); -} - -// MaxBytesPerResource is impossible to test with net::FakeURLFetcherFactory: -// -// - The PrecacheFetcher::Fetcher's max_bytes logic only applies to network -// requests, and not cached requests. -// - Forcing PrecacheFetcher::Fetcher to do a network request (i.e. a second -// request for the same URL) requires either setting a custom error of -// ERR_CACHE_MISS or setting a custom ETag response header, neither of which -// is possible under FakeURLFetcherFactory. -// -// PrecacheFetcherFetcherTest.ResourceTooBig tests the bulk of the code. We'll -// assume that PrecacheFetcher passes the right max_bytes to the -// PrecacheFetcher::Fetcher constructor. -// -// TODO(twifkak): Port these tests from FakeURLFetcherFactory to -// MockURLFetcherFactory or EmbeddedTestServer, and add a test that fetches are -// cancelled midstream. - -TEST_F(PrecacheFetcherTest, MaxBytesTotal) { - SetDefaultFlags(); - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - auto* top_host = unfinished_work->add_top_host(); - top_host->set_hostname("good-manifest.com"); - top_host->set_visits(1); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - - // Should be greater than kMaxParallelFetches, so that we can observe - // PrecacheFetcher not fetching the remaining resources after max bytes is - // exceeded. - const size_t kNumResources = kMaxParallelFetches + 5; - // Should be smaller than kNumResources - kMaxParallelFetches, such that the - // max bytes is guaranteed to be exceeded before all fetches have been - // requested. In this case, after 3 fetches have been completed, 3 more are - // added to the fetcher pool, but 2 out of 5 still remain. - const size_t kResourcesWithinMax = 3; - // Should be big enough that the size of the config, manifest, and HTTP - // headers are negligible for max bytes computation. - const size_t kBytesPerResource = 500; - const size_t kMaxBytesTotal = kResourcesWithinMax * kBytesPerResource; - - PrecacheConfigurationSettings config; - config.set_max_bytes_total(kMaxBytesTotal); - config.set_global_ranking(true); - - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - - PrecacheManifest good_manifest; - for (size_t i = 0; i < kNumResources; ++i) { - const std::string url = "http://good-manifest.com/" + std::to_string(i); - auto* resource = good_manifest.add_resource(); - resource->set_url(url); - resource->set_weight_ratio(static_cast<double>(i) / kNumResources); - factory_.SetFakeResponse(GURL(url), std::string(kBytesPerResource, '.'), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - } - - factory_.SetFakeResponse(GURL(kGoodManifestURL), - good_manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - } - - // Fetcher should request config, manifest, and all but 3 resources. For some - // reason, we are seeing it fetch all but 4 resources. Meh, close enough. - EXPECT_EQ(1 + 1 + kNumResources - 4, url_callback_.requested_urls().size()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - histogram.ExpectTotalCount("Precache.Fetch.PercentCompleted", 1); - histogram.ExpectTotalCount("Precache.Fetch.TimeToComplete", 1); - - const double expected_min_weight = - good_manifest.resource(kNumResources - 3).weight_ratio() * - 1 /* # of visits to good-manifest.com */; - histogram.ExpectBucketCount("Precache.Fetch.MinWeight", - 1000.0 * expected_min_weight, 1); -} - -// Tests the parallel fetch behaviour when more precache resource and manifest -// requests are available than the maximum capacity of fetcher pool. -TEST_F(PrecacheFetcherTest, FetcherPoolMaxLimitReached) { - SetDefaultFlags(); - - const size_t kNumTopHosts = 5; - const size_t kNumResources = kMaxParallelFetches + 5; - - PrecacheConfigurationSettings config; - std::vector<GURL> expected_requested_urls; - - config.set_top_sites_count(kNumTopHosts); - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - expected_requested_urls.emplace_back(kConfigURL); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - - for (size_t i = 0; i < kNumTopHosts; ++i) { - const std::string top_host_url = base::StringPrintf("top-host-%zu.com", i); - expected_requested_urls.emplace_back(kManifestURLPrefix + top_host_url); - } - - for (size_t i = 0; i < kNumTopHosts; ++i) { - const std::string top_host_url = base::StringPrintf("top-host-%zu.com", i); - unfinished_work->add_top_host()->set_hostname(top_host_url); - - PrecacheManifest manifest; - for (size_t j = 0; j < kNumResources; ++j) { - const std::string resource_url = - base::StringPrintf("http://top-host-%zu.com/resource-%zu", i, j); - manifest.add_resource()->set_url(resource_url); - factory_.SetFakeResponse(GURL(resource_url), "good", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - expected_requested_urls.emplace_back(resource_url); - } - factory_.SetFakeResponse(GURL(kManifestURLPrefix + top_host_url), - manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - } - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - EXPECT_GT(kNumResources, precache_fetcher.pool_.max_size()); - CheckUntilParallelFetchesBeyondCapacity(&precache_fetcher); - - base::RunLoop().RunUntilIdle(); - - // Destroy the PrecacheFetcher after it has finished, to record metrics. - } - - EXPECT_TRUE(parallel_fetches_beyond_capacity_); - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - histogram.ExpectUniqueSample("Precache.Fetch.PercentCompleted", 100, 1); - histogram.ExpectUniqueSample("Precache.Fetch.ResponseBytes.Total", - url_callback_.total_response_bytes(), 1); - histogram.ExpectTotalCount("Precache.Fetch.TimeToComplete", 1); -} - -TEST_F(PrecacheFetcherTest, FilterInvalidManifestUrls) { - SetDefaultFlags(); - base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kPrecacheManifestURLPrefix, "invalid-manifest-prefix"); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("manifest.com"); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - - factory_.SetFakeResponse(GURL(kConfigURL), "", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - } - - // The config is fetched, but not the invalid manifest URL. - EXPECT_EQ(1UL, url_callback_.requested_urls().size()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - // manifest.com will have been failed to complete, in this case. - EXPECT_THAT(histogram.GetAllSamples("Precache.Fetch.PercentCompleted"), - ElementsAre(base::Bucket(101, 1))); - histogram.ExpectTotalCount("Precache.Fetch.TimeToComplete", 1); -} - -TEST_F(PrecacheFetcherTest, FilterInvalidResourceUrls) { - SetDefaultFlags(); - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("bad-manifest.com"); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - - factory_.SetFakeResponse(GURL(kConfigURL), "", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - PrecacheManifest bad_manifest; - bad_manifest.add_resource()->set_url("http://"); - - factory_.SetFakeResponse(GURL(kBadManifestURL), - bad_manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - } - - // The config and manifest are fetched, but not the invalid resource URL. - EXPECT_EQ(2UL, url_callback_.requested_urls().size()); - - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - // bad-manifest.com will have been completed. - EXPECT_THAT(histogram.GetAllSamples("Precache.Fetch.PercentCompleted"), - ElementsAre(base::Bucket(101, 1))); - histogram.ExpectTotalCount("Precache.Fetch.TimeToComplete", 1); -} - -TEST(PrecacheFetcherStandaloneTest, GetResourceURLBase64Hash) { - // Expected base64 hash for some selected URLs. - EXPECT_EQ("dVSI/sC1cGk=", PrecacheFetcher::GetResourceURLBase64HashForTesting( - {GURL("http://used-resource-1/a.js")})); - EXPECT_EQ("B/Jc6JvusZQ=", PrecacheFetcher::GetResourceURLBase64HashForTesting( - {GURL("http://used-resource-1/b.js")})); - EXPECT_EQ("CmvACGJ4k08=", PrecacheFetcher::GetResourceURLBase64HashForTesting( - {GURL("http://used-resource-1/c.js")})); - - EXPECT_EQ("dVSI/sC1cGkH8lzom+6xlA==", - PrecacheFetcher::GetResourceURLBase64HashForTesting( - {GURL("http://used-resource-1/a.js"), - GURL("http://used-resource-1/b.js")})); -} - -TEST_F(PrecacheFetcherTest, SendUsedDownloadedResourceHash) { - SetDefaultFlags(); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - unfinished_work->add_top_host()->set_hostname("top-host-1.com"); - unfinished_work->add_top_host()->set_hostname("top-host-2.com"); - unfinished_work->add_top_host()->set_hostname("top-host-3.com"); - - UpdatePrecacheReferrerHost("top-host-1.com", 1001); - UpdatePrecacheReferrerHost("top-host-2.com", 1002); - UpdatePrecacheReferrerHost("top-host-3.com", 1003); - - // Mark some resources as precached. - RecordURLPrefetch(GURL("http://used-resource-1/a.js"), "top-host-1.com"); - RecordURLPrefetch(GURL("http://used-resource-1/b.js"), "top-host-1.com"); - RecordURLPrefetch(GURL("http://unused-resource-1/c.js"), "top-host-1.com"); - RecordURLPrefetch(GURL("http://unused-resource-2/a.js"), "top-host-2.com"); - RecordURLPrefetch(GURL("http://unused-resource-2/b.js"), "top-host-2.com"); - base::RunLoop().RunUntilIdle(); - - // Mark some resources as used during user browsing. - RecordURLNonPrefetch(GURL("http://used-resource-1/a.js")); - RecordURLNonPrefetch(GURL("http://used-resource-1/b.js")); - base::RunLoop().RunUntilIdle(); - - factory_.SetFakeResponse(GURL(kConfigURL), std::string(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse( - GURL(std::string(kManifestURLPrefix) + - "top-host-1.com?manifest=1001&used_resources=" + - net::EscapeQueryParamValue( - PrecacheFetcher::GetResourceURLBase64HashForTesting( - {GURL("http://used-resource-1/a.js"), - GURL("http://used-resource-1/b.js")}), - true) + - "&d=" + net::EscapeQueryParamValue( - PrecacheFetcher::GetResourceURLBase64HashForTesting( - {GURL("http://used-resource-1/a.js"), - GURL("http://used-resource-1/b.js"), - GURL("http://unused-resource-1/c.js")}), - true)), - std::string(), net::HTTP_OK, net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse( - GURL(std::string(kManifestURLPrefix) + - "top-host-2.com?manifest=1002&used_resources=&d=" + - net::EscapeQueryParamValue( - PrecacheFetcher::GetResourceURLBase64HashForTesting( - {GURL("http://unused-resource-2/a.js"), - GURL("http://unused-resource-2/b.js")}), - true)), - std::string(), net::HTTP_OK, net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse( - GURL(std::string(kManifestURLPrefix) + - "top-host-3.com?manifest=1003&used_resources=&d="), - std::string(), net::HTTP_OK, net::URLRequestStatus::SUCCESS); - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - } - - // If we run the precache again, no download should be reported. - factory_.ClearFakeResponses(); - factory_.SetFakeResponse(GURL(kConfigURL), std::string(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - // Since we returned an empty proto, the manifest id was set to 0. - // The d='s are empty because precache fetches are tried first solely from the - // cache and, since any matching request to the fake factory succeeds, it is - // hardcoded to be cached even though we didn't specify it as such in the fake - // response. - factory_.SetFakeResponse(GURL(std::string(kManifestURLPrefix) + - "top-host-1.com?manifest=0&used_resources=&d="), - std::string(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(std::string(kManifestURLPrefix) + - "top-host-2.com?manifest=0&used_resources=&d="), - std::string(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - factory_.SetFakeResponse(GURL(std::string(kManifestURLPrefix) + - "top-host-3.com?manifest=0&used_resources=&d="), - std::string(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - // Flush so that previous UpdatePrecacheReferrerHost calls make it through. - // Otherwise, manifest_id may be non 0 for some of the hosts. - Flush(); - { - std::unique_ptr<PrecacheUnfinishedWork> more_work( - new PrecacheUnfinishedWork()); - more_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - more_work->add_top_host()->set_hostname("top-host-1.com"); - more_work->add_top_host()->set_hostname("top-host-2.com"); - more_work->add_top_host()->set_hostname("top-host-3.com"); - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), std::move(more_work), - kExperimentID, precache_database_.GetWeakPtr(), task_runner(), - &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - } -} - -TEST(PrecacheFetcherResourceWeightTest, Naive) { - ASSERT_EQ( - 0, ResourceWeight(PrecacheConfigurationSettings::FUNCTION_NAIVE, 0, 100)); - ASSERT_EQ( - 4, ResourceWeight(PrecacheConfigurationSettings::FUNCTION_NAIVE, 1, 4)); - ASSERT_EQ(8, ResourceWeight(PrecacheConfigurationSettings::FUNCTION_NAIVE, - 0.5, 16)); -} - -TEST(PrecacheFetcherResourceWeightTest, Geometric) { - ASSERT_EQ(0, ResourceWeight(PrecacheConfigurationSettings::FUNCTION_GEOMETRIC, - 0, 100)); - ASSERT_EQ(1, ResourceWeight(PrecacheConfigurationSettings::FUNCTION_GEOMETRIC, - 1, 4)); - ASSERT_NEAR(0.9999847, - ResourceWeight(PrecacheConfigurationSettings::FUNCTION_GEOMETRIC, - 0.5, 16), - 0.0000001); -} - -class PrecacheFetcherGlobalRankingTest - : public PrecacheFetcherTest, - public testing::WithParamInterface< - PrecacheConfigurationSettings::ResourceWeightFunction> {}; - -TEST_P(PrecacheFetcherGlobalRankingTest, GloballyRankResources) { - SetDefaultFlags(); - - const size_t kNumTopHosts = 5; - const size_t kNumResources = 5; - - std::vector<GURL> expected_requested_urls; - - PrecacheConfigurationSettings config; - config.set_top_sites_count(kNumTopHosts); - config.set_global_ranking(true); - config.set_resource_weight_function(GetParam()); - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - expected_requested_urls.emplace_back(kConfigURL); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - - for (size_t i = 0; i < kNumTopHosts; ++i) { - const std::string top_host_url = base::StringPrintf("top-host-%zu.com", i); - expected_requested_urls.emplace_back(kManifestURLPrefix + top_host_url); - } - - // Visit counts and weights are chosen in such a way that resource requests - // between different hosts will be interleaved. - std::vector<std::pair<std::string, float>> resources; - for (size_t i = 0; i < kNumTopHosts; ++i) { - const std::string top_host_url = base::StringPrintf("top-host-%zu.com", i); - TopHost* top_host = unfinished_work->add_top_host(); - top_host->set_hostname(top_host_url); - top_host->set_visits(kNumTopHosts - i); - - PrecacheManifest manifest; - for (size_t j = 0; j < kNumResources; ++j) { - const float weight = 1 - static_cast<float>(j) / kNumResources; - const std::string resource_url = - base::StringPrintf("http://top-host-%zu.com/resource-%zu-weight-%.1f", - i, j, top_host->visits() * weight); - PrecacheResource* resource = manifest.add_resource(); - resource->set_url(resource_url); - resource->set_weight_ratio(weight); - factory_.SetFakeResponse(GURL(resource_url), "good", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - resources.emplace_back( - resource_url, ResourceWeight(GetParam(), weight, top_host->visits())); - } - factory_.SetFakeResponse(GURL(kManifestURLPrefix + top_host_url), - manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - } - // Sort by descending weight. - std::stable_sort(resources.begin(), resources.end(), - [](const std::pair<std::string, float>& a, - const std::pair<std::string, float>& b) { - return a.second > b.second; - }); - for (const auto& resource : resources) - expected_requested_urls.emplace_back(resource.first); - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - base::RunLoop().RunUntilIdle(); - } - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - EXPECT_TRUE(precache_delegate_.was_on_done_called()); -} - -INSTANTIATE_TEST_CASE_P( - PrecacheFetcherGlobalRankingTest, - PrecacheFetcherGlobalRankingTest, - testing::Values(PrecacheConfigurationSettings::FUNCTION_NAIVE, - PrecacheConfigurationSettings::FUNCTION_GEOMETRIC)); - -TEST_F(PrecacheFetcherTest, GloballyRankResourcesAfterPauseResume) { - SetDefaultFlags(); - - const size_t kNumTopHosts = 5; - const size_t kNumResources = 5; - - std::vector<GURL> expected_requested_urls; - - PrecacheConfigurationSettings config; - config.set_top_sites_count(kNumTopHosts); - config.set_global_ranking(true); - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - - // Visit counts and weights are chosen in such a way that resource requests - // between different hosts will be interleaved. - std::vector<std::pair<std::string, float>> resources; - for (size_t i = 0; i < kNumTopHosts; ++i) { - const std::string top_host_url = base::StringPrintf("top-host-%zu.com", i); - TopHost* top_host = unfinished_work->add_top_host(); - top_host->set_hostname(top_host_url); - top_host->set_visits(kNumTopHosts - i); - - PrecacheManifest manifest; - for (size_t j = 0; j < kNumResources; ++j) { - const float weight = 1 - static_cast<float>(j) / kNumResources; - const std::string resource_url = - base::StringPrintf("http://top-host-%zu.com/resource-%zu-weight-%.1f", - i, j, top_host->visits() * weight); - PrecacheResource* resource = manifest.add_resource(); - resource->set_url(resource_url); - resource->set_weight_ratio(weight); - factory_.SetFakeResponse(GURL(resource_url), "good", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - resources.emplace_back(resource_url, - top_host->visits() * resource->weight_ratio()); - } - factory_.SetFakeResponse(GURL(kManifestURLPrefix + top_host_url), - manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - } - // Sort by descending weight. - std::stable_sort(resources.begin(), resources.end(), - [](const std::pair<std::string, float>& a, - const std::pair<std::string, float>& b) { - return a.second > b.second; - }); - for (const auto& resource : resources) - expected_requested_urls.emplace_back(resource.first); - - std::unique_ptr<PrecacheUnfinishedWork> cancelled_work; - { - uint32_t remaining_tries = 100; - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - // Run the loop until all tophost manifest fetches are complete, but some - // resource fetches are pending. - while (--remaining_tries != 0 && - (!precache_fetcher.top_hosts_to_fetch_.empty() || - !precache_fetcher.top_hosts_fetching_.empty() || - !precache_fetcher.unfinished_work_->has_config_settings() || - precache_fetcher.resources_to_fetch_.empty())) { - LOG(INFO) << "remaining_tries: " << remaining_tries; - base::RunLoop run_loop; - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - run_loop.QuitClosure()); - run_loop.Run(); - } - - // Cancel precaching. - cancelled_work = precache_fetcher.CancelPrecaching(); - EXPECT_TRUE(precache_fetcher.top_hosts_to_fetch_.empty()); - EXPECT_TRUE(precache_fetcher.resources_to_fetch_.empty()); - } - EXPECT_NE(cancelled_work, nullptr); - EXPECT_TRUE(cancelled_work->top_host().empty()); - EXPECT_EQ(kNumTopHosts * kNumResources, - static_cast<size_t>(cancelled_work->resource().size())); - EXPECT_FALSE(precache_delegate_.was_on_done_called()); - - url_callback_.clear_requested_urls(); - - // Continuing with the precache should fetch all resources, as the previous - // run was cancelled before any finished. They should be fetched in global - // ranking order. - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(cancelled_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - LOG(INFO) << "Resuming prefetch."; - precache_fetcher.Start(); - base::RunLoop().RunUntilIdle(); - } - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - histogram.ExpectBucketCount("Precache.Fetch.MinWeight", - 1000.0 * resources.back().second, 1); -} - -TEST_F(PrecacheFetcherTest, MaxTotalResources) { - SetDefaultFlags(); - - const size_t kNumResources = 5; - - std::vector<GURL> expected_requested_urls; - - PrecacheConfigurationSettings config; - config.set_total_resources_count(2); - config.set_global_ranking(true); - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - expected_requested_urls.emplace_back(kConfigURL); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - - TopHost* top_host = unfinished_work->add_top_host(); - top_host->set_hostname("top-host.com"); - top_host->set_visits(1); - - expected_requested_urls.emplace_back(kManifestURLPrefix + - top_host->hostname()); - PrecacheManifest manifest; - for (size_t i = 0; i < kNumResources; ++i) { - const float weight = 1 - static_cast<float>(i) / kNumResources; - const std::string resource_url = - base::StringPrintf("http://top-host.com/resource-%zu-weight-%.1f", i, - top_host->visits() * weight); - PrecacheResource* resource = manifest.add_resource(); - resource->set_url(resource_url); - resource->set_weight_ratio(weight); - factory_.SetFakeResponse(GURL(resource_url), "good", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - if (i < config.total_resources_count()) - expected_requested_urls.emplace_back(resource_url); - } - factory_.SetFakeResponse(GURL(kManifestURLPrefix + top_host->hostname()), - manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - base::RunLoop().RunUntilIdle(); - } - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - const float expected_min_weight = - manifest.resource(config.total_resources_count() - 1).weight_ratio(); - histogram.ExpectUniqueSample("Precache.Fetch.MinWeight", - 1000.0 * expected_min_weight, 1); -} - -TEST_F(PrecacheFetcherTest, MinWeight) { - SetDefaultFlags(); - - const size_t kNumResources = 5; - - std::vector<GURL> expected_requested_urls; - - PrecacheConfigurationSettings config; - config.set_min_weight(3); - config.set_global_ranking(true); - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - expected_requested_urls.emplace_back(kConfigURL); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - - TopHost* top_host = unfinished_work->add_top_host(); - top_host->set_hostname("top-host.com"); - top_host->set_visits(5); - - expected_requested_urls.emplace_back(kManifestURLPrefix + - top_host->hostname()); - - PrecacheManifest manifest; - for (size_t i = 0; i < kNumResources; ++i) { - const float weight = 1 - static_cast<float>(i) / kNumResources; - const std::string resource_url = - base::StringPrintf("http://top-host.com/resource-%zu-weight-%.1f", i, - top_host->visits() * weight); - PrecacheResource* resource = manifest.add_resource(); - resource->set_url(resource_url); - resource->set_weight_ratio(weight); - factory_.SetFakeResponse(GURL(resource_url), "good", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - // If top_host->visits() * weight > config.min_weight(): - if (i < 3) - expected_requested_urls.emplace_back(resource_url); - } - factory_.SetFakeResponse(GURL(kManifestURLPrefix + top_host->hostname()), - manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - base::RunLoop().RunUntilIdle(); - } - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - EXPECT_TRUE(precache_delegate_.was_on_done_called()); -} - -// Tests cancel precaching when all tophost manifests are fetched, but some -// resource fetches are pending. -TEST_F(PrecacheFetcherTest, CancelPrecachingAfterAllManifestFetch) { - SetDefaultFlags(); - - const size_t kNumTopHosts = 5; - const size_t kNumResources = 5; - - PrecacheConfigurationSettings config; - std::vector<GURL> expected_requested_urls; - std::unique_ptr<PrecacheUnfinishedWork> cancelled_work; - - config.set_top_sites_count(kNumTopHosts); - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - expected_requested_urls.emplace_back(kConfigURL); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - - for (size_t i = 0; i < kNumTopHosts; ++i) { - const std::string top_host_url = base::StringPrintf("top-host-%zu.com", i); - expected_requested_urls.emplace_back(kManifestURLPrefix + top_host_url); - } - - int num_resources = 0; - for (size_t i = 0; i < kNumTopHosts; ++i) { - const std::string top_host_url = base::StringPrintf("top-host-%zu.com", i); - TopHost* top_host = unfinished_work->add_top_host(); - top_host->set_hostname(top_host_url); - top_host->set_visits(kNumTopHosts - i); - - PrecacheManifest manifest; - for (size_t j = 0; j < kNumResources; ++j) { - const std::string resource_url = - base::StringPrintf("http://top-host-%zu.com/resource-%zu", i, j); - PrecacheResource* resource = manifest.add_resource(); - resource->set_url(resource_url); - resource->set_weight_ratio(1); - factory_.SetFakeResponse(GURL(resource_url), "good", net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - if (++num_resources <= kMaxParallelFetches) - expected_requested_urls.emplace_back(resource_url); - } - factory_.SetFakeResponse(GURL(kManifestURLPrefix + top_host_url), - manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - } - - { - uint32_t remaining_tries = 100; - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - // Run the loop until all tophost manifest fetches are complete, but some - // resource fetches are pending. - while (--remaining_tries != 0 && - (!precache_fetcher.top_hosts_to_fetch_.empty() || - !precache_fetcher.top_hosts_fetching_.empty() || - !precache_fetcher.unfinished_work_->has_config_settings() || - precache_fetcher.resources_to_fetch_.empty())) { - LOG(INFO) << "remaining_tries: " << remaining_tries; - base::RunLoop run_loop; - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - run_loop.QuitClosure()); - run_loop.Run(); - } - - // Cancel precaching. - cancelled_work = precache_fetcher.CancelPrecaching(); - EXPECT_TRUE(precache_fetcher.top_hosts_to_fetch_.empty()); - EXPECT_TRUE(precache_fetcher.resources_to_fetch_.empty()); - } - ASSERT_NE(nullptr, cancelled_work); - EXPECT_TRUE(cancelled_work->top_host().empty()); - EXPECT_EQ(kNumTopHosts * kNumResources, - static_cast<size_t>(cancelled_work->resource().size())); - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - EXPECT_FALSE(precache_delegate_.was_on_done_called()); - - // Continuing with the precache should fetch all resources, as the previous - // run was cancelled before any finished. - expected_requested_urls.clear(); - url_callback_.clear_requested_urls(); - for (size_t i = 0; i < kNumTopHosts; ++i) { - for (size_t j = 0; j < kNumResources; ++j) { - expected_requested_urls.emplace_back( - base::StringPrintf("http://top-host-%zu.com/resource-%zu", i, j)); - } - } - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(cancelled_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - LOG(INFO) << "Resuming prefetch."; - precache_fetcher.Start(); - base::RunLoop().RunUntilIdle(); - } - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - EXPECT_TRUE(precache_delegate_.was_on_done_called()); -} - -TEST_F(PrecacheFetcherTest, DailyQuota) { - SetDefaultFlags(); - - const size_t kNumTopHosts = 3; - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->set_start_time(base::Time::UnixEpoch().ToInternalValue()); - - PrecacheConfigurationSettings config; - config.set_top_sites_count(kNumTopHosts); - config.set_daily_quota_total(10000); - factory_.SetFakeResponse(GURL(kConfigURL), config.SerializeAsString(), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - std::vector<GURL> expected_requested_urls; - expected_requested_urls.emplace_back(kConfigURL); - - for (size_t i = 0; i < kNumTopHosts; ++i) { - const std::string top_host_url = base::StringPrintf("top-host-%zu.com", i); - expected_requested_urls.emplace_back(std::string(kManifestURLPrefix) + - top_host_url); - } - - for (size_t i = 0; i < kNumTopHosts; ++i) { - const std::string top_host_url = base::StringPrintf("top-host-%zu.com", i); - const std::string resource_url = - base::StringPrintf("http://top-host-%zu.com/resource.html", i); - PrecacheManifest manifest; - manifest.add_resource()->set_url(resource_url); - - unfinished_work->add_top_host()->set_hostname(top_host_url); - factory_.SetFakeResponse( - GURL(std::string(kManifestURLPrefix) + top_host_url), - manifest.SerializeAsString(), net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - // Set a 5000 byte resource. - factory_.SetFakeResponse(GURL(resource_url), std::string(5000, 'a'), - net::HTTP_OK, net::URLRequestStatus::SUCCESS); - - expected_requested_urls.emplace_back(resource_url); - } - - base::HistogramTester histogram; - - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(0U, precache_fetcher.quota_.remaining()); - unfinished_work = precache_fetcher.CancelPrecaching(); - } - - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - EXPECT_EQ(0, unfinished_work->top_host_size()); - EXPECT_EQ(1, unfinished_work->resource_size()); - - histogram.ExpectTotalCount("Precache.Fetch.PercentCompleted", 1); - histogram.ExpectTotalCount("Precache.Fetch.ResponseBytes.Total", 1); - histogram.ExpectTotalCount("Precache.Fetch.TimeToComplete", 1); - - // Continuing with the precache when quota limit is reached, will not fetch - // any resources. - expected_requested_urls.clear(); - url_callback_.clear_requested_urls(); - { - PrecacheFetcher precache_fetcher( - request_context_.get(), GURL(), std::string(), - std::move(unfinished_work), kExperimentID, - precache_database_.GetWeakPtr(), task_runner(), &precache_delegate_); - precache_fetcher.Start(); - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(0U, precache_fetcher.quota_.remaining()); - } - EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls()); - EXPECT_TRUE(precache_delegate_.was_on_done_called()); - - histogram.ExpectTotalCount("Precache.Fetch.PercentCompleted", 2); - histogram.ExpectTotalCount("Precache.Fetch.ResponseBytes.Total", 2); - histogram.ExpectTotalCount("Precache.Fetch.TimeToComplete", 2); -} - -} // namespace precache
diff --git a/components/precache/core/precache_manifest_util.cc b/components/precache/core/precache_manifest_util.cc deleted file mode 100644 index ab801f6..0000000 --- a/components/precache/core/precache_manifest_util.cc +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright 2017 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 "components/precache/core/precache_manifest_util.h" - -#include <string> - -#include "components/precache/core/proto/precache.pb.h" - -namespace precache { - -void RemoveUnknownFields(PrecacheManifest* manifest) { - manifest->mutable_unknown_fields()->clear(); - for (auto& resource : *manifest->mutable_resource()) - resource.mutable_unknown_fields()->clear(); - if (manifest->has_experiments()) { - manifest->mutable_experiments()->mutable_unknown_fields()->clear(); - for (auto& kv : *manifest->mutable_experiments() - ->mutable_resources_by_experiment_group()) { - kv.second.mutable_unknown_fields()->clear(); - } - } - if (manifest->has_id()) - manifest->mutable_id()->mutable_unknown_fields()->clear(); -} - -base::Optional<std::vector<bool>> GetResourceBitset( - const PrecacheManifest& manifest, - uint32_t experiment_id) { - base::Optional<std::vector<bool>> ret; - if (manifest.has_experiments()) { - const auto& resource_bitset_map = - manifest.experiments().resources_by_experiment_group(); - const auto& it = resource_bitset_map.find(experiment_id); - if (it != resource_bitset_map.end()) { - if (it->second.has_bitset()) { - const std::string& bitset = it->second.bitset(); - const int bitset_size = bitset.size() * 8; - DCHECK_GE(bitset_size, manifest.resource_size()); - if (bitset_size >= manifest.resource_size()) { - ret.emplace(bitset_size); - for (size_t i = 0; i < bitset.size(); ++i) { - for (size_t j = 0; j < 8; ++j) { - if ((1 << j) & bitset[i]) - ret.value()[i * 8 + j] = true; - } - } - } - } else if (it->second.has_deprecated_bitset()) { - uint64_t bitset = it->second.deprecated_bitset(); - DCHECK_GE(64, manifest.resource_size()); - if (64 >= manifest.resource_size()) { - ret.emplace(64); - for (int i = 0; i < 64; ++i) { - if ((0x1ULL << i) & bitset) - ret.value()[i] = true; - } - } - } - } - } - // Only return one variable to ensure RVO triggers. - return ret; -} - -} // namespace precache
diff --git a/components/precache/core/precache_manifest_util.h b/components/precache/core/precache_manifest_util.h deleted file mode 100644 index b3e2ec2..0000000 --- a/components/precache/core/precache_manifest_util.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2017 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 COMPONENTS_PRECACHE_CORE_PRECACHE_MANIFEST_UTIL_H_ -#define COMPONENTS_PRECACHE_CORE_PRECACHE_MANIFEST_UTIL_H_ - -#include <stdint.h> - -#include <vector> - -#include "base/optional.h" - -namespace precache { - -class PrecacheManifest; - -// Removes unknown fields from the |manifest| including embedded messages. -void RemoveUnknownFields(PrecacheManifest* manifest); - -// Returns the resource selection bitset from the |manifest| for the given -// |experiment_id|. If the experiment group is not found, then this returns -// nullopt, in which case all resources should be selected. -base::Optional<std::vector<bool>> GetResourceBitset( - const PrecacheManifest& manifest, - uint32_t experiment_id); - -} // namespace precache - -#endif // COMPONENTS_PRECACHE_CORE_PRECACHE_MANIFEST_UTIL_H_
diff --git a/components/precache/core/precache_referrer_host_table.cc b/components/precache/core/precache_referrer_host_table.cc deleted file mode 100644 index e6acbba..0000000 --- a/components/precache/core/precache_referrer_host_table.cc +++ /dev/null
@@ -1,123 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/precache/core/precache_referrer_host_table.h" - -#include "sql/connection.h" -#include "sql/statement.h" - -using sql::Statement; - -namespace precache { - -const int64_t PrecacheReferrerHostEntry::kInvalidId = -1; - -bool PrecacheReferrerHostEntry::operator==( - const PrecacheReferrerHostEntry& entry) const { - return id == entry.id && referrer_host == entry.referrer_host && - manifest_id == entry.manifest_id && time == entry.time; -} - -PrecacheReferrerHostTable::PrecacheReferrerHostTable() : db_(NULL) {} - -PrecacheReferrerHostTable::~PrecacheReferrerHostTable() {} - -bool PrecacheReferrerHostTable::Init(sql::Connection* db) { - DCHECK(!db_); // Init must only be called once. - DCHECK(db); // The database connection must be non-NULL. - db_ = db; - return CreateTableIfNonExistent(); -} - -PrecacheReferrerHostEntry PrecacheReferrerHostTable::GetReferrerHost( - const std::string& referrer_host) { - Statement statement(db_->GetCachedStatement( - SQL_FROM_HERE, - "SELECT id, referrer_host, manifest_id, time " - "FROM precache_referrer_hosts WHERE referrer_host=?")); - - statement.BindString(0, referrer_host); - if (statement.Step()) { - return PrecacheReferrerHostEntry( - statement.ColumnInt64(0), statement.ColumnString(1), - statement.ColumnInt64(2), - base::Time::FromInternalValue(statement.ColumnInt64(3))); - } - return PrecacheReferrerHostEntry(PrecacheReferrerHostEntry::kInvalidId, - std::string(), 0, base::Time()); -} - -int64_t PrecacheReferrerHostTable::UpdateReferrerHost( - const std::string& referrer_host, - int64_t manifest_id, - const base::Time& time) { - int64_t referrer_host_id = GetReferrerHost(referrer_host).id; - if (referrer_host_id == PrecacheReferrerHostEntry::kInvalidId) { - Statement statement( - db_->GetCachedStatement(SQL_FROM_HERE, - "INSERT INTO precache_referrer_hosts " - "(id, referrer_host, manifest_id, time) " - "VALUES(NULL, ?, ?, ?)")); - - statement.BindString(0, referrer_host); - statement.BindInt64(1, manifest_id); - statement.BindInt64(2, time.ToInternalValue()); - if (statement.Run()) - return db_->GetLastInsertRowId(); - } else { - Statement statement( - db_->GetCachedStatement(SQL_FROM_HERE, - "UPDATE precache_referrer_hosts " - "SET manifest_id=?, time=? " - "WHERE id=?")); - - statement.BindInt64(0, manifest_id); - statement.BindInt64(1, time.ToInternalValue()); - ; - statement.BindInt64(2, referrer_host_id); - if (statement.Run()) - return referrer_host_id; - } - return -1; -} - -void PrecacheReferrerHostTable::DeleteAllEntriesBefore( - const base::Time& delete_end) { - Statement statement(db_->GetCachedStatement( - SQL_FROM_HERE, "DELETE FROM precache_referrer_hosts WHERE time < ?")); - statement.BindInt64(0, delete_end.ToInternalValue()); - statement.Run(); -} - -void PrecacheReferrerHostTable::DeleteAll() { - Statement statement(db_->GetCachedStatement( - SQL_FROM_HERE, "DELETE FROM precache_referrer_hosts")); - - statement.Run(); -} - -bool PrecacheReferrerHostTable::CreateTableIfNonExistent() { - return db_->Execute( - "CREATE TABLE IF NOT EXISTS precache_referrer_hosts " - "(id INTEGER PRIMARY KEY, referrer_host TEXT KEY, manifest_id INTEGER, " - "time INTEGER)"); -} - -std::map<std::string, PrecacheReferrerHostEntry> -PrecacheReferrerHostTable::GetAllDataForTesting() { - std::map<std::string, PrecacheReferrerHostEntry> all_data; - Statement statement( - db_->GetCachedStatement(SQL_FROM_HERE, - "SELECT id, referrer_host, manifest_id, time " - "FROM precache_referrer_hosts")); - while (statement.Step()) { - all_data[statement.ColumnString(1)] = PrecacheReferrerHostEntry( - statement.ColumnInt64(0), statement.ColumnString(1), - statement.ColumnInt64(2), - base::Time::FromInternalValue(statement.ColumnInt64(3))); - } - return all_data; -} - -} // namespace precache
diff --git a/components/precache/core/precache_referrer_host_table.h b/components/precache/core/precache_referrer_host_table.h deleted file mode 100644 index e956245..0000000 --- a/components/precache/core/precache_referrer_host_table.h +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PRECACHE_CORE_PRECACHE_REFERRER_HOST_TABLE_H_ -#define COMPONENTS_PRECACHE_CORE_PRECACHE_REFERRER_HOST_TABLE_H_ - -#include <stdint.h> - -#include <map> -#include <string> - -#include "base/macros.h" -#include "base/time/time.h" - -namespace sql { -class Connection; -} - -namespace precache { - -struct PrecacheReferrerHostEntry { - static const int64_t kInvalidId; - - PrecacheReferrerHostEntry() : id(kInvalidId) {} - PrecacheReferrerHostEntry(int64_t id, - const std::string& referrer_host, - int64_t manifest_id, - const base::Time& time) - : id(id), - referrer_host(referrer_host), - manifest_id(manifest_id), - time(time) {} - - // Comparison for testing. - bool operator==(const PrecacheReferrerHostEntry& entry) const; - - int64_t id; - std::string referrer_host; - int64_t manifest_id; - base::Time time; -}; - -class PrecacheReferrerHostTable { - public: - PrecacheReferrerHostTable(); - ~PrecacheReferrerHostTable(); - - // Initialize the precache referrer host table for use with the specified - // database connection. The caller keeps ownership of |db|, and |db| must not - // be NULL. Init must be called before any other methods. - bool Init(sql::Connection* db); - - // Returns the referrer host information about |referrer_host|. - PrecacheReferrerHostEntry GetReferrerHost(const std::string& referrer_host); - - // Updates the referrer host information about |referrer_host|. - int64_t UpdateReferrerHost(const std::string& referrer_host, - int64_t manifest_id, - const base::Time& time); - - // Deletes entries that were created before the time of |delete_end|. - void DeleteAllEntriesBefore(const base::Time& delete_end); - - // Delete all entries. - void DeleteAll(); - - // Used by tests to get the contents of the table. - std::map<std::string, PrecacheReferrerHostEntry> GetAllDataForTesting(); - - private: - bool CreateTableIfNonExistent(); - - // Not owned by |this|. - sql::Connection* db_; - - DISALLOW_COPY_AND_ASSIGN(PrecacheReferrerHostTable); -}; - -} // namespace precache - -#endif // COMPONENTS_PRECACHE_CORE_PRECACHE_REFERRER_HOST_TABLE_H_
diff --git a/components/precache/core/precache_referrer_host_table_unittest.cc b/components/precache/core/precache_referrer_host_table_unittest.cc deleted file mode 100644 index 624f1e26..0000000 --- a/components/precache/core/precache_referrer_host_table_unittest.cc +++ /dev/null
@@ -1,154 +0,0 @@ -// 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 "components/precache/core/precache_referrer_host_table.h" - -#include <map> -#include <memory> - -#include "base/compiler_specific.h" -#include "base/time/time.h" -#include "sql/connection.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace precache { - -namespace { - -const char* kReffererHostFoo = "foo.com"; -const char* kReffererHostBar = "bar.com"; -const int64_t kManifestIdFoo = 1001; -const int64_t kManifestIdBar = 1002; - -class PrecacheReferrerHostTableTest : public testing::Test { - public: - PrecacheReferrerHostTableTest() {} - ~PrecacheReferrerHostTableTest() override {} - - protected: - void SetUp() override { - precache_referrer_host_table_.reset(new PrecacheReferrerHostTable()); - db_.reset(new sql::Connection()); - ASSERT_TRUE(db_->OpenInMemory()); - precache_referrer_host_table_->Init(db_.get()); - } - - std::unique_ptr<PrecacheReferrerHostTable> precache_referrer_host_table_; - std::unique_ptr<sql::Connection> db_; -}; - -TEST_F(PrecacheReferrerHostTableTest, GetReferrerHost) { - const base::Time kTimeFoo = base::Time::FromInternalValue(100); - const base::Time kTimeBar = base::Time::FromInternalValue(200); - std::map<std::string, PrecacheReferrerHostEntry> expected_entries; - - // Add new referrer hosts. - int64_t foo_id = precache_referrer_host_table_->UpdateReferrerHost( - kReffererHostFoo, kManifestIdFoo, kTimeFoo); - int64_t bar_id = precache_referrer_host_table_->UpdateReferrerHost( - kReffererHostBar, kManifestIdBar, kTimeBar); - - EXPECT_NE(-1, foo_id); - EXPECT_NE(-1, bar_id); - - EXPECT_EQ(PrecacheReferrerHostEntry(foo_id, kReffererHostFoo, kManifestIdFoo, - kTimeFoo), - precache_referrer_host_table_->GetReferrerHost(kReffererHostFoo)); - EXPECT_EQ(PrecacheReferrerHostEntry(bar_id, kReffererHostBar, kManifestIdBar, - kTimeBar), - precache_referrer_host_table_->GetReferrerHost(kReffererHostBar)); - - expected_entries[kReffererHostFoo] = PrecacheReferrerHostEntry( - foo_id, kReffererHostFoo, kManifestIdFoo, kTimeFoo); - expected_entries[kReffererHostBar] = PrecacheReferrerHostEntry( - bar_id, kReffererHostBar, kManifestIdBar, kTimeBar); - EXPECT_THAT(expected_entries, - ::testing::ContainerEq( - precache_referrer_host_table_->GetAllDataForTesting())); -} - -TEST_F(PrecacheReferrerHostTableTest, UpdateReferrerHost) { - const base::Time kTimeFoo = base::Time::FromInternalValue(100); - const base::Time kTimeBar = base::Time::FromInternalValue(200); - std::map<std::string, PrecacheReferrerHostEntry> expected_entries; - - // Add new referrer hosts. - int64_t foo_id = precache_referrer_host_table_->UpdateReferrerHost( - kReffererHostFoo, kManifestIdFoo, kTimeFoo); - int64_t bar_id = precache_referrer_host_table_->UpdateReferrerHost( - kReffererHostBar, kManifestIdBar, kTimeBar); - - EXPECT_NE(-1, foo_id); - EXPECT_NE(-1, bar_id); - - expected_entries[kReffererHostFoo] = PrecacheReferrerHostEntry( - foo_id, kReffererHostFoo, kManifestIdFoo, kTimeFoo); - expected_entries[kReffererHostBar] = PrecacheReferrerHostEntry( - bar_id, kReffererHostBar, kManifestIdBar, kTimeBar); - EXPECT_THAT(expected_entries, - ::testing::ContainerEq( - precache_referrer_host_table_->GetAllDataForTesting())); - - // Updating referrer hosts should return the same ID. - EXPECT_EQ(foo_id, precache_referrer_host_table_->UpdateReferrerHost( - kReffererHostFoo, kManifestIdFoo, kTimeFoo)); - EXPECT_EQ(bar_id, precache_referrer_host_table_->UpdateReferrerHost( - kReffererHostBar, kManifestIdBar, kTimeBar)); - EXPECT_THAT(expected_entries, - ::testing::ContainerEq( - precache_referrer_host_table_->GetAllDataForTesting())); -} - -TEST_F(PrecacheReferrerHostTableTest, DeleteAll) { - const base::Time kTimeFoo = base::Time::FromInternalValue(100); - const base::Time kTimeBar = base::Time::FromInternalValue(200); - std::map<std::string, PrecacheReferrerHostEntry> expected_entries; - - // Add new referrer hosts. - int64_t foo_id = precache_referrer_host_table_->UpdateReferrerHost( - kReffererHostFoo, kManifestIdFoo, kTimeFoo); - int64_t bar_id = precache_referrer_host_table_->UpdateReferrerHost( - kReffererHostBar, kManifestIdBar, kTimeBar); - - EXPECT_NE(-1, foo_id); - EXPECT_NE(-1, bar_id); - - expected_entries[kReffererHostFoo] = PrecacheReferrerHostEntry( - foo_id, kReffererHostFoo, kManifestIdFoo, kTimeFoo); - expected_entries[kReffererHostBar] = PrecacheReferrerHostEntry( - bar_id, kReffererHostBar, kManifestIdBar, kTimeBar); - EXPECT_THAT(expected_entries, - ::testing::ContainerEq( - precache_referrer_host_table_->GetAllDataForTesting())); - - precache_referrer_host_table_->DeleteAll(); - - EXPECT_EQ(0UL, precache_referrer_host_table_->GetAllDataForTesting().size()); -} - -TEST_F(PrecacheReferrerHostTableTest, DeleteAllEntriesBefore) { - const base::Time kOldTime = base::Time::FromInternalValue(10); - const base::Time kBeforeTime = base::Time::FromInternalValue(20); - const base::Time kEndTime = base::Time::FromInternalValue(30); - const base::Time kAfterTime = base::Time::FromInternalValue(40); - - precache_referrer_host_table_->UpdateReferrerHost("old.com", 1, kOldTime); - precache_referrer_host_table_->UpdateReferrerHost("before.com", 2, - kBeforeTime); - precache_referrer_host_table_->UpdateReferrerHost("end.com", 3, kEndTime); - precache_referrer_host_table_->UpdateReferrerHost("after.com", 4, kAfterTime); - - precache_referrer_host_table_->DeleteAllEntriesBefore(kEndTime); - - const auto actual_entries = - precache_referrer_host_table_->GetAllDataForTesting(); - EXPECT_EQ(2UL, actual_entries.size()); - EXPECT_NE(actual_entries.end(), actual_entries.find("end.com")); - EXPECT_NE(actual_entries.end(), actual_entries.find("after.com")); -} - -} // namespace - -} // namespace precache
diff --git a/components/precache/core/precache_session_table.cc b/components/precache/core/precache_session_table.cc deleted file mode 100644 index f7ac55c7..0000000 --- a/components/precache/core/precache_session_table.cc +++ /dev/null
@@ -1,121 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/precache/core/precache_session_table.h" - -#include <stdint.h> -#include <string> - -#include "base/logging.h" -#include "base/time/time.h" -#include "components/precache/core/proto/timestamp.pb.h" -#include "components/precache/core/proto/unfinished_work.pb.h" -#include "sql/connection.h" -#include "sql/statement.h" - -using sql::Statement; - -namespace precache { - -PrecacheSessionTable::PrecacheSessionTable() : db_(nullptr) {} - -PrecacheSessionTable::~PrecacheSessionTable() {} - -bool PrecacheSessionTable::Init(sql::Connection* db) { - DCHECK(!db_); // Init must only be called once. - DCHECK(db); // The database connection must be non-NULL. - db_ = db; - return CreateTableIfNonExistent(); -} - -void PrecacheSessionTable::SetSessionDataType(SessionDataType id, - const std::string& data) { - Statement statement(db_->GetCachedStatement( - SQL_FROM_HERE, - "INSERT OR REPLACE INTO precache_session (type, value) VALUES(?,?)")); - statement.BindInt(0, static_cast<int>(id)); - statement.BindString(1, data); - statement.Run(); -} - -std::string PrecacheSessionTable::GetSessionDataType(SessionDataType id) { - Statement statement(db_->GetCachedStatement( - SQL_FROM_HERE, "SELECT value from precache_session where type=?")); - statement.BindInt(0, static_cast<int>(id)); - return statement.Step() ? statement.ColumnString(0) : std::string(); -} - -void PrecacheSessionTable::SetLastPrecacheTimestamp(const base::Time& time) { - DCHECK(!time.is_null()); - Timestamp timestamp; - timestamp.set_seconds((time - base::Time::UnixEpoch()).InSeconds()); - SetSessionDataType(SessionDataType::LAST_PRECACHE_TIMESTAMP, - timestamp.SerializeAsString()); -} - -base::Time PrecacheSessionTable::GetLastPrecacheTimestamp() { - Timestamp timestamp; - const std::string data = - GetSessionDataType(SessionDataType::LAST_PRECACHE_TIMESTAMP); - if (!data.empty()) - timestamp.ParseFromString(data); - return timestamp.has_seconds() - ? base::Time::UnixEpoch() + - base::TimeDelta::FromSeconds(timestamp.seconds()) - : base::Time(); -} - -void PrecacheSessionTable::DeleteLastPrecacheTimestamp() { - Statement statement(db_->GetCachedStatement( - SQL_FROM_HERE, "DELETE FROM precache_session where type=?")); - statement.BindInt(0, - static_cast<int>(SessionDataType::LAST_PRECACHE_TIMESTAMP)); - statement.Run(); -} - -// Store unfinished work. -void PrecacheSessionTable::SaveUnfinishedWork( - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work) { - SetSessionDataType(SessionDataType::UNFINISHED_WORK, - unfinished_work->SerializeAsString()); -} - -// Retrieve unfinished work. -std::unique_ptr<PrecacheUnfinishedWork> -PrecacheSessionTable::GetUnfinishedWork() { - const std::string data = GetSessionDataType(SessionDataType::UNFINISHED_WORK); - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - if (!data.empty()) - unfinished_work->ParseFromString(data); - return unfinished_work; -} - -void PrecacheSessionTable::DeleteUnfinishedWork() { - Statement statement( - db_->GetCachedStatement( - SQL_FROM_HERE, "DELETE FROM precache_session where type=?")); - statement.BindInt(0, static_cast<int>(SessionDataType::UNFINISHED_WORK)); - statement.Run(); -} - -void PrecacheSessionTable::SaveQuota(const PrecacheQuota& quota) { - SetSessionDataType(SessionDataType::QUOTA, quota.SerializeAsString()); -} - -PrecacheQuota PrecacheSessionTable::GetQuota() { - PrecacheQuota quota; - const std::string data = GetSessionDataType(SessionDataType::QUOTA); - if (!data.empty()) - quota.ParseFromString(data); - return quota; -} - -bool PrecacheSessionTable::CreateTableIfNonExistent() { - return db_->Execute( - "CREATE TABLE IF NOT EXISTS precache_session (type INTEGER PRIMARY KEY, " - "value STRING)"); -} - -} // namespace precache
diff --git a/components/precache/core/precache_session_table.h b/components/precache/core/precache_session_table.h deleted file mode 100644 index 4ddeda9..0000000 --- a/components/precache/core/precache_session_table.h +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PRECACHE_CORE_PRECACHE_SESSION_TABLE_H_ -#define COMPONENTS_PRECACHE_CORE_PRECACHE_SESSION_TABLE_H_ - -#include <memory> - -#include "base/macros.h" -#include "base/time/time.h" -#include "components/precache/core/proto/quota.pb.h" - -namespace sql { -class Connection; -} - -namespace precache { - -class PrecacheUnfinishedWork; - -// Denotes the type of session information being stored. -enum class SessionDataType { - // Unfinished work to do sometime later. - UNFINISHED_WORK = 0, - - // Timestamp of the last precache. - LAST_PRECACHE_TIMESTAMP = 1, - - // Remaining quota limits. - QUOTA = 2, -}; - -class PrecacheSessionTable { - public: - PrecacheSessionTable(); - virtual ~PrecacheSessionTable(); - - // Initializes the precache task URL table for use with the specified database - // connection. The caller keeps ownership of |db|, and |db| must not be null. - // Init must be called before any other methods. - bool Init(sql::Connection* db); - - // -- Time since last precache -- - - void SetLastPrecacheTimestamp(const base::Time& time); - - // If none present, it will return base::Time(), so it can be checked via - // is_null(). - base::Time GetLastPrecacheTimestamp(); - - void DeleteLastPrecacheTimestamp(); - - // Precache quota. - void SaveQuota(const PrecacheQuota& quota); - PrecacheQuota GetQuota(); - - // -- Unfinished work -- - - // Stores unfinished work. - void SaveUnfinishedWork( - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work); - - // Retrieves unfinished work. - std::unique_ptr<PrecacheUnfinishedWork> GetUnfinishedWork(); - - // Removes all unfinished work from the database. - void DeleteUnfinishedWork(); - - private: - bool CreateTableIfNonExistent(); - - void SetSessionDataType(SessionDataType id, const std::string& data); - std::string GetSessionDataType(SessionDataType id); - - // Non-owned pointer. - sql::Connection* db_; - - DISALLOW_COPY_AND_ASSIGN(PrecacheSessionTable); -}; - -} // namespace precache -#endif // COMPONENTS_PRECACHE_CORE_PRECACHE_SESSION_TABLE_H_
diff --git a/components/precache/core/precache_session_table_unittest.cc b/components/precache/core/precache_session_table_unittest.cc deleted file mode 100644 index dee5c09..0000000 --- a/components/precache/core/precache_session_table_unittest.cc +++ /dev/null
@@ -1,177 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include "base/compiler_specific.h" -#include "base/time/time.h" -#include "components/precache/core/precache_session_table.h" -#include "components/precache/core/proto/quota.pb.h" -#include "components/precache/core/proto/unfinished_work.pb.h" -#include "sql/connection.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace precache { - -namespace { - -class PrecacheSessionTableTest : public testing::Test { - public: - PrecacheSessionTableTest() {} - ~PrecacheSessionTableTest() override {} - - protected: - void SetUp() override { - precache_session_table_.reset(new PrecacheSessionTable()); - db_.reset(new sql::Connection()); - ASSERT_TRUE(db_->OpenInMemory()); - precache_session_table_->Init(db_.get()); - } - - std::unique_ptr<PrecacheSessionTable> precache_session_table_; - std::unique_ptr<sql::Connection> db_; -}; - -TEST_F(PrecacheSessionTableTest, LastPrecacheTimestamp) { - const base::Time sometime = base::Time::FromDoubleT(42); - - precache_session_table_->SetLastPrecacheTimestamp(sometime); - - EXPECT_EQ(sometime, precache_session_table_->GetLastPrecacheTimestamp()); - - precache_session_table_->DeleteLastPrecacheTimestamp(); - - EXPECT_EQ(base::Time(), precache_session_table_->GetLastPrecacheTimestamp()); -} - -TEST_F(PrecacheSessionTableTest, SaveAndGetUnfinishedWork) { - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("foo.com"); - unfinished_work->add_top_host()->set_hostname("bar.com"); - auto* s = unfinished_work->mutable_config_settings(); - s->set_top_sites_count(11); - s->add_forced_site("baz.com"); - s->set_top_resources_count(12); - s->set_max_bytes_per_resource(501); - s->set_max_bytes_total(1001); - unfinished_work->add_resource()->set_url("http://x.com/"); - unfinished_work->add_resource()->set_url("http://y.com/"); - unfinished_work->add_resource()->set_url("http://z.com/"); - unfinished_work->set_total_bytes(13); - unfinished_work->set_network_bytes(14); - unfinished_work->set_num_manifest_urls(15); - base::Time sometime = base::Time::UnixEpoch(); - unfinished_work->set_start_time(sometime.ToInternalValue()); - - precache_session_table_->SaveUnfinishedWork(std::move(unfinished_work)); - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work2 = - precache_session_table_->GetUnfinishedWork(); - - EXPECT_EQ(2, unfinished_work2->top_host_size()); - EXPECT_EQ("foo.com", unfinished_work2->top_host(0).hostname()); - EXPECT_EQ("bar.com", unfinished_work2->top_host(1).hostname()); - EXPECT_EQ(11, unfinished_work2->config_settings().top_sites_count()); - EXPECT_EQ(1, unfinished_work2->config_settings().forced_site_size()); - EXPECT_EQ("baz.com", unfinished_work2->config_settings().forced_site(0)); - EXPECT_EQ(12, unfinished_work2->config_settings().top_resources_count()); - EXPECT_EQ(501ul, - unfinished_work2->config_settings().max_bytes_per_resource()); - EXPECT_EQ(1001ul, unfinished_work2->config_settings().max_bytes_total()); - EXPECT_EQ(3, unfinished_work2->resource_size()); - EXPECT_EQ("http://x.com/", unfinished_work2->resource(0).url()); - EXPECT_EQ("http://y.com/", unfinished_work2->resource(1).url()); - EXPECT_EQ("http://z.com/", unfinished_work2->resource(2).url()); - EXPECT_EQ(13ul, unfinished_work2->total_bytes()); - EXPECT_EQ(14ul, unfinished_work2->network_bytes()); - EXPECT_EQ(15ul, unfinished_work2->num_manifest_urls()); - EXPECT_EQ(base::Time::UnixEpoch(), - base::Time::FromInternalValue(unfinished_work2->start_time())); -} - -// Test that storing overwrites previous unfinished work. -TEST_F(PrecacheSessionTableTest, SaveAgainAndGet) { - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("a.com"); - precache_session_table_->SaveUnfinishedWork(std::move(unfinished_work)); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work2( - new PrecacheUnfinishedWork()); - unfinished_work2->add_top_host()->set_hostname("b.com"); - precache_session_table_->SaveUnfinishedWork(std::move(unfinished_work2)); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work3 = - precache_session_table_->GetUnfinishedWork(); - EXPECT_EQ("b.com", unfinished_work3->top_host(0).hostname()); -} - -// Test that reading does not remove unfinished work from storage. -TEST_F(PrecacheSessionTableTest, SaveAndGetAgain) { - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("a.com"); - precache_session_table_->SaveUnfinishedWork(std::move(unfinished_work)); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work2 = - precache_session_table_->GetUnfinishedWork(); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work3 = - precache_session_table_->GetUnfinishedWork(); - - EXPECT_EQ("a.com", unfinished_work3->top_host(0).hostname()); -} - -// Test that storing a large proto works. -TEST_F(PrecacheSessionTableTest, SaveManyURLs) { - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - for (int i = 0; i < 1000; ++i) - unfinished_work->add_top_host()->set_hostname("a.com"); - precache_session_table_->SaveUnfinishedWork(std::move(unfinished_work)); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work2 = - precache_session_table_->GetUnfinishedWork(); - - EXPECT_EQ(1000, unfinished_work2->top_host_size()); - for (int i = 0; i < 1000; ++i) - EXPECT_EQ("a.com", unfinished_work2->top_host(i).hostname()); -} - -// Test that reading after deletion returns no unfinished work. -TEST_F(PrecacheSessionTableTest, SaveDeleteGet) { - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work( - new PrecacheUnfinishedWork()); - unfinished_work->add_top_host()->set_hostname("a.com"); - precache_session_table_->SaveUnfinishedWork(std::move(unfinished_work)); - precache_session_table_->DeleteUnfinishedWork(); - - std::unique_ptr<PrecacheUnfinishedWork> unfinished_work2 = - precache_session_table_->GetUnfinishedWork(); - - EXPECT_EQ(0, unfinished_work2->top_host_size()); -} - -TEST_F(PrecacheSessionTableTest, SaveAndGetQuota) { - // Initial quota, should have expired. - EXPECT_LT(base::Time::FromInternalValue( - precache_session_table_->GetQuota().start_time()), - base::Time::Now()); - - PrecacheQuota quota; - quota.set_start_time(base::Time::Now().ToInternalValue()); - quota.set_remaining(1000U); - - PrecacheQuota expected_quota = quota; - precache_session_table_->SaveQuota(quota); - EXPECT_EQ(expected_quota.start_time(), - precache_session_table_->GetQuota().start_time()); - EXPECT_EQ(expected_quota.remaining(), - precache_session_table_->GetQuota().remaining()); -} - -} // namespace - -} // namespace precache
diff --git a/components/precache/core/precache_switches.cc b/components/precache/core/precache_switches.cc deleted file mode 100644 index a0ea84a..0000000 --- a/components/precache/core/precache_switches.cc +++ /dev/null
@@ -1,21 +0,0 @@ -// 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 "components/precache/core/precache_switches.h" - -namespace precache { -namespace switches { - -// Enables the proactive populating of the disk cache with Web resources that -// are likely to be needed in future page fetches. -const char kEnablePrecache[] = "enable-precache"; - -// The URL that provides the PrecacheConfigurationSettings proto. -const char kPrecacheConfigSettingsURL[] = "precache-config-settings-url"; - -// Precache manifests will be served from URLs with this prefix. -const char kPrecacheManifestURLPrefix[] = "precache-manifest-url-prefix"; - -} // namespace switches -} // namespace precache
diff --git a/components/precache/core/precache_switches.h b/components/precache/core/precache_switches.h deleted file mode 100644 index 5ed0c43..0000000 --- a/components/precache/core/precache_switches.h +++ /dev/null
@@ -1,20 +0,0 @@ -// 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 COMPONENTS_PRECACHE_CORE_PRECACHE_SWITCHES_H_ -#define COMPONENTS_PRECACHE_CORE_PRECACHE_SWITCHES_H_ - -namespace precache { -namespace switches { - -// All switches in alphabetical order. The switches should be documented -// alongside the definition of their values in the .cc file. -extern const char kEnablePrecache[]; -extern const char kPrecacheConfigSettingsURL[]; -extern const char kPrecacheManifestURLPrefix[]; - -} // namespace switches -} // namespace precache - -#endif // COMPONENTS_PRECACHE_CORE_PRECACHE_SWITCHES_H_
diff --git a/components/precache/core/precache_url_table.cc b/components/precache/core/precache_url_table.cc deleted file mode 100644 index 43ae9eb..0000000 --- a/components/precache/core/precache_url_table.cc +++ /dev/null
@@ -1,205 +0,0 @@ -// 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 "components/precache/core/precache_url_table.h" - -#include <string> - -#include "base/logging.h" -#include "sql/connection.h" -#include "sql/statement.h" - -using sql::Statement; - -namespace { - -// Returns the spec of the given URL. -std::string GetKey(const GURL& url) { - return url.spec(); -} - -} // namespace - -namespace precache { - -bool PrecacheURLInfo::operator==(const PrecacheURLInfo& other) const { - return was_precached == other.was_precached && - is_precached == other.is_precached && was_used == other.was_used && - is_download_reported == other.is_download_reported; -} - -PrecacheURLTable::PrecacheURLTable() : db_(NULL) {} - -PrecacheURLTable::~PrecacheURLTable() {} - -bool PrecacheURLTable::Init(sql::Connection* db) { - DCHECK(!db_); // Init must only be called once. - DCHECK(db); // The database connection must be non-NULL. - db_ = db; - return CreateTableIfNonExistent(); -} - -void PrecacheURLTable::AddURL(const GURL& url, - int64_t referrer_host_id, - bool is_precached, - const base::Time& precache_time, - bool is_download_reported) { - Statement statement(db_->GetCachedStatement( - SQL_FROM_HERE, - "INSERT OR REPLACE INTO precache_urls " - "(url, referrer_host_id, was_used, is_precached, time, " - " is_download_reported)" - "VALUES(?, ?, 0, ?, ?, ?)")); - statement.BindString(0, GetKey(url)); - statement.BindInt64(1, referrer_host_id); - statement.BindInt64(2, is_precached ? 1 : 0); - statement.BindInt64(3, precache_time.ToInternalValue()); - statement.BindInt64(4, is_download_reported); - statement.Run(); -} - -PrecacheURLInfo PrecacheURLTable::GetURLInfo(const GURL& url) { - Statement statement(db_->GetCachedStatement( - SQL_FROM_HERE, - "SELECT is_precached, was_used, is_download_reported " - "FROM precache_urls WHERE url=?")); - statement.BindString(0, GetKey(url)); - - if (statement.Step()) { - return {/*present=*/true, /*is_precached=*/statement.ColumnBool(0), - /*was_used==*/statement.ColumnBool(1), - /*is_download_reported=*/statement.ColumnBool(2)}; - } else { - return {/*present=*/false, /*is_precached=*/false, /*was_used=*/false, - /*is_download_reported=*/false}; - } -} - -void PrecacheURLTable::SetPrecachedURLAsUsed(const GURL& url) { - Statement statement( - db_->GetCachedStatement(SQL_FROM_HERE, - "UPDATE precache_urls SET was_used=1, " - "is_precached=0 " - "WHERE url=? and was_used=0 and is_precached=1")); - - statement.BindString(0, GetKey(url)); - statement.Run(); -} - -void PrecacheURLTable::SetURLAsNotPrecached(const GURL& url) { - Statement statement( - db_->GetCachedStatement(SQL_FROM_HERE, - "UPDATE precache_urls SET is_precached=0 " - "WHERE url=? and is_precached=1")); - statement.BindString(0, GetKey(url)); - statement.Run(); -} - -void PrecacheURLTable::GetURLListForReferrerHost( - int64_t referrer_host_id, - std::vector<GURL>* used_urls, - std::vector<GURL>* downloaded_urls) { - Statement statement( - db_->GetCachedStatement(SQL_FROM_HERE, - "SELECT url, was_used, is_download_reported " - "from precache_urls where referrer_host_id=?")); - statement.BindInt64(0, referrer_host_id); - while (statement.Step()) { - GURL url(statement.ColumnString(0)); - if (statement.ColumnInt(1)) - used_urls->push_back(url); - if (!statement.ColumnInt(2)) - downloaded_urls->push_back(url); - } -} - -void PrecacheURLTable::SetDownloadReported(int64_t referrer_host_id) { - Statement statement( - db_->GetCachedStatement(SQL_FROM_HERE, - "UPDATE precache_urls SET is_download_reported=1 " - "WHERE referrer_host_id=?")); - statement.BindInt64(0, referrer_host_id); - statement.Run(); -} - -void PrecacheURLTable::ClearAllForReferrerHost(int64_t referrer_host_id) { - // Delete the URLs that are not precached. - Statement delete_statement( - db_->GetCachedStatement(SQL_FROM_HERE, - "DELETE FROM precache_urls WHERE " - "referrer_host_id=? AND is_precached=0")); - delete_statement.BindInt64(0, referrer_host_id); - delete_statement.Run(); - - // Clear was_used for precached URLs. - Statement update_statement(db_->GetCachedStatement( - SQL_FROM_HERE, - "UPDATE precache_urls SET was_used=0 WHERE referrer_host_id=?")); - update_statement.BindInt64(0, referrer_host_id); - update_statement.Run(); -} - -void PrecacheURLTable::DeleteAllPrecachedBefore(const base::Time& delete_end) { - Statement statement(db_->GetCachedStatement( - SQL_FROM_HERE, "DELETE FROM precache_urls WHERE time < ?")); - - statement.BindInt64(0, delete_end.ToInternalValue()); - statement.Run(); -} - -void PrecacheURLTable::DeleteAll() { - Statement statement( - db_->GetCachedStatement(SQL_FROM_HERE, "DELETE FROM precache_urls")); - - statement.Run(); -} - -void PrecacheURLTable::GetAllDataForTesting(std::map<GURL, base::Time>* map) { - map->clear(); - - Statement statement(db_->GetCachedStatement( - SQL_FROM_HERE, - "SELECT url, time FROM precache_urls where is_precached=1")); - - while (statement.Step()) { - GURL url = GURL(statement.ColumnString(0)); - (*map)[url] = base::Time::FromInternalValue(statement.ColumnInt64(1)); - } -} - -bool PrecacheURLTable::CreateTableIfNonExistent() { - // TODO(jamartin): The PRIMARY KEY should be (url, referrer_host_id). - if (!db_->DoesTableExist("precache_urls")) { - return db_->Execute( - "CREATE TABLE precache_urls " - "(url TEXT PRIMARY KEY, referrer_host_id INTEGER, was_used INTEGER, " - "is_precached INTEGER, " - "time INTEGER, is_download_reported INTEGER)"); - } else { - // Migrate the table by creating the missing columns. - if (!db_->DoesColumnExist("precache_urls", "was_used") && - !db_->Execute("ALTER TABLE precache_urls " - "ADD COLUMN was_used INTEGER")) { - return false; - } - if (!db_->DoesColumnExist("precache_urls", "is_precached") && - !db_->Execute("ALTER TABLE precache_urls ADD COLUMN is_precached " - "INTEGER default 1")) { - return false; - } - if (!db_->DoesColumnExist("precache_urls", "referrer_host_id") && - !db_->Execute( - "ALTER TABLE precache_urls ADD COLUMN referrer_host_id INTEGER")) { - return false; - } - if (!db_->DoesColumnExist("precache_urls", "is_download_reported") && - !db_->Execute("ALTER TABLE precache_urls " - "ADD COLUMN is_download_reported INTEGER")) { - return false; - } - } - return true; -} - -} // namespace precache
diff --git a/components/precache/core/precache_url_table.h b/components/precache/core/precache_url_table.h deleted file mode 100644 index 4f4effd3..0000000 --- a/components/precache/core/precache_url_table.h +++ /dev/null
@@ -1,111 +0,0 @@ -// 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 COMPONENTS_PRECACHE_CORE_PRECACHE_URL_TABLE_H_ -#define COMPONENTS_PRECACHE_CORE_PRECACHE_URL_TABLE_H_ - -#include <stdint.h> - -#include <map> -#include <vector> - -#include "base/macros.h" -#include "base/time/time.h" -#include "url/gurl.h" - -namespace sql { -class Connection; -} - -namespace precache { - -// Information about a given URL with respect to the PrecacheURLTable. -struct PrecacheURLInfo { - // The url has been prefetched in the past 60 days. (This number comes from - // kPrecacheHistoryExpiryPeriodDays in precache_database.cc.) - bool was_precached; - - // True if the cache entry is the one fetched by PrecacheFetcher. False if a - // new network fetch overwrote the cache entry since the prefetch. - bool is_precached; - - // The prefetched copy of the URL was used in browsing (i.e. while - // is_precached was true). - bool was_used; - - // It was already reported that this resources was downloaded. - bool is_download_reported; - - bool operator==(const PrecacheURLInfo& other) const; -}; - -// Interface for database table that keeps track of the URLs that have been -// precached but not used. This table is used to count how many bytes were saved -// by precached resources. -// Each row in this table represents a URL that was precached over the network, -// and has not been fetched through user browsing since then. -// Manages one table { URL (primary key), precache timestamp }. -class PrecacheURLTable { - public: - PrecacheURLTable(); - ~PrecacheURLTable(); - - // Initialize the precache URL table for use with the specified database - // connection. The caller keeps ownership of |db|, and |db| must not be NULL. - // Init must be called before any other methods. - bool Init(sql::Connection* db); - - // Adds an URL to the table, |referrer_host_id| is the id of the referrer host - // in PrecacheReferrerHostTable, |is_precached| indicates if the URL is - // precached, |time| is the timestamp, |is_download_reported| indicates if - // this the download of this URL was already reported. Replaces the row if one - // already exists. - void AddURL(const GURL& url, - int64_t referrer_host_id, - bool is_precached, - const base::Time& precache_time, - bool is_download_reported); - - // Returns information about the URL's status with respect to prefetching. - PrecacheURLInfo GetURLInfo(const GURL& url); - - // Sets the precached URL as used. - void SetPrecachedURLAsUsed(const GURL& url); - - // Set the previously precached URL as not precached, during user browsing. - void SetURLAsNotPrecached(const GURL& url); - - // Populates the used and downloaded resource URLs for the referrer host with - // id |referrer_host_id|. - void GetURLListForReferrerHost(int64_t referrer_host_id, - std::vector<GURL>* used_urls, - std::vector<GURL>* downloaded_urls); - - // Sets all the URLs of the given referrer_host_id as is_download_reported. - void SetDownloadReported(int64_t referrer_host_id); - - // Clears all URL entries for the referrer host |referrer_host_id|. - void ClearAllForReferrerHost(int64_t referrer_host_id); - - // Deletes entries that were precached before the time of |delete_end|. - void DeleteAllPrecachedBefore(const base::Time& delete_end); - - // Delete all entries. - void DeleteAll(); - - // Used by tests to get the contents of the table. - void GetAllDataForTesting(std::map<GURL, base::Time>* map); - - private: - bool CreateTableIfNonExistent(); - - // Non-owned pointer. - sql::Connection* db_; - - DISALLOW_COPY_AND_ASSIGN(PrecacheURLTable); -}; - -} // namespace precache - -#endif // COMPONENTS_PRECACHE_CORE_PRECACHE_URL_TABLE_H_
diff --git a/components/precache/core/precache_url_table_unittest.cc b/components/precache/core/precache_url_table_unittest.cc deleted file mode 100644 index ab9fc40..0000000 --- a/components/precache/core/precache_url_table_unittest.cc +++ /dev/null
@@ -1,202 +0,0 @@ -// 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 "components/precache/core/precache_url_table.h" - -#include <map> -#include <memory> -#include <set> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/compiler_specific.h" -#include "base/time/time.h" -#include "sql/connection.h" -#include "sql/statement.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace precache { - -void PrintTo(const PrecacheURLInfo& url_info, ::std::ostream* os) { - *os << "{" << url_info.was_precached << ", " << url_info.is_precached << ", " - << url_info.was_used << ", " << url_info.is_download_reported << "}"; -} - -namespace { - -class PrecacheURLTableTest : public testing::Test { - public: - PrecacheURLTableTest() {} - ~PrecacheURLTableTest() override {} - - protected: - void SetUp() override { - precache_url_table_.reset(new PrecacheURLTable()); - db_.reset(new sql::Connection()); - ASSERT_TRUE(db_->OpenInMemory()); - ASSERT_TRUE(precache_url_table_->Init(db_.get())); - } - - std::unique_ptr<PrecacheURLTable> precache_url_table_; - std::unique_ptr<sql::Connection> db_; -}; - -TEST_F(PrecacheURLTableTest, AddURLWithNoExistingRow) { - const base::Time kTime = base::Time::FromInternalValue(100); - precache_url_table_->AddURL(GURL("http://url.com"), 1, true, kTime, false); - - std::map<GURL, base::Time> expected_map; - expected_map[GURL("http://url.com")] = kTime; - - std::map<GURL, base::Time> actual_map; - precache_url_table_->GetAllDataForTesting(&actual_map); - EXPECT_EQ(expected_map, actual_map); -} - -TEST_F(PrecacheURLTableTest, AddURLWithExistingRow) { - const base::Time kOldTime = base::Time::FromInternalValue(50); - const base::Time kNewTime = base::Time::FromInternalValue(100); - precache_url_table_->AddURL(GURL("http://url.com"), 1, true, kOldTime, false); - precache_url_table_->AddURL(GURL("http://url.com"), 1, true, kNewTime, false); - - std::map<GURL, base::Time> expected_map; - expected_map[GURL("http://url.com")] = kNewTime; - - std::map<GURL, base::Time> actual_map; - precache_url_table_->GetAllDataForTesting(&actual_map); - EXPECT_EQ(expected_map, actual_map); -} - -TEST_F(PrecacheURLTableTest, SetURLAsNotPrecached) { - const base::Time kStaysTime = base::Time::FromInternalValue(50); - const base::Time kDeletedTime = base::Time::FromInternalValue(100); - - precache_url_table_->AddURL(GURL("http://stays.com"), 1, true, kStaysTime, - false); - precache_url_table_->AddURL(GURL("http://deleted.com"), 1, true, kDeletedTime, - false); - - precache_url_table_->SetURLAsNotPrecached(GURL("http://deleted.com")); - - std::map<GURL, base::Time> expected_map; - expected_map[GURL("http://stays.com")] = kStaysTime; - - std::map<GURL, base::Time> actual_map; - precache_url_table_->GetAllDataForTesting(&actual_map); - EXPECT_EQ(expected_map, actual_map); -} - -TEST_F(PrecacheURLTableTest, SetDownloadReported) { - const GURL url("http://stays.com"); - precache_url_table_->AddURL(url, 1, true, base::Time::FromInternalValue(50), - false); - - precache_url_table_->SetDownloadReported(1); - - EXPECT_EQ((PrecacheURLInfo{true, true, false, true}), - precache_url_table_->GetURLInfo(url)); -} - -TEST_F(PrecacheURLTableTest, GetURLInfo) { - const GURL url("http://url.com"); - - EXPECT_EQ((PrecacheURLInfo{false, false, false, false}), - precache_url_table_->GetURLInfo(url)); - - precache_url_table_->AddURL(url, 1, true, base::Time::FromInternalValue(100), - true); - - EXPECT_EQ((PrecacheURLInfo{true, true, false, true}), - precache_url_table_->GetURLInfo(url)); - - precache_url_table_->SetPrecachedURLAsUsed(url); - - EXPECT_EQ((PrecacheURLInfo{true, false, true, true}), - precache_url_table_->GetURLInfo(url)); - - precache_url_table_->AddURL(url, 1, true, base::Time::FromInternalValue(100), - false); - - EXPECT_EQ((PrecacheURLInfo{true, true, false, false}), - precache_url_table_->GetURLInfo(url)); - - precache_url_table_->SetURLAsNotPrecached(url); - - EXPECT_EQ((PrecacheURLInfo{true, false, false, false}), - precache_url_table_->GetURLInfo(url)); - - precache_url_table_->SetDownloadReported(1); - - EXPECT_EQ((PrecacheURLInfo{true, false, false, true}), - precache_url_table_->GetURLInfo(url)); -} - -TEST_F(PrecacheURLTableTest, DeleteAllPrecachedBefore) { - const base::Time kOldTime = base::Time::FromInternalValue(10); - const base::Time kBeforeTime = base::Time::FromInternalValue(20); - const base::Time kEndTime = base::Time::FromInternalValue(30); - const base::Time kAfterTime = base::Time::FromInternalValue(40); - - precache_url_table_->AddURL(GURL("http://old.com"), 1, true, kOldTime, false); - precache_url_table_->AddURL(GURL("http://before.com"), 1, true, kBeforeTime, - false); - precache_url_table_->AddURL(GURL("http://end.com"), 1, true, kEndTime, false); - precache_url_table_->AddURL(GURL("http://after.com"), 1, true, kAfterTime, - false); - - precache_url_table_->DeleteAllPrecachedBefore(kEndTime); - - std::map<GURL, base::Time> expected_map; - expected_map[GURL("http://end.com")] = kEndTime; - expected_map[GURL("http://after.com")] = kAfterTime; - - std::map<GURL, base::Time> actual_map; - precache_url_table_->GetAllDataForTesting(&actual_map); - EXPECT_EQ(expected_map, actual_map); -} - -TEST_F(PrecacheURLTableTest, TableMigration) { - // Create the previous version of the URL table. - precache_url_table_.reset(new PrecacheURLTable()); - db_.reset(new sql::Connection()); - ASSERT_TRUE(db_->OpenInMemory()); - ASSERT_TRUE(db_->Execute( - "CREATE TABLE IF NOT EXISTS precache_urls (url TEXT PRIMARY KEY, time " - "INTEGER)")); - - // Populate data for the previous version. - const std::string old_urls[] = {"http://foo.com", "http://bar.com", - "http://foobar.com"}; - for (const auto& url : old_urls) { - sql::Statement statement(db_->GetCachedStatement( - SQL_FROM_HERE, "INSERT INTO precache_urls (url, time) VALUES(?,100)")); - statement.BindString(0, url); - statement.Run(); - } - - // Verify the migration. - ASSERT_TRUE(precache_url_table_->Init(db_.get())); - EXPECT_TRUE(db_->DoesColumnExist("precache_urls", "was_used")); - EXPECT_TRUE(db_->DoesColumnExist("precache_urls", "is_precached")); - EXPECT_TRUE(db_->DoesColumnExist("precache_urls", "referrer_host_id")); - - std::set<std::string> actual_urls; - sql::Statement statement( - db_->GetCachedStatement(SQL_FROM_HERE, - "select url, referrer_host_id, was_used, " - "is_precached from precache_urls")); - while (statement.Step()) { - actual_urls.insert(statement.ColumnString(0)); - EXPECT_EQ(0, statement.ColumnInt(1)); - EXPECT_EQ(0, statement.ColumnInt(2)); - EXPECT_EQ(1, statement.ColumnInt(3)); - } - EXPECT_THAT(std::set<std::string>(begin(old_urls), end(old_urls)), - ::testing::ContainerEq(actual_urls)); -} - -} // namespace - -} // namespace precache
diff --git a/components/precache/core/proto/precache.proto b/components/precache/core/proto/precache.proto deleted file mode 100644 index f8a10c0e..0000000 --- a/components/precache/core/proto/precache.proto +++ /dev/null
@@ -1,160 +0,0 @@ -// 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. - -syntax = "proto2"; - -package precache; - -// Chrome requires this. -option optimize_for = LITE_RUNTIME; - -// Information about a cacheable resource to be precached. -message PrecacheResource { - // The URL of the resource. This field must always be present. - optional string url = 1; - - // The tophost this resource corresponds to. - optional string top_host_name = 2; - - // How important this resource is for the host. It ranges from 0.0 to 1.0. - // Higher values mean more important. - optional double weight_ratio = 3; - - // How important this resource is for the client; a combination of - // weight_ratio and TopHost.visits. Populated only in PrecacheUnfinishedWork. - // This is a non-negative number, with higher being more important. Its value - // depends on PrecacheConfigurationSettings.resource_weight_function. - optional double weight = 4; - - enum Type { - RESOURCE_TYPE_UNKNOWN = 0; - - RESOURCE_TYPE_IMAGE = 1; - RESOURCE_TYPE_FONT = 2; - RESOURCE_TYPE_STYLESHEET = 3; - RESOURCE_TYPE_SCRIPT = 4; - - RESOURCE_TYPE_OTHER = 7; - } - - // The type of resource. - optional Type type = 5; -}; - -message PrecacheManifestId { - optional int64 id = 1; -}; - -// A manifest of cacheable resources to be precached for a specific host. -// CAUTION: When any change is done here, bump kDatabaseVersion in -// chrome/browser/predictors/resource_prefetch_predictor_tables.h -message PrecacheManifest { - // List of resources that we predict that the user will need if they are - // likely to fetch the host. - repeated PrecacheResource resource = 1; - - // Experiments running on this manifest. - optional PrecacheExperiments experiments = 2; - - // Identifier for the manifest sent by the server. - optional PrecacheManifestId id = 3; -}; - -message PrecacheExperiments { - // A mapping between experiment groups and the resources that should be - // considered for the experiment. - map<fixed32, PrecacheResourceSelection> resources_by_experiment_group = 1; -}; - -// Determines which of the resources in the manifest should be selected. -message PrecacheResourceSelection { - // A bitset over the resources listed in the manifest. Bits correspond to - // resource position in LSB-to-MSB order, as in: - // - // if ((0x1ULL << i) && DEPRECATED_bitset) IncludeResource(i); - // - // Deprecated because it only supports up to 64 resources. - optional fixed64 DEPRECATED_bitset = 1 - [default = 0xFFFFFFFFFFFFFFFF, deprecated = true]; - - // A bitset over the resources listed in the manifest. Bits correspond to - // resource position. Bytes are ordered little-endian, and bits within each - // byte are ordered LSB-to-MSB. The resulting bitstream is of mixed order, - // but easy to test: - // - // if ((1 << (i % 8)) & bitset[i / 8]) IncludeResource(i); - // - // Takes precedence over DEPRECATED_bitset, if both are present. - optional bytes bitset = 2; - - // A PrecacheResourceSelection without DEPRECATED_bitset or bitset means that - // all resources should be selected. -}; - -message PrecacheConfigurationSettings { - // The maximum rank of the user's most visited hosts to consider precaching - // resources for, starting from 1. For example, a value of 10 means that only - // hosts that are in the user's top 10 most visited hosts will be considered - // as starting URLs for resource precaching. This is specified by the server - // for testing purposes, so that it's easy to adjust how aggressively - // resources are precached. - // Values that are zero or lower indicate that none of the user's top sites - // will be used for precaching. - optional int64 top_sites_count = 1 [default = 100]; - - // List of additional hosts that resources will be precached for. - // These are hosts that the server predicts that the user will visit, as a - // result of server-side analytics. - repeated string forced_site = 2; - - // The number of resources to fetch for each site. Only the top - // |top_resources_count| URLs from each manifest are fetched. - optional int32 top_resources_count = 3 [default = 100]; - - // The maximum number of bytes to download per resource. Downloads of - // resources larger than this will be cancelled. This max applies only to new - // downloads; cached resources are not capped. - optional uint64 max_bytes_per_resource = 4 [default = 500000 /* 500 KB */]; - - // The maximum number of bytes per precache run. While precaching, the total - // number of bytes used for resources is tallied -- this includes new - // downloads as well as cached resources. After this limit is reached, no - // other resources will be downloaded. - optional uint64 max_bytes_total = 5 [default = 10000000 /* 10 MB */]; - - // The maximum number of bytes that can be fetched by precache on a single - // day. After this limit is reached, no more resources will be downloaded, - // until the quota gets replenished the next day. - optional uint64 daily_quota_total = 6 [default = 40000000 /* 40 MB */]; - - // The number of resources to fetch per precache run. Only the first - // |total_resources_count| resource URLs are fetched. - optional uint32 total_resources_count = 7 [default = 999999]; - - // The minimum visit-adjusted weight for which a resource will be downloaded. - optional double min_weight = 8 [default = 0]; - - // Whether to sort resources by weight, descending, before fetching. This - // affects the fetcher's behavior with respect to max_bytes_total and - // total_resources_count. - optional bool global_ranking = 9 [default = false]; - - // If true, resource fetches are only made over the network for a given URL if - // an existing cache entry exists and has revalidation headers. - optional bool revalidation_only = 10 [default = false]; - - // The function to use to combine a resource's weight_ratio with its - // referring manifest's host_visits count to produce a final score. - enum ResourceWeightFunction { - // Models the expected number of requests for the resource in the next 30 - // days, given that weight_ratio is a probability that a visit to the host - // will request a resource, and host_visits is an estimate of the number of - // visits to the host in the next 30 days. - FUNCTION_NAIVE = 0; - // Models the probability of at least one request, given the same. - FUNCTION_GEOMETRIC = 1; - }; - optional ResourceWeightFunction resource_weight_function = 11 - [default = FUNCTION_NAIVE]; -};
diff --git a/components/precache/core/proto/quota.proto b/components/precache/core/proto/quota.proto deleted file mode 100644 index 6a60e7c5..0000000 --- a/components/precache/core/proto/quota.proto +++ /dev/null
@@ -1,25 +0,0 @@ -// 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. - -syntax = "proto2"; - -package precache; - -// Chrome requires this. -option optimize_for = LITE_RUNTIME; - -// Quota limit and expiry time. This is stored in a database, and not -// transferred via network. -message PrecacheQuota { - // Represents the start time of this quota. After enough time has elapsed - // since the start time (as defined in PrecacheFetcher::IsQuotaTimeExpired), a - // new quota is created. - optional int64 start_time = 1; - - // Maximum number of bytes that can be fetched until this quota expires. - // Initialized to PrecacheConfigurationSettings.daily_quota_total and - // decremented for every byte downloaded. After this reaches zero, the - // PrecacheFetcher will not download any more until a new quota window starts. - optional uint64 remaining = 2; -};
diff --git a/components/precache/core/proto/timestamp.proto b/components/precache/core/proto/timestamp.proto deleted file mode 100644 index 7d7efaf..0000000 --- a/components/precache/core/proto/timestamp.proto +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -syntax = "proto2"; - -package precache; - -// Chrome requires this. -option optimize_for = LITE_RUNTIME; - -message Timestamp { - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - optional int64 seconds = 1; -}
diff --git a/components/precache/core/proto/unfinished_work.proto b/components/precache/core/proto/unfinished_work.proto deleted file mode 100644 index cd07cba..0000000 --- a/components/precache/core/proto/unfinished_work.proto +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -syntax = "proto2"; - -import "precache.proto"; - -package precache; - -// Chrome requires this. -option optimize_for = LITE_RUNTIME; - -message TopHost { - // The host name of a top host. - optional string hostname = 1; - - // The number of visits it had by this user. - optional int64 visits = 2; -}; - -// Information about the precache work that needs to be completed. -message PrecacheUnfinishedWork { - // Top hosts for which to fetch manifests. - repeated TopHost top_host = 1; - - optional PrecacheConfigurationSettings config_settings = 2; - - // DEPRECATED: Manifest URLs remaining to be fetched. - // repeated DeprecatedPrecacheManifestURL deprecated_manifest = 3 - // [deprecated = true]; - - // Resource URLs remaining to be fetched. - repeated PrecacheResource resource = 4; - - // Tally of the total number of bytes contained in URL fetches, including - // config, manifests, and resources. This the number of bytes as they would be - // compressed over the network. - optional uint64 total_bytes = 5; - - // Tally of the total number of bytes received over the network from URL - // fetches (the same ones as in total_response_bytes_). This includes response - // headers and intermediate responses such as 30xs. - optional uint64 network_bytes = 6; - - // The total number of manifest URLs that the precache session started with. - optional uint64 num_manifest_urls = 7; - - // The total number of resource URLs that the precache session gathered from - // the manifests. - optional uint64 num_resource_urls = 9; - - // The internal value of a base::Time object representing the precache - // session start time. The start time is the time just before when top hosts - // are requested. - optional int64 start_time = 8; - - // The minimum resource weight that has been fetched so far. Populated only if - // global ranking is enabled. - optional double min_weight_fetched = 10; -};
diff --git a/content/browser/generic_sensor_browsertest.cc b/content/browser/generic_sensor_browsertest.cc index 9963d19..aab6636 100644 --- a/content/browser/generic_sensor_browsertest.cc +++ b/content/browser/generic_sensor_browsertest.cc
@@ -63,6 +63,7 @@ void Suspend() override {} void Resume() override {} + void ConfigureReadingChangeNotifications(bool enabled) override {} device::PlatformSensorConfiguration GetDefaultConfiguration() { return device::PlatformSensorConfiguration(60 /* frequency */);
diff --git a/content/shell/android/BUILD.gn b/content/shell/android/BUILD.gn index 96af4c2..618bbf2 100644 --- a/content/shell/android/BUILD.gn +++ b/content/shell/android/BUILD.gn
@@ -166,6 +166,7 @@ android_manifest_dep = ":content_shell_manifest" shared_libraries = [ ":libcontent_shell_content_view" ] loadable_modules = [ "$root_out_dir/libosmesa.so" ] + command_line_flags_file = "content-shell-command-line" } android_library("content_shell_test_java") {
diff --git a/content/test/gpu/gpu_tests/webgl_conformance_expectations.py b/content/test/gpu/gpu_tests/webgl_conformance_expectations.py index 8c1523c1..42810c9 100644 --- a/content/test/gpu/gpu_tests/webgl_conformance_expectations.py +++ b/content/test/gpu/gpu_tests/webgl_conformance_expectations.py
@@ -111,6 +111,10 @@ self.Fail('conformance/glsl/misc/uninitialized-local-global-variables.html', bug=1966) # angle bug ID + # Don't run performance tests on debug builds + self.Skip('conformance/rendering/texture-switch-performance.html', + ['debug']) + # Passthrough command decoder self.Fail('conformance/extensions/webgl-draw-buffers.html', ['passthrough'], bug=1523) # angle bug ID @@ -380,7 +384,7 @@ self.Fail('conformance/rendering/clipping-wide-points.html', ['mac', 'amd'], bug=642822) self.Fail('conformance/rendering/texture-switch-performance.html', - ['mac', 'amd'], bug=735483) + ['mac', 'amd', 'release'], bug=735483) # Mac Retina NVidia failures self.Fail('conformance/attribs/gl-disabled-vertex-attrib.html',
diff --git a/headless/lib/browser/headless_web_contents_impl.cc b/headless/lib/browser/headless_web_contents_impl.cc index 72c15af7..4d36bb21 100644 --- a/headless/lib/browser/headless_web_contents_impl.cc +++ b/headless/lib/browser/headless_web_contents_impl.cc
@@ -48,6 +48,15 @@ return static_cast<HeadlessWebContentsImpl*>(web_contents); } +// static +HeadlessWebContentsImpl* HeadlessWebContentsImpl::From( + HeadlessBrowser* browser, + content::WebContents* contents) { + return HeadlessWebContentsImpl::From( + browser->GetWebContentsForDevToolsAgentHostId( + content::DevToolsAgentHost::GetOrCreateFor(contents)->GetId())); +} + class HeadlessWebContentsImpl::Delegate : public content::WebContentsDelegate { public: explicit Delegate(HeadlessWebContentsImpl* headless_web_contents) @@ -94,12 +103,30 @@ } void CloseContents(content::WebContents* source) override { - if (source != headless_web_contents_->web_contents()) - return; - headless_web_contents_->Close(); + auto* const headless_contents = + HeadlessWebContentsImpl::From(browser(), source); + DCHECK(headless_contents); + headless_contents->Close(); + } + + void AddNewContents(content::WebContents* source, + content::WebContents* new_contents, + WindowOpenDisposition disposition, + const gfx::Rect& initial_rect, + bool user_gesture, + bool* was_blocked) override { + const gfx::Rect default_rect( + headless_web_contents_->browser()->options()->window_size); + const gfx::Rect rect = initial_rect.IsEmpty() ? default_rect : initial_rect; + auto* const headless_contents = + HeadlessWebContentsImpl::From(browser(), new_contents); + DCHECK(headless_contents); + headless_contents->SetBounds(rect); } private: + HeadlessBrowserImpl* browser() { return headless_web_contents_->browser(); } + HeadlessWebContentsImpl* headless_web_contents_; // Not owned. DISALLOW_COPY_AND_ASSIGN(Delegate); };
diff --git a/headless/lib/browser/headless_web_contents_impl.h b/headless/lib/browser/headless_web_contents_impl.h index af14c7a..6ea8441b 100644 --- a/headless/lib/browser/headless_web_contents_impl.h +++ b/headless/lib/browser/headless_web_contents_impl.h
@@ -29,6 +29,7 @@ } namespace headless { +class HeadlessBrowser; class HeadlessBrowserImpl; class HeadlessTabSocketImpl; @@ -43,6 +44,8 @@ ~HeadlessWebContentsImpl() override; static HeadlessWebContentsImpl* From(HeadlessWebContents* web_contents); + static HeadlessWebContentsImpl* From(HeadlessBrowser* browser, + content::WebContents* contents); static std::unique_ptr<HeadlessWebContentsImpl> Create( HeadlessWebContents::Builder* builder);
diff --git a/headless/lib/headless_web_contents_browsertest.cc b/headless/lib/headless_web_contents_browsertest.cc index 9d4196ccb..5284ccb6 100644 --- a/headless/lib/headless_web_contents_browsertest.cc +++ b/headless/lib/headless_web_contents_browsertest.cc
@@ -9,6 +9,8 @@ #include "base/base64.h" #include "base/json/json_writer.h" #include "base/strings/stringprintf.h" +#include "build/build_config.h" +#include "content/public/browser/web_contents.h" #include "content/public/test/browser_test.h" #include "headless/lib/browser/headless_web_contents_impl.h" #include "headless/public/devtools/domains/dom_snapshot.h" @@ -105,6 +107,16 @@ // Mac doesn't have WindowTreeHosts. if (parent && child && parent->window_tree_host()) EXPECT_NE(parent->window_tree_host(), child->window_tree_host()); + + gfx::Rect expected_bounds(0, 0, 200, 100); +#if !defined(OS_MACOSX) + EXPECT_EQ(expected_bounds, child->web_contents()->GetViewBounds()); + EXPECT_EQ(expected_bounds, child->web_contents()->GetContainerBounds()); +#else // !defined(OS_MACOSX) + // Mac does not support GetViewBounds() and view positions are random. + EXPECT_EQ(expected_bounds.size(), + child->web_contents()->GetContainerBounds().size()); +#endif // !defined(OS_MACOSX) } class HeadlessWindowOpenTabSocketTest : public HeadlessBrowserTest,
diff --git a/headless/test/data/window_open.html b/headless/test/data/window_open.html index dd5d7ea..46ce703 100644 --- a/headless/test/data/window_open.html +++ b/headless/test/data/window_open.html
@@ -1,3 +1,3 @@ <script> - window.open(); + window.open("", "", "width=200,height=100"); </script>
diff --git a/ios/chrome/browser/ui/authentication/signin_promo_view_consumer.h b/ios/chrome/browser/ui/authentication/signin_promo_view_consumer.h index 9f21871..b9b76b90 100644 --- a/ios/chrome/browser/ui/authentication/signin_promo_view_consumer.h +++ b/ios/chrome/browser/ui/authentication/signin_promo_view_consumer.h
@@ -20,6 +20,11 @@ (SigninPromoViewConfigurator*)configurator identityChanged:(BOOL)identityChanged; +@optional + +// Called when the sign-in is finished. +- (void)signinDidFinish; + @end #endif // IOS_CHROME_BROWSER_UI_AUTHENTICATION_SIGNIN_PROMO_VIEW_CONSUMER_H_
diff --git a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h index a5be9e98..3478315 100644 --- a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h +++ b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h
@@ -24,6 +24,20 @@ // Histograms: MobileSignInPromo.BookmarkManager.*. Bookmarks, }; + +// Enums for the sign-in promo view state. +enum class SigninPromoViewState { + // None of the buttons has been used yet. + Unused = 0, + // Sign-in is in progress. + SigninStarted, + // Sign-in buttons has been used at least once. + UsedAtLeastOnce, + // Sign-in promo has been closed. + Closed, + // Sign-in promo view has been removed. + Invalid, +}; } // namespace ios // Class that monitors the available identities and creates @@ -50,6 +64,8 @@ @property(nonatomic) const char* alreadySeenSigninViewPreferenceKey; // Histograms to use for the user actions. @property(nonatomic) ios::SigninPromoViewHistograms histograms; +// Sign-in promo view state. +@property(nonatomic) ios::SigninPromoViewState signinPromoViewState; // See -[SigninPromoViewMediator initWithBrowserState:]. - (instancetype)init NS_UNAVAILABLE; @@ -67,8 +83,13 @@ // Called when the sign-in promo view is hidden. - (void)signinPromoViewHidden; -// Called when the sign-in promo view is dismissed. -- (void)signinPromoViewDismissed; +// Called when the sign-in promo view is closed. +- (void)signinPromoViewClosed; + +// Called when the sign-in promo view is removed from the view hierarchy (it or +// one of its superviews is removed). The mediator should not be used after this +// called. +- (void)signinPromoViewRemoved; @end
diff --git a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm index d3f5e151..5a1396b 100644 --- a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm +++ b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm
@@ -13,6 +13,8 @@ #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/chrome_browser_provider_observer_bridge.h" #include "ios/chrome/browser/pref_names.h" +#import "ios/chrome/browser/signin/authentication_service.h" +#include "ios/chrome/browser/signin/authentication_service_factory.h" #include "ios/chrome/browser/signin/chrome_identity_service_observer_bridge.h" #import "ios/chrome/browser/ui/authentication/signin_promo_view_configurator.h" #import "ios/chrome/browser/ui/authentication/signin_promo_view_consumer.h" @@ -119,14 +121,6 @@ break; } } - -enum class SigninPromoViewState { - Unused = 0, - Visible, - Hidden, - SigninStarted, - Dismissed, -}; } // namespace @interface SigninPromoViewMediator ()<ChromeIdentityServiceObserver, @@ -138,7 +132,7 @@ std::unique_ptr<ChromeIdentityServiceObserverBridge> _identityServiceObserver; std::unique_ptr<ChromeBrowserProviderObserverBridge> _browserProviderObserver; UIImage* _identityAvatar; - SigninPromoViewState _signinPromoViewState; + BOOL _isSigninPromoViewVisible; } @synthesize consumer = _consumer; @@ -148,6 +142,7 @@ @synthesize alreadySeenSigninViewPreferenceKey = _alreadySeenSigninViewPreferenceKey; @synthesize histograms = _histograms; +@synthesize signinPromoViewState = _signinPromoViewState; - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { self = [super init]; @@ -168,21 +163,12 @@ } - (void)dealloc { - if (_displayedCountPreferenceKey && - (_signinPromoViewState == SigninPromoViewState::Visible || - _signinPromoViewState == SigninPromoViewState::Hidden)) { - PrefService* prefs = _browserState->GetPrefs(); - int displayedCount = prefs->GetInteger(_displayedCountPreferenceKey); - switch (_histograms) { - case ios::SigninPromoViewHistograms::Bookmarks: - UMA_HISTOGRAM_COUNTS_100( - "MobileSignInPromo.BookmarkManager.ImpressionsTilDismiss", - displayedCount); - break; - case ios::SigninPromoViewHistograms::None: - break; - } - } + DCHECK_EQ(ios::SigninPromoViewState::Invalid, _signinPromoViewState); +} + +- (BOOL)isInvalidOrClosed { + return _signinPromoViewState == ios::SigninPromoViewState::Closed || + _signinPromoViewState == ios::SigninPromoViewState::Invalid; } - (SigninPromoViewConfigurator*)createConfigurator { @@ -226,9 +212,9 @@ } - (void)sendImpressionsTillSigninButtonsHistogram { - DCHECK(_signinPromoViewState != SigninPromoViewState::Dismissed || - _signinPromoViewState != SigninPromoViewState::Unused); - _signinPromoViewState = SigninPromoViewState::SigninStarted; + DCHECK(![self isInvalidOrClosed] || + _signinPromoViewState != ios::SigninPromoViewState::Unused); + _signinPromoViewState = ios::SigninPromoViewState::SigninStarted; if (!_displayedCountPreferenceKey) return; PrefService* prefs = _browserState->GetPrefs(); @@ -245,10 +231,10 @@ } - (void)signinPromoViewVisible { - DCHECK(_signinPromoViewState != SigninPromoViewState::Dismissed); - if (_signinPromoViewState == SigninPromoViewState::Visible) + DCHECK(![self isInvalidOrClosed]); + if (_isSigninPromoViewVisible) return; - _signinPromoViewState = SigninPromoViewState::Visible; + _isSigninPromoViewVisible = YES; if (!_displayedCountPreferenceKey) return; PrefService* prefs = _browserState->GetPrefs(); @@ -262,17 +248,13 @@ } - (void)signinPromoViewHidden { - DCHECK(_signinPromoViewState != SigninPromoViewState::Unused || - _signinPromoViewState != SigninPromoViewState::Dismissed); - if (_signinPromoViewState != SigninPromoViewState::Visible) - return; - _signinPromoViewState = SigninPromoViewState::Hidden; + DCHECK(![self isInvalidOrClosed]); + _isSigninPromoViewVisible = NO; } -- (void)signinPromoViewDismissed { - DCHECK(_signinPromoViewState != SigninPromoViewState::Unused || - _signinPromoViewState != SigninPromoViewState::Hidden); - _signinPromoViewState = SigninPromoViewState::Dismissed; +- (void)signinPromoViewClosed { + DCHECK(_isSigninPromoViewVisible && ![self isInvalidOrClosed]); + _signinPromoViewState = ios::SigninPromoViewState::Closed; if (!_displayedCountPreferenceKey) return; PrefService* prefs = _browserState->GetPrefs(); @@ -288,6 +270,41 @@ } } +- (void)signinPromoViewRemoved { + DCHECK_NE(ios::SigninPromoViewState::Invalid, _signinPromoViewState); + BOOL wasUnused = _signinPromoViewState == ios::SigninPromoViewState::Unused; + _signinPromoViewState = ios::SigninPromoViewState::Invalid; + // If the sign-in promo view has been used at least once, it should not be + // counted as dismissed (even if the sign-in has been canceled). + if (!_displayedCountPreferenceKey || !wasUnused) + return; + // If the sign-in view is removed when the user is authenticated, then the + // sign-in has been done by another view, and this mediator cannot be counted + // as being dismissed. + AuthenticationService* authService = + AuthenticationServiceFactory::GetForBrowserState(_browserState); + if (authService->IsAuthenticated()) + return; + PrefService* prefs = _browserState->GetPrefs(); + int displayedCount = prefs->GetInteger(_displayedCountPreferenceKey); + switch (_histograms) { + case ios::SigninPromoViewHistograms::Bookmarks: + UMA_HISTOGRAM_COUNTS_100( + "MobileSignInPromo.BookmarkManager.ImpressionsTilDismiss", + displayedCount); + break; + case ios::SigninPromoViewHistograms::None: + break; + } +} + +- (void)signinCallback { + DCHECK_EQ(ios::SigninPromoViewState::SigninStarted, _signinPromoViewState); + _signinPromoViewState = ios::SigninPromoViewState::UsedAtLeastOnce; + if ([_consumer respondsToSelector:@selector(signinDidFinish)]) + [_consumer signinDidFinish]; +} + #pragma mark - ChromeIdentityServiceObserver - (void)identityListChanged { @@ -330,42 +347,55 @@ - (void)signinPromoViewDidTapSigninWithNewAccount: (SigninPromoView*)signinPromoView { - DCHECK(!_defaultIdentity); + DCHECK(!_defaultIdentity && ![self isInvalidOrClosed]); [self sendImpressionsTillSigninButtonsHistogram]; RecordSigninUserActionForAccessPoint(_accessPoint); RecordSigninNewAccountUserActionForAccessPoint(_accessPoint); + __weak SigninPromoViewMediator* weakSelf = self; ShowSigninCommand* command = [[ShowSigninCommand alloc] initWithOperation:AUTHENTICATION_OPERATION_SIGNIN + identity:nil accessPoint:_accessPoint - promoAction:signin_metrics::PromoAction::PROMO_ACTION_NEW_ACCOUNT]; + promoAction:signin_metrics::PromoAction::PROMO_ACTION_NEW_ACCOUNT + callback:^(BOOL succeeded) { + [weakSelf signinCallback]; + }]; [signinPromoView chromeExecuteCommand:command]; } - (void)signinPromoViewDidTapSigninWithDefaultAccount: (SigninPromoView*)signinPromoView { - DCHECK(_defaultIdentity); + DCHECK(_defaultIdentity && ![self isInvalidOrClosed]); [self sendImpressionsTillSigninButtonsHistogram]; RecordSigninUserActionForAccessPoint(_accessPoint); RecordSigninDefaultUserActionForAccessPoint(_accessPoint); + __weak SigninPromoViewMediator* weakSelf = self; ShowSigninCommand* command = [[ShowSigninCommand alloc] initWithOperation:AUTHENTICATION_OPERATION_SIGNIN identity:_defaultIdentity accessPoint:_accessPoint promoAction:signin_metrics::PromoAction::PROMO_ACTION_WITH_DEFAULT - callback:nil]; + callback:^(BOOL succeeded) { + [weakSelf signinCallback]; + }]; [signinPromoView chromeExecuteCommand:command]; } - (void)signinPromoViewDidTapSigninWithOtherAccount: (SigninPromoView*)signinPromoView { - DCHECK(_defaultIdentity); + DCHECK(_defaultIdentity && ![self isInvalidOrClosed]); [self sendImpressionsTillSigninButtonsHistogram]; RecordSigninNotDefaultUserActionForAccessPoint(_accessPoint); RecordSigninUserActionForAccessPoint(_accessPoint); + __weak SigninPromoViewMediator* weakSelf = self; ShowSigninCommand* command = [[ShowSigninCommand alloc] initWithOperation:AUTHENTICATION_OPERATION_SIGNIN + identity:nil accessPoint:_accessPoint - promoAction:signin_metrics::PromoAction::PROMO_ACTION_NOT_DEFAULT]; + promoAction:signin_metrics::PromoAction::PROMO_ACTION_NOT_DEFAULT + callback:^(BOOL succeeded) { + [weakSelf signinCallback]; + }]; [signinPromoView chromeExecuteCommand:command]; }
diff --git a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator_unittest.mm b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator_unittest.mm index 088cdeb4..3f5cbe86 100644 --- a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator_unittest.mm +++ b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator_unittest.mm
@@ -37,6 +37,7 @@ } void TearDown() override { + [mediator_ signinPromoViewRemoved]; mediator_ = nil; EXPECT_OCMOCK_VERIFY((id)consumer_); EXPECT_OCMOCK_VERIFY((id)signin_promo_view_);
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.h b/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.h index 0e32be7f..d07f383 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.h +++ b/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.h
@@ -105,7 +105,7 @@ - (void)resetFolder:(const bookmarks::BookmarkNode*)folder; // Called when something outside the view causes the promo state to change. -- (void)promoStateChangedAnimated:(BOOL)animate; +- (void)promoStateChangedAnimated:(BOOL)animated; @property(nonatomic, assign, readonly) bookmarks::BookmarkModel* bookmarkModel; @property(nonatomic, weak, readonly) id<UrlLoader> loader;
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.mm b/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.mm index 9e4992c..b1b08de 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.mm +++ b/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.mm
@@ -227,6 +227,7 @@ } - (void)dealloc { + [_signinPromoViewMediator signinPromoViewRemoved]; _collectionView.dataSource = nil; _collectionView.delegate = nil; UIView* moi = _collectionView; @@ -328,37 +329,41 @@ [self.delegate bookmarkCollectionViewDidScroll:self]; } -- (void)promoStateChangedAnimated:(BOOL)animate { - BOOL newPromoState = - !self.editing && self.folder && - self.folder->type() == BookmarkNode::MOBILE && - [self.delegate bookmarkCollectionViewShouldShowPromoCell:self]; - if (newPromoState != _promoVisible) { - // This is awful, but until the old code to do the refresh when switching - // in and out of edit mode is fixed, this is probably the cleanest thing to - // do. - _promoVisible = newPromoState; - if (experimental_flags::IsSigninPromoEnabled()) { - if (!_promoVisible) { - _signinPromoViewMediator.consumer = nil; - _signinPromoViewMediator = nil; - } else { - _signinPromoViewMediator = [[SigninPromoViewMediator alloc] - initWithBrowserState:_browserState]; - _signinPromoViewMediator.consumer = self; - _signinPromoViewMediator.displayedCountPreferenceKey = - prefs::kIosBookmarkSigninPromoDisplayedCount; - _signinPromoViewMediator.alreadySeenSigninViewPreferenceKey = - prefs::kIosBookmarkPromoAlreadySeen; - _signinPromoViewMediator.histograms = - ios::SigninPromoViewHistograms::Bookmarks; - _signinPromoViewMediator.accessPoint = - signin_metrics::AccessPoint::ACCESS_POINT_BOOKMARK_MANAGER; - [_signinPromoViewMediator signinPromoViewVisible]; - } +- (void)promoStateChangedAnimated:(BOOL)animated { + BOOL shouldShowPromo = + (!self.editing && self.folder && + self.folder->type() == BookmarkNode::MOBILE && + [self.delegate bookmarkCollectionViewShouldShowPromoCell:self]) || + (_signinPromoViewMediator && + _signinPromoViewMediator.signinPromoViewState == + ios::SigninPromoViewState::SigninStarted); + if (shouldShowPromo == _promoVisible) + return; + // This is awful, but until the old code to do the refresh when switching + // in and out of edit mode is fixed, this is probably the cleanest thing to + // do. + _promoVisible = shouldShowPromo; + if (experimental_flags::IsSigninPromoEnabled()) { + if (!_promoVisible) { + _signinPromoViewMediator.consumer = nil; + [_signinPromoViewMediator signinPromoViewRemoved]; + _signinPromoViewMediator = nil; + } else { + _signinPromoViewMediator = + [[SigninPromoViewMediator alloc] initWithBrowserState:_browserState]; + _signinPromoViewMediator.consumer = self; + _signinPromoViewMediator.displayedCountPreferenceKey = + prefs::kIosBookmarkSigninPromoDisplayedCount; + _signinPromoViewMediator.alreadySeenSigninViewPreferenceKey = + prefs::kIosBookmarkPromoAlreadySeen; + _signinPromoViewMediator.histograms = + ios::SigninPromoViewHistograms::Bookmarks; + _signinPromoViewMediator.accessPoint = + signin_metrics::AccessPoint::ACCESS_POINT_BOOKMARK_MANAGER; + [_signinPromoViewMediator signinPromoViewVisible]; } - [self.collectionView reloadData]; } + [self.collectionView reloadData]; } - (void)wasShown { @@ -818,7 +823,7 @@ // Removes the sign-in promo view. - (void)signinPromoCloseButtonAction { - [_signinPromoViewMediator signinPromoViewDismissed]; + [_signinPromoViewMediator signinPromoViewClosed]; [_delegate bookmarkCollectionViewDismissPromo:self]; } @@ -887,6 +892,10 @@ } } +- (void)signinDidFinish { + [self promoStateChangedAnimated:NO]; +} + #pragma mark - UIScrollViewDelegate - (void)scrollViewDidScroll:(UIScrollView*)scrollView {
diff --git a/ios/chrome/browser/ui/ntp/recent_tabs/recent_tabs_table_view_controller.mm b/ios/chrome/browser/ui/ntp/recent_tabs/recent_tabs_table_view_controller.mm index 401c916..abbdbbc 100644 --- a/ios/chrome/browser/ui/ntp/recent_tabs/recent_tabs_table_view_controller.mm +++ b/ios/chrome/browser/ui/ntp/recent_tabs/recent_tabs_table_view_controller.mm
@@ -182,6 +182,7 @@ } - (void)dealloc { + [_signinPromoViewMediator signinPromoViewRemoved]; [self.tableView removeObserver:self forKeyPath:@"contentSize"]; } @@ -554,8 +555,10 @@ withRowAnimation:UITableViewRowAnimationFade]; [self.tableView endUpdates]; - if (_sessionState != SessionsSyncUserState::USER_SIGNED_OUT) + if (_sessionState != SessionsSyncUserState::USER_SIGNED_OUT) { + [_signinPromoViewMediator signinPromoViewRemoved]; _signinPromoViewMediator = nil; + } } - (NSInteger)numberOfSessionSections {
diff --git a/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm b/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm index 2eb11dac..d8255d0 100644 --- a/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm
@@ -350,6 +350,7 @@ [model addItem:[self signInTextItem] toSectionWithIdentifier:SectionIdentifierSignIn]; } else { + [_signinPromoViewMediator signinPromoViewRemoved]; _signinPromoViewMediator = nil; [model addItem:[self accountCellItem] toSectionWithIdentifier:SectionIdentifierSignIn]; @@ -1034,6 +1035,8 @@ "MobileSignInPromo.SettingsManager.ImpressionsTilDismiss", displayedCount); } + [_signinPromoViewMediator signinPromoViewRemoved]; + _signinPromoViewMediator = nil; [_signinInteractionController cancel]; [self stopBrowserStateServiceObservers]; }
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_switcher_panel_overlay_view.mm b/ios/chrome/browser/ui/tab_switcher/tab_switcher_panel_overlay_view.mm index 3789705d..f3d6ceef 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_switcher_panel_overlay_view.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_switcher_panel_overlay_view.mm
@@ -182,6 +182,10 @@ return self; } +- (void)dealloc { + [_signinPromoViewMediator signinPromoViewRemoved]; +} + - (void)layoutSubviews { [super layoutSubviews]; CGRect containerFrame = [_container frame]; @@ -205,6 +209,7 @@ [_signinPromoView removeFromSuperview]; _signinPromoView = nil; _signinPromoViewMediator.consumer = nil; + [_signinPromoViewMediator signinPromoViewRemoved]; _signinPromoViewMediator = nil; [self updateText]; [self updateButtonTarget];
diff --git a/ios/web/BUILD.gn b/ios/web/BUILD.gn index 70e428c..c2be502 100644 --- a/ios/web/BUILD.gn +++ b/ios/web/BUILD.gn
@@ -235,12 +235,27 @@ "web_state/ui/crw_swipe_recognizer_provider.h", "web_state/ui/crw_touch_tracking_recognizer.h", "web_state/ui/crw_touch_tracking_recognizer.mm", + "web_state/ui/crw_web_view_content_view.mm", "web_state/ui/crw_web_view_navigation_proxy.h", "web_state/ui/crw_web_view_proxy_impl.h", "web_state/ui/crw_web_view_proxy_impl.mm", "web_state/ui/crw_web_view_scroll_view_proxy.mm", "web_state/ui/crw_wk_navigation_states.h", "web_state/ui/crw_wk_navigation_states.mm", + "web_state/ui/crw_wk_script_message_router.h", + "web_state/ui/crw_wk_script_message_router.mm", + "web_state/ui/web_view_js_utils.h", + "web_state/ui/web_view_js_utils.mm", + "web_state/ui/wk_back_forward_list_item_holder.h", + "web_state/ui/wk_back_forward_list_item_holder.mm", + "web_state/ui/wk_web_view_configuration_provider.h", + "web_state/ui/wk_web_view_configuration_provider.mm", + "web_state/web_controller_observer_bridge.h", + "web_state/web_controller_observer_bridge.mm", + "web_state/web_view_internal_creation_util.h", + "web_state/web_view_internal_creation_util.mm", + "web_state/wk_web_view_security_util.h", + "web_state/wk_web_view_security_util.mm", "web_thread_impl.cc", "web_thread_impl.h", "web_view_creation_util.mm", @@ -311,17 +326,6 @@ "web_state/ui/crw_web_controller.mm", "web_state/ui/crw_web_controller_container_view.h", "web_state/ui/crw_web_controller_container_view.mm", - "web_state/ui/crw_web_view_content_view.mm", - "web_state/ui/crw_wk_script_message_router.h", - "web_state/ui/crw_wk_script_message_router.mm", - "web_state/ui/web_view_js_utils.h", - "web_state/ui/web_view_js_utils.mm", - "web_state/ui/wk_back_forward_list_item_holder.h", - "web_state/ui/wk_back_forward_list_item_holder.mm", - "web_state/ui/wk_web_view_configuration_provider.h", - "web_state/ui/wk_web_view_configuration_provider.mm", - "web_state/web_controller_observer_bridge.h", - "web_state/web_controller_observer_bridge.mm", "web_state/web_state.mm", "web_state/web_state_delegate.mm", "web_state/web_state_delegate_bridge.mm", @@ -332,10 +336,6 @@ "web_state/web_state_policy_decider.mm", "web_state/web_state_weak_ptr_factory.h", "web_state/web_state_weak_ptr_factory.mm", - "web_state/web_view_internal_creation_util.h", - "web_state/web_view_internal_creation_util.mm", - "web_state/wk_web_view_security_util.h", - "web_state/wk_web_view_security_util.mm", ] libs = [
diff --git a/ios/web/public/web_state/ui/crw_content_view.h b/ios/web/public/web_state/ui/crw_content_view.h index fb04b6c..480a597 100644 --- a/ios/web/public/web_state/ui/crw_content_view.h +++ b/ios/web/public/web_state/ui/crw_content_view.h
@@ -14,7 +14,7 @@ // The scroll view used to display the content. If |scrollView| is non-nil, // it will be used to back the CRWContentViewScrollViewProxy and is expected to // be a subview of the CRWContentView. -@property(nonatomic, retain, readonly) UIScrollView* scrollView; +@property(nonatomic, strong, readonly) UIScrollView* scrollView; // Adds a top padding to content view. Implementations of this protocol can // implement this method using UIScrollView.contentInset (where applicable) or
diff --git a/ios/web/public/web_state/ui/crw_web_view_content_view.h b/ios/web/public/web_state/ui/crw_web_view_content_view.h index 28334c96..f6ea2662 100644 --- a/ios/web/public/web_state/ui/crw_web_view_content_view.h +++ b/ios/web/public/web_state/ui/crw_web_view_content_view.h
@@ -11,7 +11,7 @@ @interface CRWWebViewContentView : CRWContentView // The webView passed to |-initWithWebView|. -@property(nonatomic, retain, readonly) UIView* webView; +@property(nonatomic, strong, readonly) UIView* webView; // Initializes the CRWWebViewContentView to display |webView|. - (instancetype)initWithWebView:(UIView*)webView
diff --git a/ios/web/web_state/ui/crw_web_view_content_view.mm b/ios/web/web_state/ui/crw_web_view_content_view.mm index cda7343..cab3ef2 100644 --- a/ios/web/web_state/ui/crw_web_view_content_view.mm +++ b/ios/web/web_state/ui/crw_web_view_content_view.mm
@@ -7,7 +7,10 @@ #import <WebKit/WebKit.h> #include "base/logging.h" -#import "base/mac/scoped_nsobject.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif namespace { @@ -21,10 +24,6 @@ } // namespace @interface CRWWebViewContentView () { - // The web view being shown. - base::scoped_nsobject<UIView> _webView; - // The web view's scroll view. - base::scoped_nsobject<UIScrollView> _scrollView; // Backs up property of the same name if |_webView| is a WKWebView. CGFloat _topContentPadding; } @@ -38,6 +37,8 @@ @implementation CRWWebViewContentView @synthesize shouldUseInsetForTopPadding = _shouldUseInsetForTopPadding; +@synthesize scrollView = _scrollView; +@synthesize webView = _webView; - (instancetype)initWithWebView:(UIView*)webView scrollView:(UIScrollView*)scrollView { @@ -46,8 +47,8 @@ DCHECK(webView); DCHECK(scrollView); DCHECK([scrollView isDescendantOfView:webView]); - _webView.reset([webView retain]); - _scrollView.reset([scrollView retain]); + _webView = webView; + _scrollView = scrollView; } return self; } @@ -97,16 +98,6 @@ [self updateWebViewFrame]; } -#pragma mark Accessors - -- (UIScrollView*)scrollView { - return _scrollView.get(); -} - -- (UIView*)webView { - return _webView.get(); -} - #pragma mark Layout - (void)layoutSubviews {
diff --git a/ios/web/web_state/ui/crw_wk_script_message_router.h b/ios/web/web_state/ui/crw_wk_script_message_router.h index 6dfc20b..c24a25f0 100644 --- a/ios/web/web_state/ui/crw_wk_script_message_router.h +++ b/ios/web/web_state/ui/crw_wk_script_message_router.h
@@ -14,7 +14,8 @@ @interface CRWWKScriptMessageRouter : NSObject // Underlying WKUserContentController. -@property(nonatomic, readonly) WKUserContentController* userContentController; +@property(weak, nonatomic, readonly) + WKUserContentController* userContentController; // Designated initializer. |userContentController| must not be nil. - (instancetype)initWithUserContentController:
diff --git a/ios/web/web_state/ui/crw_wk_script_message_router.mm b/ios/web/web_state/ui/crw_wk_script_message_router.mm index ed13ddb..e1836872 100644 --- a/ios/web/web_state/ui/crw_wk_script_message_router.mm +++ b/ios/web/web_state/ui/crw_wk_script_message_router.mm
@@ -5,7 +5,10 @@ #import "ios/web/web_state/ui/crw_wk_script_message_router.h" #include "base/logging.h" -#import "base/mac/scoped_nsobject.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif @interface CRWWKScriptMessageRouter ()<WKScriptMessageHandler> @@ -18,16 +21,16 @@ @implementation CRWWKScriptMessageRouter { // Two level map of registed message handlers. Keys are message names and // values are more maps (where keys are web views and values are handlers). - base::scoped_nsobject<NSMutableDictionary> _handlers; + NSMutableDictionary* _handlers; // Wrapped WKUserContentController. - base::scoped_nsobject<WKUserContentController> _userContentController; + WKUserContentController* _userContentController; } #pragma mark - #pragma mark Interface - (WKUserContentController*)userContentController { - return _userContentController.get(); + return _userContentController; } - (instancetype)init { @@ -39,8 +42,8 @@ (WKUserContentController*)userContentController { DCHECK(userContentController); if ((self = [super init])) { - _handlers.reset([[NSMutableDictionary alloc] init]); - _userContentController.reset([userContentController retain]); + _handlers = [[NSMutableDictionary alloc] init]; + _userContentController = userContentController; } return self; } @@ -100,12 +103,10 @@ - (void)tryRemoveScriptMessageHandlerForName:(NSString*)messageName webView:(WKWebView*)webView { NSMapTable* webViewToHandlerMap = [_handlers objectForKey:messageName]; - id handler = [webViewToHandlerMap objectForKey:webView]; + NS_VALID_UNTIL_END_OF_SCOPE id handler = + [webViewToHandlerMap objectForKey:webView]; if (!handler) return; - // Extend the lifetime of |handler| so removeScriptMessageHandlerForName: can - // be called from inside of |handler|. - [[handler retain] autorelease]; if (webViewToHandlerMap.count == 1) { [_handlers removeObjectForKey:messageName]; [_userContentController removeScriptMessageHandlerForName:messageName];
diff --git a/ios/web/web_state/ui/web_view_js_utils.mm b/ios/web/web_state/ui/web_view_js_utils.mm index 1afe2d8..9a8f9ae 100644 --- a/ios/web/web_state/ui/web_view_js_utils.mm +++ b/ios/web/web_state/ui/web_view_js_utils.mm
@@ -9,11 +9,14 @@ #include "base/logging.h" #include "base/mac/foundation_util.h" -#import "base/mac/scoped_nsobject.h" #include "base/memory/ptr_util.h" #include "base/strings/sys_string_conversions.h" #include "base/values.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace { // Converts result of WKWebView script evaluation to base::Value, parsing @@ -30,7 +33,7 @@ return result; } - CFTypeID result_type = CFGetTypeID(wk_result); + CFTypeID result_type = CFGetTypeID((__bridge CFTypeRef)wk_result); if (result_type == CFStringGetTypeID()) { result.reset(new base::Value(base::SysNSStringToUTF16(wk_result))); DCHECK(result->IsType(base::Value::Type::STRING)); @@ -91,10 +94,10 @@ dispatch_async(dispatch_get_main_queue(), ^{ NSString* error_message = @"JS evaluation failed because there is no web view."; - base::scoped_nsobject<NSError> error([[NSError alloc] + NSError* error = [[NSError alloc] initWithDomain:kJSEvaluationErrorDomain code:JS_EVALUATION_ERROR_CODE_NO_WEB_VIEW - userInfo:@{NSLocalizedDescriptionKey : error_message}]); + userInfo:@{NSLocalizedDescriptionKey : error_message}]; completion_handler(nil, error); }); return;
diff --git a/ios/web/web_state/ui/wk_back_forward_list_item_holder.mm b/ios/web/web_state/ui/wk_back_forward_list_item_holder.mm index f74be49..aaec35d 100644 --- a/ios/web/web_state/ui/wk_back_forward_list_item_holder.mm +++ b/ios/web/web_state/ui/wk_back_forward_list_item_holder.mm
@@ -7,6 +7,10 @@ #include "base/memory/ptr_util.h" #import "ios/web/public/navigation_item.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace web { namespace {
diff --git a/ios/web/web_state/ui/wk_web_view_configuration_provider.mm b/ios/web/web_state/ui/wk_web_view_configuration_provider.mm index 9ba5899..2a4b988 100644 --- a/ios/web/web_state/ui/wk_web_view_configuration_provider.mm +++ b/ios/web/web_state/ui/wk_web_view_configuration_provider.mm
@@ -7,13 +7,16 @@ #import <Foundation/Foundation.h> #import <WebKit/WebKit.h> -#import "base/ios/weak_nsobject.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "ios/web/public/browser_state.h" #import "ios/web/web_state/js/page_script_util.h" #import "ios/web/web_state/ui/crw_wk_script_message_router.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace web { namespace { @@ -23,10 +26,10 @@ // Returns an autoreleased instance of WKUserScript to be added to // configuration's userContentController. WKUserScript* InternalGetEarlyPageScript(BrowserState* browser_state) { - return [[[WKUserScript alloc] + return [[WKUserScript alloc] initWithSource:GetEarlyPageScript(browser_state) injectionTime:WKUserScriptInjectionTimeAtDocumentStart - forMainFrameOnly:YES] autorelease]; + forMainFrameOnly:YES]; } } // namespace @@ -70,7 +73,7 @@ addUserScript:InternalGetEarlyPageScript(browser_state_)]; } // Prevent callers from changing the internals of configuration. - return [[configuration_ copy] autorelease]; + return [configuration_ copy]; } CRWWKScriptMessageRouter*
diff --git a/ios/web/web_state/web_controller_observer_bridge.mm b/ios/web/web_state/web_controller_observer_bridge.mm index 6fcf900..fd1dd2f9 100644 --- a/ios/web/web_state/web_controller_observer_bridge.mm +++ b/ios/web/web_state/web_controller_observer_bridge.mm
@@ -7,6 +7,10 @@ #include "base/logging.h" #import "ios/web/public/web_state/crw_web_controller_observer.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace web { WebControllerObserverBridge::WebControllerObserverBridge(
diff --git a/ios/web/web_state/web_view_internal_creation_util.mm b/ios/web/web_state/web_view_internal_creation_util.mm index 1174fc0..0fa0b81 100644 --- a/ios/web/web_state/web_view_internal_creation_util.mm +++ b/ios/web/web_state/web_view_internal_creation_util.mm
@@ -7,12 +7,15 @@ #import <objc/runtime.h> #include "base/logging.h" -#import "base/mac/scoped_nsobject.h" #include "base/strings/sys_string_conversions.h" #import "ios/web/public/web_client.h" #import "ios/web/web_state/ui/crw_context_menu_controller.h" #import "ios/web/web_state/ui/wk_web_view_configuration_provider.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace web { namespace { @@ -61,17 +64,17 @@ web_view.allowsLinkPreview = NO; if (context_menu_delegate) { - base::scoped_nsobject<CRWContextMenuController> context_menu_controller( - [[CRWContextMenuController alloc] - initWithWebView:web_view - injectionEvaluator:nil - delegate:context_menu_delegate]); - objc_setAssociatedObject(web_view, context_menu_controller.get(), - context_menu_controller.get(), + CRWContextMenuController* context_menu_controller = [ + [CRWContextMenuController alloc] initWithWebView:web_view + injectionEvaluator:nil + delegate:context_menu_delegate]; + void* associated_object_key = (__bridge void*)context_menu_controller; + objc_setAssociatedObject(web_view, associated_object_key, + context_menu_controller, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - return [web_view autorelease]; + return web_view; } WKWebView* BuildWKWebView(CGRect frame,
diff --git a/ios/web/web_state/wk_web_view_security_util.mm b/ios/web/web_state/wk_web_view_security_util.mm index 5b7e446..c4d1057 100644 --- a/ios/web/web_state/wk_web_view_security_util.mm +++ b/ios/web/web_state/wk_web_view_security_util.mm
@@ -10,6 +10,10 @@ #include "net/cert/x509_util_ios.h" #include "net/ssl/ssl_info.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace web { // These keys were determined by inspecting userInfo dict of an SSL error. @@ -50,10 +54,12 @@ return nullptr; std::vector<SecCertificateRef> intermediates; for (NSUInteger i = 1; i < certs.count; i++) { - intermediates.push_back(reinterpret_cast<SecCertificateRef>(certs[i])); + SecCertificateRef cert = (__bridge SecCertificateRef)certs[i]; + intermediates.push_back(cert); } + SecCertificateRef root_cert = (__bridge SecCertificateRef)certs[0]; return net::x509_util::CreateX509CertificateFromSecCertificate( - reinterpret_cast<SecCertificateRef>(certs[0]), intermediates); + reinterpret_cast<SecCertificateRef>(root_cert), intermediates); } scoped_refptr<net::X509Certificate> CreateCertFromTrust(SecTrustRef trust) { @@ -83,8 +89,8 @@ base::ScopedCFTypeRef<SecPolicyRef> policy( SecPolicyCreateSSL(TRUE, static_cast<CFStringRef>(host))); SecTrustRef ref_result = nullptr; - if (SecTrustCreateWithCertificates(certs, policy, &ref_result) == - errSecSuccess) { + if (SecTrustCreateWithCertificates((__bridge CFArrayRef)certs, policy, + &ref_result) == errSecSuccess) { scoped_result.reset(ref_result); } return scoped_result;
diff --git a/media/filters/BUILD.gn b/media/filters/BUILD.gn index 9197675..e8ff812e 100644 --- a/media/filters/BUILD.gn +++ b/media/filters/BUILD.gn
@@ -85,26 +85,6 @@ # See http://crbug.com/171009 configs += [ "//build/config/compiler:no_size_t_to_int_warning" ] - # TODO(a.suchit): Needs to create separate BUILD.gn file for video. - sources += [ - "//media/video/fake_video_encode_accelerator.cc", - "//media/video/fake_video_encode_accelerator.h", - "//media/video/gpu_memory_buffer_video_frame_pool.cc", - "//media/video/gpu_memory_buffer_video_frame_pool.h", - "//media/video/h264_poc.cc", - "//media/video/h264_poc.h", - "//media/video/half_float_maker.cc", - "//media/video/half_float_maker.h", - "//media/video/jpeg_decode_accelerator.cc", - "//media/video/jpeg_decode_accelerator.h", - "//media/video/picture.cc", - "//media/video/picture.h", - "//media/video/video_decode_accelerator.cc", - "//media/video/video_decode_accelerator.h", - "//media/video/video_encode_accelerator.cc", - "//media/video/video_encode_accelerator.h", - ] - configs += [ "//media:media_config", "//media:media_implementation", @@ -123,6 +103,7 @@ "//media/audio", "//media/cdm", "//media/muxers", + "//media/video", ] if (proprietary_codecs) {
diff --git a/media/video/BUILD.gn b/media/video/BUILD.gn new file mode 100644 index 0000000..8fb38ce --- /dev/null +++ b/media/video/BUILD.gn
@@ -0,0 +1,40 @@ +# Copyright 2017 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("//media/media_options.gni") + +source_set("video") { + visibility = [ "//media/filters" ] + + sources = [ + "//media/video/fake_video_encode_accelerator.cc", + "//media/video/fake_video_encode_accelerator.h", + "//media/video/gpu_memory_buffer_video_frame_pool.cc", + "//media/video/gpu_memory_buffer_video_frame_pool.h", + "//media/video/h264_poc.cc", + "//media/video/h264_poc.h", + "//media/video/half_float_maker.cc", + "//media/video/half_float_maker.h", + "//media/video/jpeg_decode_accelerator.cc", + "//media/video/jpeg_decode_accelerator.h", + "//media/video/picture.cc", + "//media/video/picture.h", + "//media/video/video_decode_accelerator.cc", + "//media/video/video_decode_accelerator.h", + "//media/video/video_encode_accelerator.cc", + "//media/video/video_encode_accelerator.h", + ] + + # TODO(wolenetz): Fix size_t to int truncation in win64. + # See http://crbug.com/171009 + configs += [ "//build/config/compiler:no_size_t_to_int_warning" ] + + deps = [ + "//gpu", + "//skia", + "//third_party/libyuv", + ] + + configs += [ "//media:media_implementation" ] +}
diff --git a/services/device/generic_sensor/platform_sensor.cc b/services/device/generic_sensor/platform_sensor.cc index cb78c97..0aef1ec6 100644 --- a/services/device/generic_sensor/platform_sensor.cc +++ b/services/device/generic_sensor/platform_sensor.cc
@@ -107,20 +107,20 @@ void PlatformSensor::NotifySensorReadingChanged() { for (auto& client : clients_) { - if (!client.IsNotificationSuspended()) + if (!client.IsSuspended()) client.OnSensorReadingChanged(); } } void PlatformSensor::NotifySensorError() { - for (auto& observer : clients_) - observer.OnSensorError(); + for (auto& client : clients_) + client.OnSensorError(); } bool PlatformSensor::UpdateSensorInternal(const ConfigMap& configurations) { const PlatformSensorConfiguration* optimal_configuration = nullptr; for (const auto& pair : configurations) { - if (pair.first->IsNotificationSuspended()) + if (pair.first->IsSuspended()) continue; const auto& conf_list = pair.second;
diff --git a/services/device/generic_sensor/platform_sensor.h b/services/device/generic_sensor/platform_sensor.h index 1e3847e..0255916 100644 --- a/services/device/generic_sensor/platform_sensor.h +++ b/services/device/generic_sensor/platform_sensor.h
@@ -31,7 +31,7 @@ public: virtual void OnSensorReadingChanged() = 0; virtual void OnSensorError() = 0; - virtual bool IsNotificationSuspended() = 0; + virtual bool IsSuspended() = 0; protected: virtual ~Client() {}
diff --git a/services/device/generic_sensor/platform_sensor_and_provider_unittest_linux.cc b/services/device/generic_sensor/platform_sensor_and_provider_unittest_linux.cc index 9e1b94cb..bcee24d 100644 --- a/services/device/generic_sensor/platform_sensor_and_provider_unittest_linux.cc +++ b/services/device/generic_sensor/platform_sensor_and_provider_unittest_linux.cc
@@ -114,7 +114,7 @@ if (sensor_) sensor_->AddClient(this); - ON_CALL(*this, IsNotificationSuspended()).WillByDefault(Return(false)); + ON_CALL(*this, IsSuspended()).WillByDefault(Return(false)); } ~MockPlatformSensorClient() override { @@ -125,7 +125,7 @@ // PlatformSensor::Client interface. MOCK_METHOD0(OnSensorReadingChanged, void()); MOCK_METHOD0(OnSensorError, void()); - MOCK_METHOD0(IsNotificationSuspended, bool()); + MOCK_METHOD0(IsSuspended, bool()); private: scoped_refptr<PlatformSensor> sensor_;
diff --git a/services/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc b/services/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc index 12a5d388..29f9072 100644 --- a/services/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc +++ b/services/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc
@@ -393,7 +393,7 @@ if (sensor_) sensor_->AddClient(this); - ON_CALL(*this, IsNotificationSuspended()).WillByDefault(Return(false)); + ON_CALL(*this, IsSuspended()).WillByDefault(Return(false)); } ~MockPlatformSensorClient() override { @@ -404,7 +404,7 @@ // PlatformSensor::Client interface. MOCK_METHOD0(OnSensorReadingChanged, void()); MOCK_METHOD0(OnSensorError, void()); - MOCK_METHOD0(IsNotificationSuspended, bool()); + MOCK_METHOD0(IsSuspended, bool()); private: scoped_refptr<PlatformSensor> sensor_;
diff --git a/services/device/generic_sensor/sensor_impl.cc b/services/device/generic_sensor/sensor_impl.cc index 013e25a..9c4a596 100644 --- a/services/device/generic_sensor/sensor_impl.cc +++ b/services/device/generic_sensor/sensor_impl.cc
@@ -12,8 +12,8 @@ SensorImpl::SensorImpl(scoped_refptr<PlatformSensor> sensor) : sensor_(std::move(sensor)), - suspended_(false), - suppress_on_change_events_count_(0) { + reading_notification_enabled_(true), + suspended_(false) { sensor_->AddClient(this); } @@ -30,10 +30,7 @@ AddConfigurationCallback callback) { // TODO(Mikhail): To avoid overflowing browser by repeated AddConfigs // (maybe limit the number of configs per client). - bool success = sensor_->StartListening(this, configuration); - if (success && configuration.suppress_on_change_events()) - ++suppress_on_change_events_count_; - std::move(callback).Run(success); + std::move(callback).Run(sensor_->StartListening(this, configuration)); } void SensorImpl::GetDefaultConfiguration( @@ -44,10 +41,7 @@ void SensorImpl::RemoveConfiguration( const PlatformSensorConfiguration& configuration, RemoveConfigurationCallback callback) { - bool success = sensor_->StopListening(this, configuration); - if (success && configuration.suppress_on_change_events()) - --suppress_on_change_events_count_; - std::move(callback).Run(success); + std::move(callback).Run(sensor_->StopListening(this, configuration)); } void SensorImpl::Suspend() { @@ -60,9 +54,13 @@ sensor_->UpdateSensor(); } +void SensorImpl::ConfigureReadingChangeNotifications(bool enabled) { + reading_notification_enabled_ = enabled; +} + void SensorImpl::OnSensorReadingChanged() { DCHECK(!suspended_); - if (client_ && suppress_on_change_events_count_ == 0) + if (client_ && reading_notification_enabled_) client_->SensorReadingChanged(); } @@ -72,7 +70,7 @@ client_->RaiseError(); } -bool SensorImpl::IsNotificationSuspended() { +bool SensorImpl::IsSuspended() { return suspended_; }
diff --git a/services/device/generic_sensor/sensor_impl.h b/services/device/generic_sensor/sensor_impl.h index d9606eed..6396e6c4 100644 --- a/services/device/generic_sensor/sensor_impl.h +++ b/services/device/generic_sensor/sensor_impl.h
@@ -30,20 +30,18 @@ RemoveConfigurationCallback callback) override; void Suspend() override; void Resume() override; + void ConfigureReadingChangeNotifications(bool enabled) override; // device::Sensor::Client implementation. void OnSensorReadingChanged() override; void OnSensorError() override; - bool IsNotificationSuspended() override; + bool IsSuspended() override; private: scoped_refptr<PlatformSensor> sensor_; mojom::SensorClientPtr client_; + bool reading_notification_enabled_; bool suspended_; - // The number of configurations that have |suppress_on_change_events_| - // flag set to true. If there is at least one configuration that sets this - // flag to true, SensorClient::SensorReadingChanged() is not called. - int suppress_on_change_events_count_; DISALLOW_COPY_AND_ASSIGN(SensorImpl); };
diff --git a/services/device/public/cpp/generic_sensor/platform_sensor_configuration.h b/services/device/public/cpp/generic_sensor/platform_sensor_configuration.h index be7ad030..baca2f03 100644 --- a/services/device/public/cpp/generic_sensor/platform_sensor_configuration.h +++ b/services/device/public/cpp/generic_sensor/platform_sensor_configuration.h
@@ -25,14 +25,8 @@ void set_frequency(double frequency); double frequency() const { return frequency_; } - void set_suppress_on_change_events(bool suppress_on_change_events) { - suppress_on_change_events_ = suppress_on_change_events; - } - bool suppress_on_change_events() const { return suppress_on_change_events_; } - private: double frequency_ = 1.0; // 1 Hz by default. - bool suppress_on_change_events_ = false; }; } // namespace device
diff --git a/services/device/public/cpp/generic_sensor/sensor_struct_traits.cc b/services/device/public/cpp/generic_sensor/sensor_struct_traits.cc index 37e84687..89c49e9 100644 --- a/services/device/public/cpp/generic_sensor/sensor_struct_traits.cc +++ b/services/device/public/cpp/generic_sensor/sensor_struct_traits.cc
@@ -19,7 +19,6 @@ } out->set_frequency(data.frequency()); - out->set_suppress_on_change_events(data.suppress_on_change_events()); return true; }
diff --git a/services/device/public/cpp/generic_sensor/sensor_struct_traits.h b/services/device/public/cpp/generic_sensor/sensor_struct_traits.h index 5f5c57e..e15f8ee0 100644 --- a/services/device/public/cpp/generic_sensor/sensor_struct_traits.h +++ b/services/device/public/cpp/generic_sensor/sensor_struct_traits.h
@@ -17,11 +17,6 @@ return input.frequency(); } - static bool suppress_on_change_events( - const device::PlatformSensorConfiguration& input) { - return input.suppress_on_change_events(); - } - static bool Read(device::mojom::SensorConfigurationDataView data, device::PlatformSensorConfiguration* out); };
diff --git a/services/device/public/interfaces/sensor.mojom b/services/device/public/interfaces/sensor.mojom index 03380a4..305ba19c 100644 --- a/services/device/public/interfaces/sensor.mojom +++ b/services/device/public/interfaces/sensor.mojom
@@ -46,15 +46,6 @@ // Requested frequency in Hz. double frequency; // TODO(shalamov): Add map<string, union> for sensor specific configuration. - - // For sensors with ON_CHANGE reporting mode: - // If at least one configuration sets this flag to true, - // SensorClient::SensorReadingChanged() signal is not sent to the client; - // otherwise it is. - // For sensors with CONTINUOUS reporting mode: - // This flag has no effect since SensorClient::SensorReadingChanged() is not - // sent to the client. - bool suppress_on_change_events = false; }; // Interface for controlling the Sensor. @@ -92,6 +83,11 @@ // Resumes previously suspended sensor reading changes notification and // activates all the previously added configurations for current instance. Resume(); + + // Disables or enables reading change notification for sensors with ON_CHANGE + // reporting mode, keeping all the previously added configurations active. + // Reading change notification is enabled by default. + ConfigureReadingChangeNotifications(bool enabled); }; // Interface that client of the Sensor interface must implement to observe
diff --git a/services/resource_coordinator/memory_instrumentation/coordinator_impl.cc b/services/resource_coordinator/memory_instrumentation/coordinator_impl.cc index 06990a1..9fa5daa 100644 --- a/services/resource_coordinator/memory_instrumentation/coordinator_impl.cc +++ b/services/resource_coordinator/memory_instrumentation/coordinator_impl.cc
@@ -196,21 +196,12 @@ it++; if (current->client != client_process) continue; - - switch (current->type) { - case QueuedMemoryDumpRequest::PendingResponse::Type::kProcessDump: { - OnProcessMemoryDumpResponse(client_process, false /* success */, - request->args.dump_guid, - nullptr /* process_memory_dump */); - break; - } - case QueuedMemoryDumpRequest::PendingResponse::Type::kOSDump: { - OSMemDumpMap results; - OnOSMemoryDumpResponse(client_process, false /* success */, results); - break; - } - } + RemovePendingResponse(client_process, current->type); + request->failed_memory_dump_count++; + // Regression test (crbug.com/742265). + DCHECK(GetCurrentRequest()); } + FinalizeGlobalMemoryDumpIfAllManagersReplied(); } size_t num_deleted = clients_.erase(client_process); DCHECK(num_deleted == 1); @@ -315,28 +306,14 @@ return; } - auto it = - request->pending_responses.find({client, ResponseType::kProcessDump}); + RemovePendingResponse(client, ResponseType::kProcessDump); - if (request->args.dump_guid != dump_guid || - it == request->pending_responses.end()) { - VLOG(1) << "Unexpected memory dump response, dump-id:" << dump_guid; - return; - } - - auto iter = clients_.find(client); - if (iter == clients_.end()) { + if (!clients_.count(client)) { VLOG(1) << "Received a memory dump response from an unregistered client"; return; } - if (process_memory_dump) { - request->responses[client].dump_ptr = std::move(process_memory_dump); - } else { - request->responses[client].dump_ptr = mojom::RawProcessMemoryDump::New(); - } - - request->pending_responses.erase(it); + request->responses[client].dump_ptr = std::move(process_memory_dump); if (!success) { request->failed_memory_dump_count++; @@ -357,23 +334,15 @@ return; } - auto it = request->pending_responses.find({client, ResponseType::kOSDump}); + RemovePendingResponse(client, ResponseType::kOSDump); - if (it == request->pending_responses.end()) { - VLOG(1) << "Unexpected memory dump response"; - return; - } - - auto iter = clients_.find(client); - if (iter == clients_.end()) { + if (!clients_.count(client)) { VLOG(1) << "Received a memory dump response from an unregistered client"; return; } request->responses[client].os_dumps = os_dumps; - request->pending_responses.erase(it); - if (!success) { request->failed_memory_dump_count++; VLOG(1) << "RequestGlobalMemoryDump() FAIL: NACK from client process"; @@ -382,6 +351,22 @@ FinalizeGlobalMemoryDumpIfAllManagersReplied(); } +void CoordinatorImpl::RemovePendingResponse( + mojom::ClientProcess* client, + QueuedMemoryDumpRequest::PendingResponse::Type type) { + QueuedMemoryDumpRequest* request = GetCurrentRequest(); + if (request == nullptr) { + NOTREACHED() << "No current dump request."; + return; + } + auto it = request->pending_responses.find({client, type}); + if (it == request->pending_responses.end()) { + VLOG(1) << "Unexpected memory dump response"; + return; + } + request->pending_responses.erase(it); +} + void CoordinatorImpl::FinalizeGlobalMemoryDumpIfAllManagersReplied() { DCHECK(!queued_memory_dump_requests_.empty()); QueuedMemoryDumpRequest* request = &queued_memory_dump_requests_.front(); @@ -398,17 +383,22 @@ std::map<base::ProcessId, OSMemDump> os_dumps; for (auto& response : request->responses) { const base::ProcessId pid = response.second.process_id; - const OSMemDump dump = response.second.dump_ptr->os_dump; + const mojom::RawProcessMemoryDumpPtr& dump_ptr = response.second.dump_ptr; + + // The dump might be nullptr if the client crashed / disconnected before + // replying. + if (!dump_ptr) + continue; // TODO(hjd): We should have a better way to tell if os_dump is filled. // TODO(hjd): Remove this if when we collect OS dumps separately. - if (dump.resident_set_kb > 0) { + if (dump_ptr->os_dump.resident_set_kb > 0) { DCHECK_EQ(0u, os_dumps.count(pid)); - os_dumps[pid] = dump; + os_dumps[pid] = dump_ptr->os_dump; } // TODO(hjd): Remove this for loop when we collect OS dumps separately. - for (auto& extra : response.second.dump_ptr->extra_processes_dumps) { + for (auto& extra : dump_ptr->extra_processes_dumps) { const base::ProcessId extra_pid = extra.first; const OSMemDump extra_dump = extra.second; DCHECK_EQ(0u, os_dumps.count(extra_pid)); @@ -426,10 +416,15 @@ std::map<base::ProcessId, mojom::ProcessMemoryDumpPtr> finalized_pmds; for (auto& response : request->responses) { const base::ProcessId pid = response.second.process_id; - mojom::ProcessMemoryDumpPtr& pmd = finalized_pmds[pid]; - if (!pmd) - pmd = mojom::ProcessMemoryDump::New(); + DCHECK(!finalized_pmds.count(pid)); + // The dump might be nullptr if the client crashed / disconnected before + // replying. + if (!response.second.dump_ptr) + continue; + + mojom::ProcessMemoryDumpPtr& pmd = finalized_pmds[pid]; + pmd = mojom::ProcessMemoryDump::New(); pmd->process_type = response.second.process_type; pmd->chrome_dump = response.second.dump_ptr->chrome_dump; pmd->os_dump = CreatePublicOSDump(os_dumps[pid]);
diff --git a/services/resource_coordinator/memory_instrumentation/coordinator_impl.h b/services/resource_coordinator/memory_instrumentation/coordinator_impl.h index 2d31868..ca30b92d 100644 --- a/services/resource_coordinator/memory_instrumentation/coordinator_impl.h +++ b/services/resource_coordinator/memory_instrumentation/coordinator_impl.h
@@ -129,6 +129,8 @@ void OnOSMemoryDumpResponse(mojom::ClientProcess*, bool success, const OSMemDumpMap&); + void RemovePendingResponse(mojom::ClientProcess*, + QueuedMemoryDumpRequest::PendingResponse::Type); void PerformNextQueuedGlobalMemoryDump(); void FinalizeGlobalMemoryDumpIfAllManagersReplied();
diff --git a/services/resource_coordinator/memory_instrumentation/coordinator_impl_unittest.cc b/services/resource_coordinator/memory_instrumentation/coordinator_impl_unittest.cc index 98b648428..deee3c75 100644 --- a/services/resource_coordinator/memory_instrumentation/coordinator_impl_unittest.cc +++ b/services/resource_coordinator/memory_instrumentation/coordinator_impl_unittest.cc
@@ -230,6 +230,37 @@ run_loop.Run(); } +// Like ClientCrashDuringGlobalDump but covers the case of having only one +// client. Regression testing for crbug.com/742265. +TEST_F(CoordinatorImplTest, SingleClientCrashDuringGlobalDump) { + base::RunLoop run_loop; + + base::trace_event::MemoryDumpRequestArgs args = { + 0, base::trace_event::MemoryDumpType::EXPLICITLY_TRIGGERED, + base::trace_event::MemoryDumpLevelOfDetail::DETAILED}; + + auto client_process = base::MakeUnique<NiceMock<MockClientProcess>>( + this, 1, mojom::ProcessType::BROWSER); + + ON_CALL(*client_process, RequestProcessMemoryDump(_, _)) + .WillByDefault( + Invoke([&client_process]( + const MemoryDumpRequestArgs& args, + const MockClientProcess::RequestProcessMemoryDumpCallback& + callback) { + // The dtor here will cause mojo to post an UnregisterClient call to + // the coordinator. + client_process.reset(); + callback.Run(true, args.dump_guid, nullptr); + })); + + MockGlobalMemoryDumpCallback callback; + EXPECT_CALL(callback, OnCall(false, Ne(0u), NotNull())) + .WillOnce(RunClosure(run_loop.QuitClosure())); + RequestGlobalMemoryDump(args, callback.Get()); + run_loop.Run(); +} + TEST_F(CoordinatorImplTest, GlobalMemoryDumpStruct) { base::RunLoop run_loop;
diff --git a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json index 5dc972b..cbc1417 100644 --- a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json +++ b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json
@@ -101139,11 +101139,6 @@ {} ] ], - "payment-request/payment-request-in-iframe-expected.txt": [ - [ - {} - ] - ], "payment-request/payment-request-onshippingaddresschange-attribute.https-expected.txt": [ [ {} @@ -150900,12 +150895,6 @@ {} ] ], - "payment-request/payment-request-in-iframe.html": [ - [ - "/payment-request/payment-request-in-iframe.html", - {} - ] - ], "payment-request/payment-request-onshippingaddresschange-attribute.https.html": [ [ "/payment-request/payment-request-onshippingaddresschange-attribute.https.html", @@ -222698,11 +222687,11 @@ "testharness" ], "encoding/api-invalid-label.html": [ - "03709b6005a96c42a80c4db5a71874fb3d0c3f6f", + "38912a0e00f769ff9c116a5871b3691d059a4ef9", "testharness" ], "encoding/api-replacement-encodings.html": [ - "6a7d970c4228c341332acc2779fb94416c7d380a", + "ea956ff139f386abf52226d981dbb5ec0e3f2a38", "testharness" ], "encoding/api-surrogates-utf8.html": [ @@ -223474,7 +223463,7 @@ "support" ], "encoding/resources/encodings.js": [ - "27b7c95700ec1b5bfa45257574a01cf9ff30ca96", + "66626403db30a2778878a187df339b0bfd767495", "support" ], "encoding/textdecoder-byte-order-marks.html": [ @@ -227790,11 +227779,11 @@ "testharness" ], "html/browsers/origin/cross-origin-objects/cross-origin-objects.html": [ - "02e290c300057b9520390e55833194908d74ca76", + "ed130a2bd50ae3f0571c832b28b438e67871aa7c", "testharness" ], "html/browsers/origin/cross-origin-objects/frame.html": [ - "dc9cd0af288e67202b3db551516613a2707201c5", + "7f982fe347ac7fbc14e853d14a2535685a970395", "support" ], "html/browsers/origin/cross-origin-objects/win-documentdomain.sub.html": [ @@ -251361,14 +251350,6 @@ "a90cf1e385cfee1c2090f4144e08b7cb051366d5", "testharness" ], - "payment-request/payment-request-in-iframe-expected.txt": [ - "40145219ed132de43c4b06a898bdc8568ef079ac", - "support" - ], - "payment-request/payment-request-in-iframe.html": [ - "0a7cd9d70a64331eef4277db7e5ee91934b50b11", - "testharness" - ], "payment-request/payment-request-onshippingaddresschange-attribute.https-expected.txt": [ "e47a64b12833665e0be8cc2962021c90160fb9d6", "support" @@ -251402,7 +251383,7 @@ "support" ], "payment-request/payment-request-update-event-constructor.http.html": [ - "6ddbcd3b5847492daf0c2e913369bc861e4d006a", + "017f1f1aca43171083833ddb27ff66e39902e85d", "testharness" ], "payment-request/payment-request-update-event-constructor.https-expected.txt": [
diff --git a/third_party/WebKit/LayoutTests/external/wpt/encoding/api-invalid-label.html b/third_party/WebKit/LayoutTests/external/wpt/encoding/api-invalid-label.html index f15c184a..3c7486fa 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/encoding/api-invalid-label.html +++ b/third_party/WebKit/LayoutTests/external/wpt/encoding/api-invalid-label.html
@@ -8,9 +8,7 @@ var tests = ["invalid-invalidLabel"]; setup(function() { encodings_table.forEach(function(section) { - section.encodings.filter(function(encoding) { - return encoding.name !== 'replacement'; - }).forEach(function(encoding) { + section.encodings.forEach(function(encoding) { encoding.labels.forEach(function(label) { ["\u0000", "\u000b", "\u00a0", "\u2028", "\u2029"].forEach(function(ws) { tests.push(ws + label);
diff --git a/third_party/WebKit/LayoutTests/external/wpt/encoding/api-replacement-encodings.html b/third_party/WebKit/LayoutTests/external/wpt/encoding/api-replacement-encodings.html index 2dffd72e..6340263 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/encoding/api-replacement-encodings.html +++ b/third_party/WebKit/LayoutTests/external/wpt/encoding/api-replacement-encodings.html
@@ -5,10 +5,6 @@ <script src="resources/encodings.js"></script> <script> -test(function() { - assert_throws(new RangeError(), function() { new TextDecoder('replacement'); }); -}, 'The "replacement" label should not be a known encoding.'); - encodings_table.forEach(function(section) { section.encodings.filter(function(encoding) { return encoding.name === 'replacement';
diff --git a/third_party/WebKit/LayoutTests/external/wpt/encoding/resources/encodings.js b/third_party/WebKit/LayoutTests/external/wpt/encoding/resources/encodings.js index fabbbd1..c7a2a5a 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/encoding/resources/encodings.js +++ b/third_party/WebKit/LayoutTests/external/wpt/encoding/resources/encodings.js
@@ -431,7 +431,8 @@ "hz-gb-2312", "iso-2022-cn", "iso-2022-cn-ext", - "iso-2022-kr" + "iso-2022-kr", + "replacement" ], "name": "replacement" },
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/browsers/origin/cross-origin-objects/cross-origin-objects.html b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/origin/cross-origin-objects/cross-origin-objects.html index 442620b..9b09388 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/html/browsers/origin/cross-origin-objects/cross-origin-objects.html +++ b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/origin/cross-origin-objects/cross-origin-objects.html
@@ -187,7 +187,7 @@ var isSymbol = (typeof(propName) == "symbol"); propName = String(propName); assert_true(isObject(desc), "property descriptor for " + propName + " should exist"); - assert_equals(desc.enumerable, false, "property descriptor for " + propName + " should be non-enumerable"); + assert_equals(desc.enumerable, true, "property descriptor for " + propName + " should be enumerable"); assert_equals(desc.configurable, true, "property descriptor for " + propName + " should be configurable"); if (isSymbol) { assert_true("value" in desc, @@ -274,9 +274,15 @@ assert_array_equals(Object.getOwnPropertyNames(C).sort(), whitelistedWindowPropNames, "Object.getOwnPropertyNames() gives the right answer for cross-origin Window"); + assert_array_equals(Object.keys(C).sort(), + whitelistedWindowPropNames, + "Object.keys() gives the right answer for cross-origin Window"); assert_array_equals(Object.getOwnPropertyNames(C.location).sort(), whitelistedLocationPropNames, "Object.getOwnPropertyNames() gives the right answer for cross-origin Location"); + assert_array_equals(Object.keys(C.location).sort(), + whitelistedLocationPropNames, + "Object.keys() gives the right answer for cross-origin Location"); }, "[[OwnPropertyKeys]] should return all properties from cross-origin objects"); addTest(function() {
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/browsers/origin/cross-origin-objects/frame.html b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/origin/cross-origin-objects/frame.html index 0a7769d..341da6a 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/html/browsers/origin/cross-origin-objects/frame.html +++ b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/origin/cross-origin-objects/frame.html
@@ -37,6 +37,6 @@ <body> <!-- Two subframes to give us some indexed properties --> <iframe></iframe> - <iframe></iframe> + <iframe name=donotleakme></iframe><!-- "donotleakme" is excluded as cross-origin named property due to [[HideFromKeys]] --> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-in-iframe-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-in-iframe-expected.txt deleted file mode 100644 index d4aa504..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-in-iframe-expected.txt +++ /dev/null
@@ -1,7 +0,0 @@ -This is a testharness.js-based test. -FAIL Test for PaymentRequest in an iframe (see also -https://github.com/w3c/browser-payment-api/issues/2) assert_throws: If the browsing context of the script calling the constructor is not a top-level browsing context, then throw a SecurityError. function "function () { - new PaymentRequest([{supportedMethods: 'foo'}], {total: {label: 'label', amount: {currency: 'USD', value: '5.00'}}}); - }" threw object "TypeError: Failed to construct 'PaymentRequest': The provided value cannot be converted to a sequence." ("TypeError") expected object "[object Object]" ("SecurityError") -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-in-iframe.html b/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-in-iframe.html deleted file mode 100644 index 8ee6928c..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-in-iframe.html +++ /dev/null
@@ -1,18 +0,0 @@ -<!DOCTYPE html> -<!-- Copyright © 2016 Chromium authors and World Wide Web Consortium, (Massachusetts Institute of Technology, ERCIM, Keio University, Beihang). --> -<meta charset="utf-8"> -<title>Test for PaymentRequest in an iframe (see also -https://github.com/w3c/browser-payment-api/issues/2)</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<iframe srcdoc=" -<!DOCTYPE html> -<meta charset='utf-8'> -<script> -window.top.test(function() { - window.top.assert_throws({name: 'SecurityError'}, function() { - new PaymentRequest([{supportedMethods: 'foo'}], {total: {label: 'label', amount: {currency: 'USD', value: '5.00'}}}); - }, 'If the browsing context of the script calling the constructor is not a top-level browsing context, then throw a SecurityError.'); -}); -</script> -"></iframe>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-update-event-constructor.http-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-update-event-constructor.http-expected.txt deleted file mode 100644 index d3f21b34..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-update-event-constructor.http-expected.txt +++ /dev/null
@@ -1,6 +0,0 @@ -This is a testharness.js-based test. -FAIL PaymentRequestUpdateEvent constructor throws in a non-secure context assert_throws: function "() => { - new PaymentRequestUpdateEvent("test"); - }" did not throw -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-update-event-constructor.http.html b/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-update-event-constructor.http.html index 685eed6..db7765f7 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-update-event-constructor.http.html +++ b/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-update-event-constructor.http.html
@@ -1,14 +1,12 @@ <!DOCTYPE html> <!-- Copyright © 2017 Chromium authors and World Wide Web Consortium, (Massachusetts Institute of Technology, ERCIM, Keio University, Beihang). --> <meta charset="utf-8"> -<title>Test for PaymentRequestUpdateEvent Constructor</title> -<link rel="help" href="https://w3c.github.io/browser-payment-api/#constructor"> +<title>Test for PaymentRequestUpdateEvent Constructor (insecure)</title> +<link rel="help" href="https://w3c.github.io/browser-payment-api/#paymentrequestupdateevent-interface"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script> test(() => { - assert_throws("SecurityError", () => { - new PaymentRequestUpdateEvent("test"); - }); -}, "PaymentRequestUpdateEvent constructor throws in a non-secure context"); + assert_false("PaymentRequestUpdateEvent" in Window); +}, "PaymentRequestUpdateEvent constructor must not be exposed in insecure context"); </script>
diff --git a/third_party/WebKit/Source/core/animation/AnimationTestHelper.h b/third_party/WebKit/Source/core/animation/AnimationTestHelper.h index 59ee07c..e5d833fd 100644 --- a/third_party/WebKit/Source/core/animation/AnimationTestHelper.h +++ b/third_party/WebKit/Source/core/animation/AnimationTestHelper.h
@@ -5,6 +5,8 @@ #ifndef AnimationTestHelper_h #define AnimationTestHelper_h +#include "core/animation/InterpolableValue.h" +#include "core/animation/LegacyStyleInterpolation.h" #include "platform/wtf/text/StringView.h" #include "platform/wtf/text/WTFString.h" #include "v8/include/v8.h" @@ -20,6 +22,23 @@ const StringView& name, double value); +class SampleTestInterpolation : public LegacyStyleInterpolation { + public: + static PassRefPtr<LegacyStyleInterpolation> Create( + std::unique_ptr<InterpolableValue> start, + std::unique_ptr<InterpolableValue> end) { + return AdoptRef( + new SampleTestInterpolation(std::move(start), std::move(end))); + } + + private: + SampleTestInterpolation(std::unique_ptr<InterpolableValue> start, + std::unique_ptr<InterpolableValue> end) + : LegacyStyleInterpolation(std::move(start), + std::move(end), + CSSPropertyBackgroundColor) {} +}; + } // namespace blink #endif // AnimationTestHelper_h
diff --git a/third_party/WebKit/Source/core/animation/CompositorMutatorImpl.h b/third_party/WebKit/Source/core/animation/CompositorMutatorImpl.h index 968c859..f2e6faaa 100644 --- a/third_party/WebKit/Source/core/animation/CompositorMutatorImpl.h +++ b/third_party/WebKit/Source/core/animation/CompositorMutatorImpl.h
@@ -6,6 +6,7 @@ #define CompositorMutatorImpl_h #include <memory> +#include "core/animation/CompositorAnimator.h" #include "core/animation/CustomCompositorAnimationManager.h" #include "platform/graphics/CompositorMutator.h" #include "platform/heap/Handle.h" @@ -14,7 +15,6 @@ namespace blink { -class CompositorAnimator; class CompositorMutatorClient; // Fans out requests from the compositor to all of the registered
diff --git a/third_party/WebKit/Source/core/animation/InterpolableValueTest.cpp b/third_party/WebKit/Source/core/animation/InterpolableValueTest.cpp index 7298e463..bb2cee5 100644 --- a/third_party/WebKit/Source/core/animation/InterpolableValueTest.cpp +++ b/third_party/WebKit/Source/core/animation/InterpolableValueTest.cpp
@@ -2,34 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> +#include "core/animation/AnimationTestHelper.h" #include "core/animation/InterpolableValue.h" - #include "core/animation/LegacyStyleInterpolation.h" #include "testing/gtest/include/gtest/gtest.h" -#include <memory> namespace blink { -namespace { - -class SampleInterpolation : public LegacyStyleInterpolation { - public: - static PassRefPtr<LegacyStyleInterpolation> Create( - std::unique_ptr<InterpolableValue> start, - std::unique_ptr<InterpolableValue> end) { - return AdoptRef(new SampleInterpolation(std::move(start), std::move(end))); - } - - private: - SampleInterpolation(std::unique_ptr<InterpolableValue> start, - std::unique_ptr<InterpolableValue> end) - : LegacyStyleInterpolation(std::move(start), - std::move(end), - CSSPropertyBackgroundColor) {} -}; - -} // namespace - class AnimationInterpolableValueTest : public ::testing::Test { protected: InterpolableValue* InterpolationValue( @@ -38,7 +18,7 @@ } double InterpolateNumbers(double a, double b, double progress) { - RefPtr<LegacyStyleInterpolation> i = SampleInterpolation::Create( + RefPtr<LegacyStyleInterpolation> i = SampleTestInterpolation::Create( InterpolableNumber::Create(a), InterpolableNumber::Create(b)); i->Interpolate(0, progress); return ToInterpolableNumber(InterpolationValue(*i.Get()))->Value(); @@ -55,7 +35,7 @@ std::unique_ptr<InterpolableList> list_b, double progress) { RefPtr<LegacyStyleInterpolation> i = - SampleInterpolation::Create(std::move(list_a), std::move(list_b)); + SampleTestInterpolation::Create(std::move(list_a), std::move(list_b)); i->Interpolate(0, progress); return i; }
diff --git a/third_party/WebKit/Source/core/animation/InterpolationEffectTest.cpp b/third_party/WebKit/Source/core/animation/InterpolationEffectTest.cpp index eacaf49..7bc0ab0 100644 --- a/third_party/WebKit/Source/core/animation/InterpolationEffectTest.cpp +++ b/third_party/WebKit/Source/core/animation/InterpolationEffectTest.cpp
@@ -2,33 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> +#include "core/animation/AnimationTestHelper.h" #include "core/animation/InterpolationEffect.h" - #include "core/animation/LegacyStyleInterpolation.h" #include "testing/gtest/include/gtest/gtest.h" -#include <memory> namespace blink { namespace { -class SampleInterpolation : public LegacyStyleInterpolation { - public: - static PassRefPtr<LegacyStyleInterpolation> Create( - std::unique_ptr<InterpolableValue> start, - std::unique_ptr<InterpolableValue> end) { - return AdoptRef(new SampleInterpolation(std::move(start), std::move(end))); - } - - private: - SampleInterpolation(std::unique_ptr<InterpolableValue> start, - std::unique_ptr<InterpolableValue> end) - : LegacyStyleInterpolation(std::move(start), - std::move(end), - CSSPropertyBackgroundColor) {} -}; - -const double kDuration = 1.0; +const double kInterpolationTestDuration = 1.0; } // namespace @@ -49,31 +33,31 @@ TEST_F(AnimationInterpolationEffectTest, SingleInterpolation) { InterpolationEffect interpolation_effect; interpolation_effect.AddInterpolation( - SampleInterpolation::Create(InterpolableNumber::Create(0), - InterpolableNumber::Create(10)), + SampleTestInterpolation::Create(InterpolableNumber::Create(0), + InterpolableNumber::Create(10)), RefPtr<TimingFunction>(), 0, 1, -1, 2); Vector<RefPtr<Interpolation>> active_interpolations; - interpolation_effect.GetActiveInterpolations(-2, kDuration, + interpolation_effect.GetActiveInterpolations(-2, kInterpolationTestDuration, active_interpolations); EXPECT_EQ(0ul, active_interpolations.size()); - interpolation_effect.GetActiveInterpolations(-0.5, kDuration, + interpolation_effect.GetActiveInterpolations(-0.5, kInterpolationTestDuration, active_interpolations); EXPECT_EQ(1ul, active_interpolations.size()); EXPECT_EQ(-5, GetInterpolableNumber(active_interpolations.at(0))); - interpolation_effect.GetActiveInterpolations(0.5, kDuration, + interpolation_effect.GetActiveInterpolations(0.5, kInterpolationTestDuration, active_interpolations); EXPECT_EQ(1ul, active_interpolations.size()); EXPECT_FLOAT_EQ(5, GetInterpolableNumber(active_interpolations.at(0))); - interpolation_effect.GetActiveInterpolations(1.5, kDuration, + interpolation_effect.GetActiveInterpolations(1.5, kInterpolationTestDuration, active_interpolations); EXPECT_EQ(1ul, active_interpolations.size()); EXPECT_FLOAT_EQ(15, GetInterpolableNumber(active_interpolations.at(0))); - interpolation_effect.GetActiveInterpolations(3, kDuration, + interpolation_effect.GetActiveInterpolations(3, kInterpolationTestDuration, active_interpolations); EXPECT_EQ(0ul, active_interpolations.size()); } @@ -81,56 +65,56 @@ TEST_F(AnimationInterpolationEffectTest, MultipleInterpolations) { InterpolationEffect interpolation_effect; interpolation_effect.AddInterpolation( - SampleInterpolation::Create(InterpolableNumber::Create(10), - InterpolableNumber::Create(15)), + SampleTestInterpolation::Create(InterpolableNumber::Create(10), + InterpolableNumber::Create(15)), RefPtr<TimingFunction>(), 1, 2, 1, 3); interpolation_effect.AddInterpolation( - SampleInterpolation::Create(InterpolableNumber::Create(0), - InterpolableNumber::Create(1)), + SampleTestInterpolation::Create(InterpolableNumber::Create(0), + InterpolableNumber::Create(1)), LinearTimingFunction::Shared(), 0, 1, 0, 1); interpolation_effect.AddInterpolation( - SampleInterpolation::Create(InterpolableNumber::Create(1), - InterpolableNumber::Create(6)), + SampleTestInterpolation::Create(InterpolableNumber::Create(1), + InterpolableNumber::Create(6)), CubicBezierTimingFunction::Preset( CubicBezierTimingFunction::EaseType::EASE), 0.5, 1.5, 0.5, 1.5); Vector<RefPtr<Interpolation>> active_interpolations; - interpolation_effect.GetActiveInterpolations(-0.5, kDuration, + interpolation_effect.GetActiveInterpolations(-0.5, kInterpolationTestDuration, active_interpolations); EXPECT_EQ(0ul, active_interpolations.size()); - interpolation_effect.GetActiveInterpolations(0, kDuration, + interpolation_effect.GetActiveInterpolations(0, kInterpolationTestDuration, active_interpolations); EXPECT_EQ(1ul, active_interpolations.size()); EXPECT_FLOAT_EQ(0, GetInterpolableNumber(active_interpolations.at(0))); - interpolation_effect.GetActiveInterpolations(0.5, kDuration, + interpolation_effect.GetActiveInterpolations(0.5, kInterpolationTestDuration, active_interpolations); EXPECT_EQ(2ul, active_interpolations.size()); EXPECT_FLOAT_EQ(0.5f, GetInterpolableNumber(active_interpolations.at(0))); EXPECT_FLOAT_EQ(1, GetInterpolableNumber(active_interpolations.at(1))); - interpolation_effect.GetActiveInterpolations(1, kDuration, + interpolation_effect.GetActiveInterpolations(1, kInterpolationTestDuration, active_interpolations); EXPECT_EQ(2ul, active_interpolations.size()); EXPECT_FLOAT_EQ(10, GetInterpolableNumber(active_interpolations.at(0))); EXPECT_FLOAT_EQ(5.0282884f, GetInterpolableNumber(active_interpolations.at(1))); - interpolation_effect.GetActiveInterpolations(1, kDuration * 1000, - active_interpolations); + interpolation_effect.GetActiveInterpolations( + 1, kInterpolationTestDuration * 1000, active_interpolations); EXPECT_EQ(2ul, active_interpolations.size()); EXPECT_FLOAT_EQ(10, GetInterpolableNumber(active_interpolations.at(0))); EXPECT_FLOAT_EQ(5.0120168f, GetInterpolableNumber(active_interpolations.at(1))); - interpolation_effect.GetActiveInterpolations(1.5, kDuration, + interpolation_effect.GetActiveInterpolations(1.5, kInterpolationTestDuration, active_interpolations); EXPECT_EQ(1ul, active_interpolations.size()); EXPECT_FLOAT_EQ(12.5f, GetInterpolableNumber(active_interpolations.at(0))); - interpolation_effect.GetActiveInterpolations(2, kDuration, + interpolation_effect.GetActiveInterpolations(2, kInterpolationTestDuration, active_interpolations); EXPECT_EQ(1ul, active_interpolations.size()); EXPECT_FLOAT_EQ(15, GetInterpolableNumber(active_interpolations.at(0)));
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.cpp b/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.cpp index 952ec18..ba245e06 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.cpp +++ b/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.cpp
@@ -32,7 +32,7 @@ return new CSSMatrixComponent(matrix, options.is2D() || matrix->is2D()); } -DOMMatrix* CSSMatrixComponent::AsMatrix() const { +const DOMMatrix* CSSMatrixComponent::AsMatrix() const { if (is2D() && !matrix_->is2D()) return To2DMatrix(matrix_);
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.h b/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.h index ec92f978..a4b10093 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.h
@@ -37,7 +37,7 @@ // Internal methods - from CSSTransformComponent. TransformComponentType GetType() const final { return kMatrixType; } - DOMMatrix* AsMatrix() const final; + const DOMMatrix* AsMatrix() const final; CSSFunctionValue* ToCSSValue() const final; DEFINE_INLINE_VIRTUAL_TRACE() {
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSPerspective.cpp b/third_party/WebKit/Source/core/css/cssom/CSSPerspective.cpp index aa9df3b..2a9ffed8 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSPerspective.cpp +++ b/third_party/WebKit/Source/core/css/cssom/CSSPerspective.cpp
@@ -51,7 +51,7 @@ return new CSSPerspective(length); } -DOMMatrix* CSSPerspective::AsMatrix() const { +const DOMMatrix* CSSPerspective::AsMatrix() const { if (!length_->IsCalculated() && ToCSSUnitValue(length_)->value() < 0) { // Negative values are invalid. // https://github.com/w3c/css-houdini-drafts/issues/420
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSPerspective.h b/third_party/WebKit/Source/core/css/cssom/CSSPerspective.h index c344fda8..a0f9183 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSPerspective.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSPerspective.h
@@ -39,7 +39,7 @@ // Internal methods - from CSSTransformComponent. TransformComponentType GetType() const final { return kPerspectiveType; } - DOMMatrix* AsMatrix() const final; + const DOMMatrix* AsMatrix() const final; CSSFunctionValue* ToCSSValue() const final; DEFINE_INLINE_VIRTUAL_TRACE() {
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSRotation.cpp b/third_party/WebKit/Source/core/css/cssom/CSSRotation.cpp index 32d606b..1395b2a 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSRotation.cpp +++ b/third_party/WebKit/Source/core/css/cssom/CSSRotation.cpp
@@ -126,7 +126,7 @@ angle_ = angle; } -DOMMatrix* CSSRotation::AsMatrix() const { +const DOMMatrix* CSSRotation::AsMatrix() const { DOMMatrix* matrix = DOMMatrix::Create(); CSSUnitValue* angle = angle_->to(CSSPrimitiveValue::UnitType::kDegrees); if (is2D()) {
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSRotation.h b/third_party/WebKit/Source/core/css/cssom/CSSRotation.h index 6aa70d2..10b1ad4 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSRotation.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSRotation.h
@@ -49,7 +49,7 @@ // Internal methods - from CSSTransformComponent. TransformComponentType GetType() const final { return kRotationType; } - DOMMatrix* AsMatrix() const final; + const DOMMatrix* AsMatrix() const final; CSSFunctionValue* ToCSSValue() const final; DEFINE_INLINE_VIRTUAL_TRACE() {
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSScale.h b/third_party/WebKit/Source/core/css/cssom/CSSScale.h index 3284af0f..2623007 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSScale.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSScale.h
@@ -39,7 +39,7 @@ // Internal methods - from CSSTransformComponent. TransformComponentType GetType() const final { return kScaleType; } - DOMMatrix* AsMatrix() const final { + const DOMMatrix* AsMatrix() const final { DOMMatrix* result = DOMMatrix::Create(); return result->scaleSelf(x_, y_, z_); }
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSSkew.cpp b/third_party/WebKit/Source/core/css/cssom/CSSSkew.cpp index 85b993a..b8d0c62 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSSkew.cpp +++ b/third_party/WebKit/Source/core/css/cssom/CSSSkew.cpp
@@ -74,7 +74,7 @@ } } -DOMMatrix* CSSSkew::AsMatrix() const { +const DOMMatrix* CSSSkew::AsMatrix() const { CSSUnitValue* ax = ax_->to(CSSPrimitiveValue::UnitType::kRadians); CSSUnitValue* ay = ay_->to(CSSPrimitiveValue::UnitType::kRadians); DCHECK(ax);
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSSkew.h b/third_party/WebKit/Source/core/css/cssom/CSSSkew.h index bf8a4d1b..307b5a2 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSSkew.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSSkew.h
@@ -41,7 +41,7 @@ void setIs2D(bool is2D) final {} // Internal methods - from CSSTransformComponent. - DOMMatrix* AsMatrix() const override; + const DOMMatrix* AsMatrix() const override; TransformComponentType GetType() const override { return kSkewType; } CSSFunctionValue* ToCSSValue() const override;
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSTransformComponent.h b/third_party/WebKit/Source/core/css/cssom/CSSTransformComponent.h index 0f258c1..172db18 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSTransformComponent.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSTransformComponent.h
@@ -52,7 +52,7 @@ // Internal methods. virtual TransformComponentType GetType() const = 0; virtual CSSFunctionValue* ToCSSValue() const = 0; - virtual DOMMatrix* AsMatrix() const = 0; + virtual const DOMMatrix* AsMatrix() const = 0; DEFINE_INLINE_VIRTUAL_TRACE() {}
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSTransformValue.cpp b/third_party/WebKit/Source/core/css/cssom/CSSTransformValue.cpp index e73f121..2742564 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSTransformValue.cpp +++ b/third_party/WebKit/Source/core/css/cssom/CSSTransformValue.cpp
@@ -38,9 +38,9 @@ DOMMatrix* CSSTransformValue::toMatrix() const { DOMMatrix* matrix = DOMMatrix::Create(); for (size_t i = 0; i < transform_components_.size(); i++) { - DOMMatrix* matrixComponent = transform_components_[i]->AsMatrix(); + const DOMMatrix* matrixComponent = transform_components_[i]->AsMatrix(); if (matrixComponent) { - matrix->multiplySelf(matrixComponent); + matrix->multiplySelf(*matrixComponent); } } return matrix;
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSTranslation.cpp b/third_party/WebKit/Source/core/css/cssom/CSSTranslation.cpp index 1df7c3b..eb76663 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSTranslation.cpp +++ b/third_party/WebKit/Source/core/css/cssom/CSSTranslation.cpp
@@ -197,7 +197,7 @@ z_ = z; } -DOMMatrix* CSSTranslation::AsMatrix() const { +const DOMMatrix* CSSTranslation::AsMatrix() const { CSSUnitValue* x = x_->to(CSSPrimitiveValue::UnitType::kPixels); CSSUnitValue* y = y_->to(CSSPrimitiveValue::UnitType::kPixels); CSSUnitValue* z = z_->to(CSSPrimitiveValue::UnitType::kPixels);
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSTranslation.h b/third_party/WebKit/Source/core/css/cssom/CSSTranslation.h index 1155435b..0892879 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSTranslation.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSTranslation.h
@@ -41,16 +41,16 @@ static CSSTranslation* FromCSSValue(const CSSFunctionValue&); // Getters and setters for attributes defined in the IDL. - CSSNumericValue* x() const { return x_; } - CSSNumericValue* y() const { return y_; } - CSSNumericValue* z() const { return z_; } + CSSNumericValue* x() { return x_; } + CSSNumericValue* y() { return y_; } + CSSNumericValue* z() { return z_; } void setX(CSSNumericValue* x, ExceptionState&); void setY(CSSNumericValue* y, ExceptionState&); void setZ(CSSNumericValue* z, ExceptionState&); // Internal methods - from CSSTransformComponent. TransformComponentType GetType() const final { return kTranslationType; } - DOMMatrix* AsMatrix() const final; + const DOMMatrix* AsMatrix() const final; CSSFunctionValue* ToCSSValue() const final; DEFINE_INLINE_VIRTUAL_TRACE() {
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserTokenTest.cpp b/third_party/WebKit/Source/core/css/parser/CSSParserTokenTest.cpp index 9ad6a16..d89f331 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserTokenTest.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSParserTokenTest.cpp
@@ -8,10 +8,10 @@ namespace blink { -static CSSParserToken Ident(const String& string) { +static CSSParserToken IdentToken(const String& string) { return CSSParserToken(kIdentToken, string); } -static CSSParserToken Dimension(double value, const String& unit) { +static CSSParserToken DimensionToken(double value, const String& unit) { CSSParserToken token(kNumberToken, value, kNumberValueType, kNoSign); token.ConvertToDimensionWithUnit(unit); return token; @@ -23,11 +23,11 @@ String foo16_bit = String::Make16BitFrom8BitSource(foo8_bit.Characters8(), foo8_bit.length()); - EXPECT_EQ(Ident(foo8_bit), Ident(foo16_bit)); - EXPECT_EQ(Ident(foo16_bit), Ident(foo8_bit)); - EXPECT_EQ(Ident(foo16_bit), Ident(foo16_bit)); - EXPECT_NE(Ident(bar8_bit), Ident(foo8_bit)); - EXPECT_NE(Ident(bar8_bit), Ident(foo16_bit)); + EXPECT_EQ(IdentToken(foo8_bit), IdentToken(foo16_bit)); + EXPECT_EQ(IdentToken(foo16_bit), IdentToken(foo8_bit)); + EXPECT_EQ(IdentToken(foo16_bit), IdentToken(foo16_bit)); + EXPECT_NE(IdentToken(bar8_bit), IdentToken(foo8_bit)); + EXPECT_NE(IdentToken(bar8_bit), IdentToken(foo16_bit)); } TEST(CSSParserTokenTest, DimensionTokenEquality) { @@ -36,10 +36,10 @@ String em16_bit = String::Make16BitFrom8BitSource(em8_bit.Characters8(), em8_bit.length()); - EXPECT_EQ(Dimension(1, em8_bit), Dimension(1, em16_bit)); - EXPECT_EQ(Dimension(1, em8_bit), Dimension(1, em8_bit)); - EXPECT_NE(Dimension(1, em8_bit), Dimension(1, rem8_bit)); - EXPECT_NE(Dimension(2, em8_bit), Dimension(1, em16_bit)); + EXPECT_EQ(DimensionToken(1, em8_bit), DimensionToken(1, em16_bit)); + EXPECT_EQ(DimensionToken(1, em8_bit), DimensionToken(1, em8_bit)); + EXPECT_NE(DimensionToken(1, em8_bit), DimensionToken(1, rem8_bit)); + EXPECT_NE(DimensionToken(2, em8_bit), DimensionToken(1, em16_bit)); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/parser/CSSTokenizerTest.cpp b/third_party/WebKit/Source/core/css/parser/CSSTokenizerTest.cpp index 40834fb..a8c3b13a 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSTokenizerTest.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSTokenizerTest.cpp
@@ -90,7 +90,7 @@ static CSSParserToken GetString(const String& string) { return CSSParserToken(kStringToken, string); } -static CSSParserToken Function(const String& string) { +static CSSParserToken Func(const String& string) { return CSSParserToken(kFunctionToken, string); } static CSSParserToken Url(const String& string) { @@ -272,17 +272,17 @@ } TEST(CSSTokenizerTest, FunctionToken) { - TEST_TOKENS("scale(2)", Function("scale"), - Number(kIntegerValueType, 2, kNoSign), RightParenthesis()); - TEST_TOKENS("foo-bar\\ baz(", Function("foo-bar baz")); - TEST_TOKENS("fun\\(ction(", Function("fun(ction")); - TEST_TOKENS("-foo(", Function("-foo")); - TEST_TOKENS("url(\"foo.gif\"", Function("url"), GetString("foo.gif")); - TEST_TOKENS("foo( \'bar.gif\'", Function("foo"), Whitespace(), + TEST_TOKENS("scale(2)", Func("scale"), Number(kIntegerValueType, 2, kNoSign), + RightParenthesis()); + TEST_TOKENS("foo-bar\\ baz(", Func("foo-bar baz")); + TEST_TOKENS("fun\\(ction(", Func("fun(ction")); + TEST_TOKENS("-foo(", Func("-foo")); + TEST_TOKENS("url(\"foo.gif\"", Func("url"), GetString("foo.gif")); + TEST_TOKENS("foo( \'bar.gif\'", Func("foo"), Whitespace(), GetString("bar.gif")); // To simplify implementation we drop the whitespace in // function(url),whitespace,string() - TEST_TOKENS("url( \'bar.gif\'", Function("url"), GetString("bar.gif")); + TEST_TOKENS("url( \'bar.gif\'", Func("url"), GetString("bar.gif")); } TEST(CSSTokenizerTest, AtKeywordToken) {
diff --git a/third_party/WebKit/Source/core/dom/DocumentTest.cpp b/third_party/WebKit/Source/core/dom/DocumentTest.cpp index aee33d2..1937e46 100644 --- a/third_party/WebKit/Source/core/dom/DocumentTest.cpp +++ b/third_party/WebKit/Source/core/dom/DocumentTest.cpp
@@ -285,13 +285,13 @@ DocumentShutdownObserver::Trace(visitor); } -class MockValidationMessageClient - : public GarbageCollectedFinalized<MockValidationMessageClient>, +class MockDocumentValidationMessageClient + : public GarbageCollectedFinalized<MockDocumentValidationMessageClient>, public ValidationMessageClient { - USING_GARBAGE_COLLECTED_MIXIN(MockValidationMessageClient); + USING_GARBAGE_COLLECTED_MIXIN(MockDocumentValidationMessageClient); public: - MockValidationMessageClient() { Reset(); } + MockDocumentValidationMessageClient() { Reset(); } void Reset() { show_validation_message_was_called = false; document_detached_was_called = false; @@ -798,7 +798,8 @@ TEST_F(DocumentTest, ValidationMessageCleanup) { ValidationMessageClient* original_client = &GetPage().GetValidationMessageClient(); - MockValidationMessageClient* mock_client = new MockValidationMessageClient(); + MockDocumentValidationMessageClient* mock_client = + new MockDocumentValidationMessageClient(); GetDocument().GetSettings()->SetScriptEnabled(true); GetPage().SetValidationMessageClient(mock_client); // ImplicitOpen()-CancelParsing() makes Document.loadEventFinished()
diff --git a/third_party/WebKit/Source/core/dom/IdleDeadlineTest.cpp b/third_party/WebKit/Source/core/dom/IdleDeadlineTest.cpp index 59d723e..a9cd888 100644 --- a/third_party/WebKit/Source/core/dom/IdleDeadlineTest.cpp +++ b/third_party/WebKit/Source/core/dom/IdleDeadlineTest.cpp
@@ -12,10 +12,10 @@ namespace blink { namespace { -class MockScheduler final : public WebScheduler { +class MockIdleDeadlineScheduler final : public WebScheduler { public: - MockScheduler() {} - ~MockScheduler() override {} + MockIdleDeadlineScheduler() {} + ~MockIdleDeadlineScheduler() override {} // WebScheduler implementation: WebTaskRunner* LoadingTaskRunner() override { return nullptr; } @@ -40,30 +40,30 @@ scheduler::RendererScheduler::NavigatingFrameType) override {} private: - DISALLOW_COPY_AND_ASSIGN(MockScheduler); + DISALLOW_COPY_AND_ASSIGN(MockIdleDeadlineScheduler); }; -class MockThread final : public WebThread { +class MockIdleDeadlineThread final : public WebThread { public: - MockThread() {} - ~MockThread() override {} + MockIdleDeadlineThread() {} + ~MockIdleDeadlineThread() override {} bool IsCurrentThread() const override { return true; } WebScheduler* Scheduler() const override { return &scheduler_; } private: - mutable MockScheduler scheduler_; - DISALLOW_COPY_AND_ASSIGN(MockThread); + mutable MockIdleDeadlineScheduler scheduler_; + DISALLOW_COPY_AND_ASSIGN(MockIdleDeadlineThread); }; -class MockPlatform : public TestingPlatformSupport { +class MockIdleDeadlinePlatform : public TestingPlatformSupport { public: - MockPlatform() {} - ~MockPlatform() override {} + MockIdleDeadlinePlatform() {} + ~MockIdleDeadlinePlatform() override {} WebThread* CurrentThread() override { return &thread_; } private: - MockThread thread_; - DISALLOW_COPY_AND_ASSIGN(MockPlatform); + MockIdleDeadlineThread thread_; + DISALLOW_COPY_AND_ASSIGN(MockIdleDeadlinePlatform); }; } // namespace @@ -96,7 +96,7 @@ } TEST_F(IdleDeadlineTest, yieldForHighPriorityWork) { - ScopedTestingPlatformSupport<MockPlatform> platform; + ScopedTestingPlatformSupport<MockIdleDeadlinePlatform> platform; IdleDeadline* deadline = IdleDeadline::Create(1.25, IdleDeadline::CallbackType::kCalledWhenIdle);
diff --git a/third_party/WebKit/Source/core/dom/ScriptedIdleTaskControllerTest.cpp b/third_party/WebKit/Source/core/dom/ScriptedIdleTaskControllerTest.cpp index b3f3c44..5f1536764 100644 --- a/third_party/WebKit/Source/core/dom/ScriptedIdleTaskControllerTest.cpp +++ b/third_party/WebKit/Source/core/dom/ScriptedIdleTaskControllerTest.cpp
@@ -16,10 +16,11 @@ namespace blink { namespace { -class MockScheduler final : public WebScheduler { +class MockScriptedIdleTaskControllerScheduler final : public WebScheduler { public: - MockScheduler(bool should_yield) : should_yield_(should_yield) {} - ~MockScheduler() override {} + MockScriptedIdleTaskControllerScheduler(bool should_yield) + : should_yield_(should_yield) {} + ~MockScriptedIdleTaskControllerScheduler() override {} // WebScheduler implementation: WebTaskRunner* LoadingTaskRunner() override { return nullptr; } @@ -56,13 +57,14 @@ bool should_yield_; std::unique_ptr<WebThread::IdleTask> idle_task_; - DISALLOW_COPY_AND_ASSIGN(MockScheduler); + DISALLOW_COPY_AND_ASSIGN(MockScriptedIdleTaskControllerScheduler); }; -class MockThread final : public WebThread { +class MockScriptedIdleTaskControllerThread final : public WebThread { public: - MockThread(bool should_yield) : scheduler_(should_yield) {} - ~MockThread() override {} + MockScriptedIdleTaskControllerThread(bool should_yield) + : scheduler_(should_yield) {} + ~MockScriptedIdleTaskControllerThread() override {} bool IsCurrentThread() const override { return true; } WebScheduler* Scheduler() const override { return &scheduler_; } @@ -70,22 +72,23 @@ bool HasIdleTask() const { return scheduler_.HasIdleTask(); } private: - mutable MockScheduler scheduler_; - DISALLOW_COPY_AND_ASSIGN(MockThread); + mutable MockScriptedIdleTaskControllerScheduler scheduler_; + DISALLOW_COPY_AND_ASSIGN(MockScriptedIdleTaskControllerThread); }; -class MockPlatform : public TestingPlatformSupport { +class MockScriptedIdleTaskControllerPlatform : public TestingPlatformSupport { public: - MockPlatform(bool should_yield) : thread_(should_yield) {} - ~MockPlatform() override {} + MockScriptedIdleTaskControllerPlatform(bool should_yield) + : thread_(should_yield) {} + ~MockScriptedIdleTaskControllerPlatform() override {} WebThread* CurrentThread() override { return &thread_; } void RunIdleTask() { thread_.RunIdleTask(); } bool HasIdleTask() const { return thread_.HasIdleTask(); } private: - MockThread thread_; - DISALLOW_COPY_AND_ASSIGN(MockPlatform); + MockScriptedIdleTaskControllerThread thread_; + DISALLOW_COPY_AND_ASSIGN(MockScriptedIdleTaskControllerPlatform); }; class MockIdleRequestCallback : public IdleRequestCallback { @@ -104,7 +107,8 @@ }; TEST_F(ScriptedIdleTaskControllerTest, RunCallback) { - ScopedTestingPlatformSupport<MockPlatform, bool> platform(false); + ScopedTestingPlatformSupport<MockScriptedIdleTaskControllerPlatform, bool> + platform(false); NullExecutionContext execution_context; ScriptedIdleTaskController* controller = ScriptedIdleTaskController::Create(execution_context_); @@ -116,14 +120,15 @@ EXPECT_TRUE(platform->HasIdleTask()); EXPECT_NE(0, id); - EXPECT_CALL(*callback, handleEvent(testing::_)); + EXPECT_CALL(*callback, handleEvent(::testing::_)); platform->RunIdleTask(); ::testing::Mock::VerifyAndClearExpectations(callback); EXPECT_FALSE(platform->HasIdleTask()); } TEST_F(ScriptedIdleTaskControllerTest, DontRunCallbackWhenAskedToYield) { - ScopedTestingPlatformSupport<MockPlatform, bool> platform(true); + ScopedTestingPlatformSupport<MockScriptedIdleTaskControllerPlatform, bool> + platform(true); NullExecutionContext execution_context; ScriptedIdleTaskController* controller = ScriptedIdleTaskController::Create(execution_context_); @@ -133,7 +138,7 @@ int id = controller->RegisterCallback(callback, options); EXPECT_NE(0, id); - EXPECT_CALL(*callback, handleEvent(testing::_)).Times(0); + EXPECT_CALL(*callback, handleEvent(::testing::_)).Times(0); platform->RunIdleTask(); ::testing::Mock::VerifyAndClearExpectations(callback);
diff --git a/third_party/WebKit/Source/core/dom/SelectorQueryTest.cpp b/third_party/WebKit/Source/core/dom/SelectorQueryTest.cpp index f444d10d..054d0d44 100644 --- a/third_party/WebKit/Source/core/dom/SelectorQueryTest.cpp +++ b/third_party/WebKit/Source/core/dom/SelectorQueryTest.cpp
@@ -34,10 +34,10 @@ void RunTests(ContainerNode& scope, const QueryTest (&test_cases)[length]) { for (const auto& test_case : test_cases) { const char* selector = test_case.selector; - SCOPED_TRACE(testing::Message() - << (test_case.query_all ? "querySelectorAll('" - : "querySelector('") - << selector << "')"); + SCOPED_TRACE( + ::testing::Message() + << (test_case.query_all ? "querySelectorAll('" : "querySelector('") + << selector << "')"); if (test_case.query_all) { StaticElementList* match_all = scope.QuerySelectorAll(selector); EXPECT_EQ(test_case.matches, match_all->length());
diff --git a/third_party/WebKit/Source/core/frame/BUILD.gn b/third_party/WebKit/Source/core/frame/BUILD.gn index 71ba42e..4607c04 100644 --- a/third_party/WebKit/Source/core/frame/BUILD.gn +++ b/third_party/WebKit/Source/core/frame/BUILD.gn
@@ -130,6 +130,8 @@ "WebFrameSerializerImpl.h", "WebFrameWidgetBase.cpp", "WebFrameWidgetBase.h", + "WebFrameWidgetImpl.cpp", + "WebFrameWidgetImpl.h", "WebLocalFrameBase.cpp", "WebLocalFrameBase.h", "WebRemoteFrameBase.cpp",
diff --git a/third_party/WebKit/Source/core/frame/BrowserControlsTest.cpp b/third_party/WebKit/Source/core/frame/BrowserControlsTest.cpp index 88d4900e..8e5ff9c 100644 --- a/third_party/WebKit/Source/core/frame/BrowserControlsTest.cpp +++ b/third_party/WebKit/Source/core/frame/BrowserControlsTest.cpp
@@ -141,12 +141,6 @@ FrameTestHelpers::WebViewHelper helper_; }; -#define EXPECT_SIZE_EQ(expected, actual) \ - do { \ - EXPECT_FLOAT_EQ((expected).Width(), (actual).Width()); \ - EXPECT_FLOAT_EQ((expected).Height(), (actual).Height()); \ - } while (false) - // Disable these tests on Mac OSX until further investigation. // Local build on Mac is OK but the bot fails. This is not an issue as // Browser Controls are currently only used on Android.
diff --git a/third_party/WebKit/Source/core/frame/FrameSerializerTest.cpp b/third_party/WebKit/Source/core/frame/FrameSerializerTest.cpp index 3e4963c..44a0eaa4 100644 --- a/third_party/WebKit/Source/core/frame/FrameSerializerTest.cpp +++ b/third_party/WebKit/Source/core/frame/FrameSerializerTest.cpp
@@ -52,16 +52,14 @@ #include "public/web/WebSettings.h" #include "testing/gtest/include/gtest/gtest.h" -using blink::URLTestHelpers::ToKURL; -using blink::URLTestHelpers::RegisterMockedURLLoad; - namespace blink { class FrameSerializerTest : public ::testing::Test, public FrameSerializer::Delegate { public: FrameSerializerTest() - : folder_("frameserializer/"), base_url_(ToKURL("http://www.test.com")) {} + : folder_("frameserializer/"), + base_url_(URLTestHelpers::ToKURL("http://www.test.com")) {} protected: void SetUp() override { @@ -80,7 +78,7 @@ void SetRewriteURLFolder(const char* folder) { rewrite_folder_ = folder; } void RegisterURL(const KURL& url, const char* file, const char* mime_type) { - RegisterMockedURLLoad( + URLTestHelpers::RegisterMockedURLLoad( url, testing::CoreTestDataPath(WebString::FromUTF8(folder_ + file)), WebString::FromUTF8(mime_type)); } @@ -356,8 +354,9 @@ RegisterURL("ul-dot.png", "image.png", "image/png"); RegisterURL("ol-dot.png", "image.png", "image/png"); - const KURL image_url_from_data_url(ToKURL("http://www.dataurl.com"), - "fuchsia_background.png"); + const KURL image_url_from_data_url( + URLTestHelpers::ToKURL("http://www.dataurl.com"), + "fuchsia_background.png"); RegisterURL(image_url_from_data_url, "image.png", "image/png"); RegisterURL("included_in_another_frame.css", "text/css");
diff --git a/third_party/WebKit/Source/core/frame/FrameTestHelpers.h b/third_party/WebKit/Source/core/frame/FrameTestHelpers.h index f9c1e9a..03e3e5e 100644 --- a/third_party/WebKit/Source/core/frame/FrameTestHelpers.h +++ b/third_party/WebKit/Source/core/frame/FrameTestHelpers.h
@@ -53,6 +53,50 @@ #include "public/web/WebViewClient.h" #include "services/service_manager/public/cpp/interface_provider.h" +#define ASSERT_POINT_EQ(expected, actual) \ + do { \ + ASSERT_EQ((expected).x(), (actual).x()); \ + ASSERT_EQ((expected).y(), (actual).y()); \ + } while (false) + +#define ASSERT_SIZE_EQ(expected, actual) \ + do { \ + ASSERT_EQ((expected).Width(), (actual).Width()); \ + ASSERT_EQ((expected).Height(), (actual).Height()); \ + } while (false) + +#define EXPECT_POINT_EQ(expected, actual) \ + do { \ + EXPECT_EQ((expected).X(), (actual).X()); \ + EXPECT_EQ((expected).Y(), (actual).Y()); \ + } while (false) + +#define EXPECT_FLOAT_POINT_EQ(expected, actual) \ + do { \ + EXPECT_FLOAT_EQ((expected).X(), (actual).X()); \ + EXPECT_FLOAT_EQ((expected).Y(), (actual).Y()); \ + } while (false) + +#define EXPECT_SIZE_EQ(expected, actual) \ + do { \ + EXPECT_EQ((expected).Width(), (actual).Width()); \ + EXPECT_EQ((expected).Height(), (actual).Height()); \ + } while (false) + +#define EXPECT_FLOAT_SIZE_EQ(expected, actual) \ + do { \ + EXPECT_FLOAT_EQ((expected).Width(), (actual).Width()); \ + EXPECT_FLOAT_EQ((expected).Height(), (actual).Height()); \ + } while (false) + +#define EXPECT_FLOAT_RECT_EQ(expected, actual) \ + do { \ + EXPECT_FLOAT_EQ((expected).X(), (actual).X()); \ + EXPECT_FLOAT_EQ((expected).Y(), (actual).Y()); \ + EXPECT_FLOAT_EQ((expected).Width(), (actual).Width()); \ + EXPECT_FLOAT_EQ((expected).Height(), (actual).Height()); \ + } while (false) + namespace blink { class WebFrame;
diff --git a/third_party/WebKit/Source/core/frame/LocalFrameViewTest.cpp b/third_party/WebKit/Source/core/frame/LocalFrameViewTest.cpp index a703ec3..5ba3fd1 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrameViewTest.cpp +++ b/third_party/WebKit/Source/core/frame/LocalFrameViewTest.cpp
@@ -29,9 +29,9 @@ namespace blink { namespace { -class MockChromeClient : public EmptyChromeClient { +class AnimationMockChromeClient : public EmptyChromeClient { public: - MockChromeClient() : has_scheduled_animation_(false) {} + AnimationMockChromeClient() : has_scheduled_animation_(false) {} // ChromeClient MOCK_METHOD2(AttachRootGraphicsLayer, @@ -57,7 +57,7 @@ protected: LocalFrameViewTest() : ScopedRootLayerScrollingForTest(GetParam()), - chrome_client_(new MockChromeClient) { + chrome_client_(new AnimationMockChromeClient) { EXPECT_CALL(ChromeClient(), AttachRootGraphicsLayer(_, _)) .Times(AnyNumber()); } @@ -76,10 +76,10 @@ } Document& GetDocument() { return page_holder_->GetDocument(); } - MockChromeClient& ChromeClient() { return *chrome_client_; } + AnimationMockChromeClient& ChromeClient() { return *chrome_client_; } private: - Persistent<MockChromeClient> chrome_client_; + Persistent<AnimationMockChromeClient> chrome_client_; std::unique_ptr<DummyPageHolder> page_holder_; };
diff --git a/third_party/WebKit/Source/core/frame/RootFrameViewportTest.cpp b/third_party/WebKit/Source/core/frame/RootFrameViewportTest.cpp index 3b3351e..3ed693a 100644 --- a/third_party/WebKit/Source/core/frame/RootFrameViewportTest.cpp +++ b/third_party/WebKit/Source/core/frame/RootFrameViewportTest.cpp
@@ -4,6 +4,7 @@ #include "core/frame/RootFrameViewport.h" +#include "core/frame/FrameTestHelpers.h" #include "core/layout/ScrollAlignment.h" #include "platform/geometry/DoubleRect.h" #include "platform/geometry/LayoutRect.h" @@ -13,17 +14,6 @@ #include "public/platform/WebThread.h" #include "testing/gtest/include/gtest/gtest.h" -#define EXPECT_POINT_EQ(expected, actual) \ - do { \ - EXPECT_EQ((expected).X(), (actual).X()); \ - EXPECT_EQ((expected).Y(), (actual).Y()); \ - } while (false) -#define EXPECT_SIZE_EQ(expected, actual) \ - do { \ - EXPECT_EQ((expected).Width(), (actual).Width()); \ - EXPECT_EQ((expected).Height(), (actual).Height()); \ - } while (false) - namespace blink { class ScrollableAreaStub : public GarbageCollectedFinalized<ScrollableAreaStub>,
diff --git a/third_party/WebKit/Source/core/frame/VisualViewportTest.cpp b/third_party/WebKit/Source/core/frame/VisualViewportTest.cpp index 26e5d5a..1122520 100644 --- a/third_party/WebKit/Source/core/frame/VisualViewportTest.cpp +++ b/third_party/WebKit/Source/core/frame/VisualViewportTest.cpp
@@ -46,50 +46,6 @@ #include <string> -#define ASSERT_POINT_EQ(expected, actual) \ - do { \ - ASSERT_EQ((expected).x(), (actual).x()); \ - ASSERT_EQ((expected).y(), (actual).y()); \ - } while (false) - -#define ASSERT_SIZE_EQ(expected, actual) \ - do { \ - ASSERT_EQ((expected).Width(), (actual).Width()); \ - ASSERT_EQ((expected).Height(), (actual).Height()); \ - } while (false) - -#define EXPECT_POINT_EQ(expected, actual) \ - do { \ - EXPECT_EQ((expected).X(), (actual).X()); \ - EXPECT_EQ((expected).Y(), (actual).Y()); \ - } while (false) - -#define EXPECT_FLOAT_POINT_EQ(expected, actual) \ - do { \ - EXPECT_FLOAT_EQ((expected).X(), (actual).X()); \ - EXPECT_FLOAT_EQ((expected).Y(), (actual).Y()); \ - } while (false) - -#define EXPECT_SIZE_EQ(expected, actual) \ - do { \ - EXPECT_EQ((expected).Width(), (actual).Width()); \ - EXPECT_EQ((expected).Height(), (actual).Height()); \ - } while (false) - -#define EXPECT_FLOAT_SIZE_EQ(expected, actual) \ - do { \ - EXPECT_FLOAT_EQ((expected).Width(), (actual).Width()); \ - EXPECT_FLOAT_EQ((expected).Height(), (actual).Height()); \ - } while (false) - -#define EXPECT_FLOAT_RECT_EQ(expected, actual) \ - do { \ - EXPECT_FLOAT_EQ((expected).X(), (actual).X()); \ - EXPECT_FLOAT_EQ((expected).Y(), (actual).Y()); \ - EXPECT_FLOAT_EQ((expected).Width(), (actual).Width()); \ - EXPECT_FLOAT_EQ((expected).Height(), (actual).Height()); \ - } while (false) - using ::testing::_; using ::testing::PrintToString; using ::testing::Mock;
diff --git a/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp b/third_party/WebKit/Source/core/frame/WebFrameWidgetImpl.cpp similarity index 99% rename from third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp rename to third_party/WebKit/Source/core/frame/WebFrameWidgetImpl.cpp index f0ab8a3..33031eb 100644 --- a/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp +++ b/third_party/WebKit/Source/core/frame/WebFrameWidgetImpl.cpp
@@ -28,7 +28,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "web/WebFrameWidgetImpl.h" +#include "core/frame/WebFrameWidgetImpl.h" #include <memory> @@ -824,9 +824,10 @@ PageWidgetEventHandler::HandleMouseDown(main_frame, event); - if (event.button == WebMouseEvent::Button::kLeft && mouse_capture_node_) + if (event.button == WebMouseEvent::Button::kLeft && mouse_capture_node_) { mouse_capture_gesture_token_ = main_frame.GetEventHandler().TakeLastMouseDownGestureToken(); + } if (view_impl->GetPagePopup() && page_popup && ToWebPagePopupImpl(view_impl->GetPagePopup()) @@ -1022,9 +1023,10 @@ suppress_next_keypress_event_ = false; LocalFrame* frame = ToLocalFrame(FocusedCoreFrame()); - if (!frame) + if (!frame) { return suppress ? WebInputEventResult::kHandledSuppressed : WebInputEventResult::kNotHandled; + } EventHandler& handler = frame->GetEventHandler(); @@ -1186,9 +1188,10 @@ void WebFrameWidgetImpl::SetVisibilityState( WebPageVisibilityState visibility_state) { - if (layer_tree_view_) + if (layer_tree_view_) { layer_tree_view_->SetVisible(visibility_state == kWebPageVisibilityStateVisible); + } } HitTestResult WebFrameWidgetImpl::HitTestResultForRootFramePos(
diff --git a/third_party/WebKit/Source/web/WebFrameWidgetImpl.h b/third_party/WebKit/Source/core/frame/WebFrameWidgetImpl.h similarity index 100% rename from third_party/WebKit/Source/web/WebFrameWidgetImpl.h rename to third_party/WebKit/Source/core/frame/WebFrameWidgetImpl.h
diff --git a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveListTest.cpp b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveListTest.cpp index f224619..5268f9e8 100644 --- a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveListTest.cpp +++ b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveListTest.cpp
@@ -157,8 +157,8 @@ }; for (const auto& test : cases) { - SCOPED_TRACE(testing::Message() << "List: `" << test.list << "`, URL: `" - << test.url << "`"); + SCOPED_TRACE(::testing::Message() + << "List: `" << test.list << "`, URL: `" << test.url << "`"); KURL script_src = KURL(NullURL(), test.url); // Report-only @@ -213,8 +213,8 @@ }; for (const auto& test : cases) { - SCOPED_TRACE(testing::Message() << "List: `" << test.list << "`, URL: `" - << test.url << "`"); + SCOPED_TRACE(::testing::Message() + << "List: `" << test.list << "`, URL: `" << test.url << "`"); KURL resource = KURL(NullURL(), test.url); // Report-only 'script-src' @@ -350,7 +350,7 @@ }; for (const auto& test : cases) { - SCOPED_TRACE(testing::Message() + SCOPED_TRACE(::testing::Message() << "List: `" << test.list << "`, URL: `" << test.url << "`, Integrity: `" << test.integrity << "`"); KURL resource = KURL(NullURL(), test.url);
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp index 974815ff..67ce29e 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp
@@ -58,8 +58,8 @@ // Enforced for (const auto& test : cases) { - SCOPED_TRACE(testing::Message() << "[Enforce] Header: `" << test.header - << "`"); + SCOPED_TRACE(::testing::Message() + << "[Enforce] Header: `" << test.header << "`"); csp = ContentSecurityPolicy::Create(); csp->DidReceiveHeader(test.header, kContentSecurityPolicyHeaderTypeEnforce, kContentSecurityPolicyHeaderSourceHTTP); @@ -79,8 +79,8 @@ // Report-Only for (const auto& test : cases) { - SCOPED_TRACE(testing::Message() << "[Report-Only] Header: `" << test.header - << "`"); + SCOPED_TRACE(::testing::Message() + << "[Report-Only] Header: `" << test.header << "`"); csp = ContentSecurityPolicy::Create(); csp->DidReceiveHeader(test.header, kContentSecurityPolicyHeaderTypeReport, kContentSecurityPolicyHeaderSourceHTTP); @@ -665,9 +665,9 @@ }; for (const auto& test : cases) { - SCOPED_TRACE(testing::Message() << "Policy: `" << test.policy << "`, URL: `" - << test.url << "`, Nonce: `" << test.nonce - << "`"); + SCOPED_TRACE(::testing::Message() + << "Policy: `" << test.policy << "`, URL: `" << test.url + << "`, Nonce: `" << test.nonce << "`"); KURL resource = KURL(NullURL(), test.url); unsigned expected_reports = test.allowed ? 0u : 1u; @@ -725,8 +725,8 @@ document->SetSecurityOrigin(secure_origin); for (const auto& test : cases) { - SCOPED_TRACE(testing::Message() << "Policy: `" << test.policy - << "`, Nonce: `" << test.nonce << "`"); + SCOPED_TRACE(::testing::Message() << "Policy: `" << test.policy + << "`, Nonce: `" << test.nonce << "`"); unsigned expected_reports = test.allowed ? 0u : 1u; HTMLScriptElement* element = HTMLScriptElement::Create(*document, true); @@ -828,9 +828,9 @@ }; for (const auto& test : cases) { - SCOPED_TRACE(testing::Message() << "Policy: `" << test.policy1 << "`/`" - << test.policy2 << "`, URL: `" << test.url - << "`, Nonce: `" << test.nonce << "`"); + SCOPED_TRACE(::testing::Message() << "Policy: `" << test.policy1 << "`/`" + << test.policy2 << "`, URL: `" << test.url + << "`, Nonce: `" << test.nonce << "`"); KURL resource = KURL(NullURL(), test.url); unsigned expected_reports =
diff --git a/third_party/WebKit/Source/core/geometry/DOMMatrix.cpp b/third_party/WebKit/Source/core/geometry/DOMMatrix.cpp index 77584f8..1843083 100644 --- a/third_party/WebKit/Source/core/geometry/DOMMatrix.cpp +++ b/third_party/WebKit/Source/core/geometry/DOMMatrix.cpp
@@ -143,14 +143,14 @@ DCHECK(exception_state.HadException()); return nullptr; } - return multiplySelf(other_matrix); + return multiplySelf(*other_matrix); } -DOMMatrix* DOMMatrix::multiplySelf(DOMMatrix* other_matrix) { - if (!other_matrix->is2D()) +DOMMatrix* DOMMatrix::multiplySelf(const DOMMatrix& other_matrix) { + if (!other_matrix.is2D()) is2d_ = false; - *matrix_ *= other_matrix->Matrix(); + *matrix_ *= other_matrix.Matrix(); return this; }
diff --git a/third_party/WebKit/Source/core/geometry/DOMMatrix.h b/third_party/WebKit/Source/core/geometry/DOMMatrix.h index f93c2e6..1a3a1398 100644 --- a/third_party/WebKit/Source/core/geometry/DOMMatrix.h +++ b/third_party/WebKit/Source/core/geometry/DOMMatrix.h
@@ -88,7 +88,7 @@ } DOMMatrix* multiplySelf(DOMMatrixInit&, ExceptionState&); - DOMMatrix* multiplySelf(DOMMatrix* other_matrix); + DOMMatrix* multiplySelf(const DOMMatrix& other_matrix); DOMMatrix* preMultiplySelf(DOMMatrixInit&, ExceptionState&); DOMMatrix* translateSelf(double tx = 0, double ty = 0, double tz = 0); DOMMatrix* scaleSelf(double sx = 1);
diff --git a/third_party/WebKit/Source/core/html/HTMLFormControlElementTest.cpp b/third_party/WebKit/Source/core/html/HTMLFormControlElementTest.cpp index 3a3ffcf6..fdb2e14 100644 --- a/third_party/WebKit/Source/core/html/HTMLFormControlElementTest.cpp +++ b/third_party/WebKit/Source/core/html/HTMLFormControlElementTest.cpp
@@ -18,10 +18,10 @@ namespace blink { namespace { -class MockValidationMessageClient - : public GarbageCollectedFinalized<MockValidationMessageClient>, +class MockFormValidationMessageClient + : public GarbageCollectedFinalized<MockFormValidationMessageClient>, public ValidationMessageClient { - USING_GARBAGE_COLLECTED_MIXIN(MockValidationMessageClient); + USING_GARBAGE_COLLECTED_MIXIN(MockFormValidationMessageClient); public: void ShowValidationMessage(const Element& anchor, @@ -127,7 +127,7 @@ "<body><input required id=input></body>"); GetDocument().View()->UpdateAllLifecyclePhases(); ValidationMessageClient* validation_message_client = - new MockValidationMessageClient(); + new MockFormValidationMessageClient(); GetPage().SetValidationMessageClient(validation_message_client); Page::OrdinaryPages().insert(&GetPage());
diff --git a/third_party/WebKit/Source/core/html/HTMLMediaElementTest.cpp b/third_party/WebKit/Source/core/html/HTMLMediaElementTest.cpp index 93e6f3ae..e76e7446 100644 --- a/third_party/WebKit/Source/core/html/HTMLMediaElementTest.cpp +++ b/third_party/WebKit/Source/core/html/HTMLMediaElementTest.cpp
@@ -13,14 +13,14 @@ namespace blink { -enum class TestParam { kAudio, kVideo }; +enum class MediaTestParam { kAudio, kVideo }; -class HTMLMediaElementTest : public ::testing::TestWithParam<TestParam> { +class HTMLMediaElementTest : public ::testing::TestWithParam<MediaTestParam> { protected: void SetUp() { dummy_page_holder_ = DummyPageHolder::Create(); - if (GetParam() == TestParam::kAudio) + if (GetParam() == MediaTestParam::kAudio) media_ = HTMLAudioElement::Create(dummy_page_holder_->GetDocument()); else media_ = HTMLVideoElement::Create(dummy_page_holder_->GetDocument()); @@ -39,10 +39,10 @@ INSTANTIATE_TEST_CASE_P(Audio, HTMLMediaElementTest, - ::testing::Values(TestParam::kAudio)); + ::testing::Values(MediaTestParam::kAudio)); INSTANTIATE_TEST_CASE_P(Video, HTMLMediaElementTest, - ::testing::Values(TestParam::kVideo)); + ::testing::Values(MediaTestParam::kVideo)); TEST_P(HTMLMediaElementTest, effectiveMediaVolume) { struct TestData {
diff --git a/third_party/WebKit/Source/core/html/HTMLVideoElementPersistentTest.cpp b/third_party/WebKit/Source/core/html/HTMLVideoElementPersistentTest.cpp index d8a04a4..1f3bdc3 100644 --- a/third_party/WebKit/Source/core/html/HTMLVideoElementPersistentTest.cpp +++ b/third_party/WebKit/Source/core/html/HTMLVideoElementPersistentTest.cpp
@@ -20,7 +20,7 @@ namespace { -class MockChromeClient : public EmptyChromeClient { +class FullscreenMockChromeClient : public EmptyChromeClient { public: MOCK_METHOD1(EnterFullscreen, void(LocalFrame&)); MOCK_METHOD1(ExitFullscreen, void(LocalFrame&)); @@ -34,7 +34,7 @@ class HTMLVideoElementPersistentTest : public ::testing::Test { protected: void SetUp() override { - chrome_client_ = new MockChromeClient(); + chrome_client_ = new FullscreenMockChromeClient(); Page::PageClients clients; FillWithEmptyClients(clients); @@ -59,7 +59,7 @@ return Fullscreen::FullscreenElementFrom(GetDocument()); } - MockChromeClient& GetMockChromeClient() { return *chrome_client_; } + FullscreenMockChromeClient& GetMockChromeClient() { return *chrome_client_; } void SimulateDidEnterFullscreen() { Fullscreen::FromIfExists(GetDocument())->DidEnterFullscreen(); @@ -75,7 +75,7 @@ private: std::unique_ptr<DummyPageHolder> page_holder_; - Persistent<MockChromeClient> chrome_client_; + Persistent<FullscreenMockChromeClient> chrome_client_; }; TEST_F(HTMLVideoElementPersistentTest, nothingIsFullscreen) {
diff --git a/third_party/WebKit/Source/core/html/media/MediaCustomControlsFullscreenDetectorTest.cpp b/third_party/WebKit/Source/core/html/media/MediaCustomControlsFullscreenDetectorTest.cpp index a1bbc01..1f11e0a7 100644 --- a/third_party/WebKit/Source/core/html/media/MediaCustomControlsFullscreenDetectorTest.cpp +++ b/third_party/WebKit/Source/core/html/media/MediaCustomControlsFullscreenDetectorTest.cpp
@@ -15,7 +15,7 @@ namespace { -struct TestParam { +struct VideoTestParam { String description; IntRect target_rect; bool expected_result; @@ -90,7 +90,7 @@ // TestWithParam cannot be applied here as IntRect needs the memory allocator // to be initialized, but the array of parameters is statically initialized, // which is before the memory allocation initialization. - TestParam test_params[] = { + VideoTestParam test_params[] = { {"xCompleteFill", {0, 0, 100, 50}, true}, {"yCompleteFill", {0, 0, 50, 100}, true}, {"xyCompleteFill", {0, 0, 100, 100}, true}, @@ -106,7 +106,7 @@ IntRect root_rect(0, 0, 100, 100); - for (const TestParam& test_param : test_params) { + for (const VideoTestParam& test_param : test_params) { const IntRect& target_rect = test_param.target_rect; IntRect intersection_rect = Intersection(target_rect, root_rect); EXPECT_EQ(test_param.expected_result,
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScannerTest.cpp b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScannerTest.cpp index f624e63..fec1dfdb 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScannerTest.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScannerTest.cpp
@@ -33,7 +33,7 @@ ClientHintsPreferences preferences; }; -struct PreconnectTestCase { +struct HTMLPreconnectTestCase { const char* base_url; const char* input_html; const char* preconnected_host; @@ -223,7 +223,7 @@ test_case.resource_width, test_case.preferences); } - void Test(PreconnectTestCase test_case) { + void Test(HTMLPreconnectTestCase test_case) { MockHTMLResourcePreloader preloader; KURL base_url(kParsedURLString, test_case.base_url); scanner_->AppendToEnd(String(test_case.input_html)); @@ -568,7 +568,7 @@ } TEST_F(HTMLPreloadScannerTest, testPreconnect) { - PreconnectTestCase test_cases[] = { + HTMLPreconnectTestCase test_cases[] = { {"http://example.test", "<link rel=preconnect href=http://example2.test>", "http://example2.test", kCrossOriginAttributeNotSet}, {"http://example.test",
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloaderTest.cpp b/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloaderTest.cpp index dd55969..9b5b4f9 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloaderTest.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloaderTest.cpp
@@ -11,7 +11,7 @@ namespace blink { -struct PreconnectTestCase { +struct HTMLResourcePreconnectTestCase { const char* base_url; const char* url; bool is_cors; @@ -45,7 +45,7 @@ protected: HTMLResourcePreloaderTest() : dummy_page_holder_(DummyPageHolder::Create()) {} - void Test(PreconnectTestCase test_case) { + void Test(HTMLResourcePreconnectTestCase test_case) { // TODO(yoav): Need a mock loader here to verify things are happenning // beyond preconnect. PreloaderNetworkHintsMock network_hints; @@ -71,7 +71,7 @@ }; TEST_F(HTMLResourcePreloaderTest, testPreconnect) { - PreconnectTestCase test_cases[] = { + HTMLResourcePreconnectTestCase test_cases[] = { {"http://example.test", "http://example.com", false, false}, {"http://example.test", "http://example.com", true, false}, {"http://example.test", "https://example.com", true, true},
diff --git a/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReaderTest.cpp b/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReaderTest.cpp index 8c150b96..779323e 100644 --- a/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReaderTest.cpp +++ b/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReaderTest.cpp
@@ -149,17 +149,15 @@ ASSERT_FALSE(reader.GetLine(line)); } -enum LineBreakType { kCr, kLf, kCrLf }; +enum NewlineType { kCr, kLf, kCrLf }; -String LineBreakString(LineBreakType type) { +String LineBreakString(NewlineType type) { static const char kBreakStrings[] = "\r\n"; return String(type == kLf ? kBreakStrings + 1 : kBreakStrings, type == kCrLf ? 2 : 1); } -String MakeTestData(const char** lines, - const LineBreakType* breaks, - int count) { +String MakeTestData(const char** lines, const NewlineType* breaks, int count) { StringBuilder builder; for (int i = 0; i < count; ++i) { builder.Append(lines[i]); @@ -174,7 +172,7 @@ TEST(BufferedLineReaderTest, BufferSizes) { const char* lines[] = {"aaaaaaaaaaaaaaaa", "bbbbbbbbbb", "ccccccccccccc", "", "dddddd", "", "eeeeeeeeee"}; - const LineBreakType kBreaks[] = {kLf, kLf, kLf, kLf, kLf, kLf, kLf}; + const NewlineType kBreaks[] = {kLf, kLf, kLf, kLf, kLf, kLf, kLf}; const size_t num_test_lines = WTF_ARRAY_LENGTH(lines); static_assert(num_test_lines == WTF_ARRAY_LENGTH(kBreaks), "number of test lines and breaks should be the same"); @@ -201,7 +199,7 @@ const char* lines[] = { "aaaaaaaaaaaaaaaa", "bbbbbbbbbb", "ccccccccccccc", "", "dddddd", "eeeeeeeeee", "fffffffffffffffffff"}; - const LineBreakType kBreaks[] = {kCr, kLf, kCrLf, kCr, kLf, kCrLf, kLf}; + const NewlineType kBreaks[] = {kCr, kLf, kCrLf, kCr, kLf, kCrLf, kLf}; const size_t num_test_lines = WTF_ARRAY_LENGTH(lines); static_assert(num_test_lines == WTF_ARRAY_LENGTH(kBreaks), "number of test lines and breaks should be the same");
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_block_layout_algorithm_test.cc b/third_party/WebKit/Source/core/layout/ng/ng_block_layout_algorithm_test.cc index a774fe4..5bc6198 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_block_layout_algorithm_test.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_block_layout_algorithm_test.cc
@@ -27,7 +27,7 @@ using ::testing::ElementsAre; using ::testing::Pointee; -RefPtr<NGConstraintSpace> ConstructConstraintSpace( +RefPtr<NGConstraintSpace> ConstructBlockLayoutTestConstraintSpace( NGWritingMode writing_mode, TextDirection direction, NGLogicalSize size, @@ -70,9 +70,9 @@ MinMaxContentSize RunComputeMinAndMax(NGBlockNode node) { // The constraint space is not used for min/max computation, but we need // it to create the algorithm. - RefPtr<NGConstraintSpace> space = - ConstructConstraintSpace(kHorizontalTopBottom, TextDirection::kLtr, - NGLogicalSize(LayoutUnit(), LayoutUnit())); + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( + kHorizontalTopBottom, TextDirection::kLtr, + NGLogicalSize(LayoutUnit(), LayoutUnit())); NGBlockLayoutAlgorithm algorithm(node, space.Get()); EXPECT_TRUE(algorithm.ComputeMinMaxContentSize().has_value()); @@ -118,7 +118,7 @@ <div id="box" style="width:30px; height:40px"></div> )HTML"); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(100), NGSizeIndefinite)); @@ -145,7 +145,7 @@ const int kMarginTop = 5; NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(100), NGSizeIndefinite)); @@ -189,9 +189,9 @@ const int kMarginLeft = 100; NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = - ConstructConstraintSpace(kHorizontalTopBottom, TextDirection::kLtr, - NGLogicalSize(LayoutUnit(500), LayoutUnit(500))); + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( + kHorizontalTopBottom, TextDirection::kLtr, + NGLogicalSize(LayoutUnit(500), LayoutUnit(500))); RefPtr<NGPhysicalBoxFragment> frag = RunBlockLayoutAlgorithm(space.Get(), container); @@ -605,9 +605,9 @@ const int kMarginTop = 40; NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = - ConstructConstraintSpace(kHorizontalTopBottom, TextDirection::kLtr, - NGLogicalSize(LayoutUnit(500), LayoutUnit(500))); + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( + kHorizontalTopBottom, TextDirection::kLtr, + NGLogicalSize(LayoutUnit(500), LayoutUnit(500))); RefPtr<NGPhysicalBoxFragment> frag = RunBlockLayoutAlgorithm(space.Get(), container); @@ -710,7 +710,7 @@ NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); @@ -747,7 +747,7 @@ NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(100), NGSizeIndefinite)); RefPtr<NGPhysicalBoxFragment> frag = @@ -779,7 +779,7 @@ NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(100), NGSizeIndefinite)); RefPtr<NGPhysicalBoxFragment> frag = @@ -1209,7 +1209,7 @@ NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(100), NGSizeIndefinite), true); RefPtr<NGPhysicalFragment> frag = @@ -1238,7 +1238,7 @@ )HTML"); NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); RefPtr<const NGPhysicalBoxFragment> parent_fragment = @@ -1272,7 +1272,7 @@ )HTML"); NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); RefPtr<const NGPhysicalBoxFragment> parent_fragment = @@ -1315,7 +1315,7 @@ )HTML"); NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); RefPtr<const NGPhysicalBoxFragment> parent_fragment = @@ -1358,7 +1358,7 @@ )HTML"); NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); RefPtr<const NGPhysicalBoxFragment> parent_fragment = @@ -1410,7 +1410,7 @@ )HTML"); NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); RefPtr<const NGPhysicalBoxFragment> parent_fragment = @@ -1471,7 +1471,7 @@ )HTML"); NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); RefPtr<const NGPhysicalBoxFragment> parent_fragment = @@ -1533,7 +1533,7 @@ )HTML"); NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); RefPtr<const NGPhysicalBoxFragment> parent_fragment = @@ -1597,7 +1597,7 @@ )HTML"); NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); RefPtr<const NGPhysicalBoxFragment> parent_fragment = @@ -1672,7 +1672,7 @@ )HTML"); NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); RefPtr<const NGPhysicalBoxFragment> parent_fragment = @@ -1718,7 +1718,7 @@ )HTML"); NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); RefPtr<const NGPhysicalBoxFragment> parent_fragment = @@ -1770,7 +1770,7 @@ )HTML"); NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); RefPtr<const NGPhysicalBoxFragment> parent_fragment = @@ -1967,7 +1967,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); NGBlockNode node(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true, kFragmentainerSpaceAvailable); @@ -1995,7 +1995,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); NGBlockNode node(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true, kFragmentainerSpaceAvailable); @@ -2041,7 +2041,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); NGBlockNode node(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true, kFragmentainerSpaceAvailable); @@ -2108,7 +2108,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); NGBlockNode node(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true, kFragmentainerSpaceAvailable); @@ -2173,7 +2173,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); NGBlockNode node(ToLayoutBox(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true, kFragmentainerSpaceAvailable); @@ -2239,7 +2239,7 @@ LayoutUnit kFragmentainerSpaceAvailable(150); NGBlockNode node(ToLayoutBlockFlow(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true, kFragmentainerSpaceAvailable); @@ -2263,7 +2263,7 @@ EXPECT_EQ(NGPhysicalSize(LayoutUnit(75), LayoutUnit(150)), child->Size()); EXPECT_EQ(NGPhysicalOffset(LayoutUnit(65), LayoutUnit(10)), child->Offset()); - space = ConstructConstraintSpace( + space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true, kFragmentainerSpaceAvailable); @@ -2321,7 +2321,7 @@ LayoutUnit kFragmentainerSpaceAvailable(150); NGBlockNode node(ToLayoutBlockFlow(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true, kFragmentainerSpaceAvailable); @@ -2371,7 +2371,7 @@ LayoutUnit kFragmentainerSpaceAvailable(150); NGBlockNode node(ToLayoutBlockFlow(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true, kFragmentainerSpaceAvailable); @@ -2390,7 +2390,7 @@ EXPECT_EQ(NGPhysicalSize(LayoutUnit(75), LayoutUnit(150)), child->Size()); EXPECT_EQ(NGPhysicalOffset(LayoutUnit(10), LayoutUnit(10)), child->Offset()); - space = ConstructConstraintSpace( + space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true, kFragmentainerSpaceAvailable); @@ -2494,7 +2494,7 @@ )HTML"); NGBlockNode node(ToLayoutBlockFlow(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite)); @@ -2533,7 +2533,7 @@ )HTML"); NGBlockNode node(ToLayoutBlockFlow(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true); @@ -2569,7 +2569,7 @@ )HTML"); NGBlockNode node(ToLayoutBlockFlow(GetLayoutObjectByElementId("container"))); - RefPtr<NGConstraintSpace> space = ConstructConstraintSpace( + RefPtr<NGConstraintSpace> space = ConstructBlockLayoutTestConstraintSpace( kHorizontalTopBottom, TextDirection::kLtr, NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true);
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_constraint_space_test.cc b/third_party/WebKit/Source/core/layout/ng/ng_constraint_space_test.cc index a3217b6..23b038f6 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_constraint_space_test.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_constraint_space_test.cc
@@ -13,7 +13,7 @@ namespace { -RefPtr<NGConstraintSpace> ConstructConstraintSpace( +RefPtr<NGConstraintSpace> ConstructTestConstraintSpace( NGWritingMode writing_mode, TextDirection direction, NGLogicalSize size, @@ -33,8 +33,8 @@ NGLogicalSize size; size.inline_size = LayoutUnit(600); size.block_size = LayoutUnit(400); - RefPtr<NGConstraintSpace> space = - ConstructConstraintSpace(kHorizontalTopBottom, TextDirection::kLtr, size); + RefPtr<NGConstraintSpace> space = ConstructTestConstraintSpace( + kHorizontalTopBottom, TextDirection::kLtr, size); NGLayoutOpportunityIterator iterator( space->Exclusions().get(), space->AvailableSize(), NGLogicalOffset()); @@ -50,8 +50,8 @@ size.inline_size = LayoutUnit(600); size.block_size = LayoutUnit(400); // Create a space with a 100x100 exclusion in the top right corner. - RefPtr<NGConstraintSpace> space = - ConstructConstraintSpace(kHorizontalTopBottom, TextDirection::kLtr, size); + RefPtr<NGConstraintSpace> space = ConstructTestConstraintSpace( + kHorizontalTopBottom, TextDirection::kLtr, size); NGExclusion exclusion; exclusion.rect.size = {LayoutUnit(100), LayoutUnit(100)}; exclusion.rect.offset = {LayoutUnit(500), LayoutUnit()}; @@ -77,8 +77,8 @@ size.inline_size = LayoutUnit(600); size.block_size = LayoutUnit(400); // Create a space with a 100x100 exclusion in the top left corner. - RefPtr<NGConstraintSpace> space = - ConstructConstraintSpace(kHorizontalTopBottom, TextDirection::kLtr, size); + RefPtr<NGConstraintSpace> space = ConstructTestConstraintSpace( + kHorizontalTopBottom, TextDirection::kLtr, size); NGExclusion exclusion; exclusion.rect.size = {LayoutUnit(100), LayoutUnit(100)}; space->AddExclusion(exclusion); @@ -126,8 +126,8 @@ NGLogicalSize size; size.inline_size = LayoutUnit(600); size.block_size = LayoutUnit(400); - RefPtr<NGConstraintSpace> space = - ConstructConstraintSpace(kHorizontalTopBottom, TextDirection::kLtr, size); + RefPtr<NGConstraintSpace> space = ConstructTestConstraintSpace( + kHorizontalTopBottom, TextDirection::kLtr, size); // Add exclusions NGExclusion exclusion1; exclusion1.rect.size = {LayoutUnit(100), LayoutUnit(100)}; @@ -189,8 +189,8 @@ // available constraint space, i.e. 0,0 600x200 TEST(NGConstraintSpaceTest, LayoutOpportunitiesWithOutOfBoundsExclusions) { NGLogicalSize size = {LayoutUnit(600), LayoutUnit(100)}; - RefPtr<NGConstraintSpace> space = - ConstructConstraintSpace(kHorizontalTopBottom, TextDirection::kLtr, size); + RefPtr<NGConstraintSpace> space = ConstructTestConstraintSpace( + kHorizontalTopBottom, TextDirection::kLtr, size); NGExclusion exclusion; exclusion.rect.size = {LayoutUnit(100), LayoutUnit(100)}; exclusion.rect.offset = {LayoutUnit(), LayoutUnit(150)}; @@ -208,9 +208,9 @@ // Verifies that we combine 2 adjoining left exclusions into one left exclusion. TEST(NGConstraintSpaceTest, TwoLeftExclusionsShadowEachOther) { NGLogicalOffset bfc_offset = {LayoutUnit(8), LayoutUnit(8)}; - RefPtr<NGConstraintSpace> space = - ConstructConstraintSpace(kHorizontalTopBottom, TextDirection::kLtr, - {LayoutUnit(200), LayoutUnit(200)}, bfc_offset); + RefPtr<NGConstraintSpace> space = ConstructTestConstraintSpace( + kHorizontalTopBottom, TextDirection::kLtr, + {LayoutUnit(200), LayoutUnit(200)}, bfc_offset); NGExclusion small_left; small_left.rect.size = {LayoutUnit(10), LayoutUnit(10)}; @@ -250,9 +250,9 @@ // exclusion. TEST(NGConstraintSpaceTest, TwoRightExclusionsShadowEachOther) { NGLogicalOffset bfc_offset = {LayoutUnit(8), LayoutUnit(8)}; - RefPtr<NGConstraintSpace> space = - ConstructConstraintSpace(kHorizontalTopBottom, TextDirection::kLtr, - {LayoutUnit(200), LayoutUnit(200)}, bfc_offset); + RefPtr<NGConstraintSpace> space = ConstructTestConstraintSpace( + kHorizontalTopBottom, TextDirection::kLtr, + {LayoutUnit(200), LayoutUnit(200)}, bfc_offset); NGExclusion small_right; small_right.rect.size = {LayoutUnit(10), LayoutUnit(10)};
diff --git a/third_party/WebKit/Source/core/page/PageOverlayTest.cpp b/third_party/WebKit/Source/core/page/PageOverlayTest.cpp index 84fdf70..022a602 100644 --- a/third_party/WebKit/Source/core/page/PageOverlayTest.cpp +++ b/third_party/WebKit/Source/core/page/PageOverlayTest.cpp
@@ -109,9 +109,9 @@ bool old_value_; }; -class MockCanvas : public SkCanvas { +class MockPageOverlayCanvas : public SkCanvas { public: - MockCanvas(int width, int height) : SkCanvas(width, height) {} + MockPageOverlayCanvas(int width, int height) : SkCanvas(width, height) {} MOCK_METHOD2(onDrawRect, void(const SkRect&, const SkPaint&)); }; @@ -128,7 +128,7 @@ // page overlay actually winds up getting drawn on top of the rest. // For now, we just check that the GraphicsLayer will draw the right thing. - MockCanvas canvas(kViewportWidth, kViewportHeight); + MockPageOverlayCanvas canvas(kViewportWidth, kViewportHeight); EXPECT_CALL(canvas, onDrawRect(_, _)).Times(AtLeast(0)); EXPECT_CALL(canvas, onDrawRect(SkRect::MakeWH(kViewportWidth, kViewportHeight),
diff --git a/third_party/WebKit/Source/core/page/PrintContextTest.cpp b/third_party/WebKit/Source/core/page/PrintContextTest.cpp index 69f59f7..d8a70e1 100644 --- a/third_party/WebKit/Source/core/page/PrintContextTest.cpp +++ b/third_party/WebKit/Source/core/page/PrintContextTest.cpp
@@ -27,7 +27,7 @@ const int kPageWidth = 800; const int kPageHeight = 600; -class MockCanvas : public SkCanvas { +class MockPageContextCanvas : public SkCanvas { public: enum OperationType { kDrawRect, kDrawPoint }; @@ -36,8 +36,8 @@ SkRect rect; }; - MockCanvas() : SkCanvas(kPageWidth, kPageHeight) {} - ~MockCanvas() override {} + MockPageContextCanvas() : SkCanvas(kPageWidth, kPageHeight) {} + ~MockPageContextCanvas() override {} void onDrawAnnotation(const SkRect& rect, const char key[], @@ -80,7 +80,7 @@ GetDocument().body()->setInnerHTML(body_content); } - void PrintSinglePage(MockCanvas& canvas) { + void PrintSinglePage(MockPageContextCanvas& canvas) { IntRect page_rect(0, 0, kPageWidth, kPageHeight); GetPrintContext().BeginPrintMode(page_rect.Width(), page_rect.Height()); GetDocument().View()->UpdateAllLifecyclePhases(); @@ -148,23 +148,24 @@ EXPECT_EQ(expectedHeight, actualRect.height()); TEST_F(PrintContextTest, LinkTarget) { - MockCanvas canvas; + MockPageContextCanvas canvas; SetBodyInnerHTML( AbsoluteBlockHtmlForLink(50, 60, 70, 80, "http://www.google.com") + AbsoluteBlockHtmlForLink(150, 160, 170, 180, "http://www.google.com#fragment")); PrintSinglePage(canvas); - const Vector<MockCanvas::Operation>& operations = canvas.RecordedOperations(); + const Vector<MockPageContextCanvas::Operation>& operations = + canvas.RecordedOperations(); ASSERT_EQ(2u, operations.size()); - EXPECT_EQ(MockCanvas::kDrawRect, operations[0].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[0].type); EXPECT_SKRECT_EQ(50, 60, 70, 80, operations[0].rect); - EXPECT_EQ(MockCanvas::kDrawRect, operations[1].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[1].type); EXPECT_SKRECT_EQ(150, 160, 170, 180, operations[1].rect); } TEST_F(PrintContextTest, LinkTargetUnderAnonymousBlockBeforeBlock) { - MockCanvas canvas; + MockPageContextCanvas canvas; SetBodyInnerHTML("<div style='padding-top: 50px'>" + InlineHtmlForLink("http://www.google.com", "<img style='width: 111; height: 10'>") + @@ -173,57 +174,61 @@ "<img style='width: 122; height: 20'>") + "</div>" + "</div>"); PrintSinglePage(canvas); - const Vector<MockCanvas::Operation>& operations = canvas.RecordedOperations(); + const Vector<MockPageContextCanvas::Operation>& operations = + canvas.RecordedOperations(); ASSERT_EQ(2u, operations.size()); - EXPECT_EQ(MockCanvas::kDrawRect, operations[0].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[0].type); EXPECT_SKRECT_EQ(0, 50, 111, 10, operations[0].rect); - EXPECT_EQ(MockCanvas::kDrawRect, operations[1].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[1].type); EXPECT_SKRECT_EQ(0, 60, 122, 20, operations[1].rect); } TEST_F(PrintContextTest, LinkTargetContainingABlock) { - MockCanvas canvas; + MockPageContextCanvas canvas; SetBodyInnerHTML( "<div style='padding-top: 50px'>" + InlineHtmlForLink("http://www.google2.com", "<div style='width:133; height: 30'>BLOCK</div>") + "</div>"); PrintSinglePage(canvas); - const Vector<MockCanvas::Operation>& operations = canvas.RecordedOperations(); + const Vector<MockPageContextCanvas::Operation>& operations = + canvas.RecordedOperations(); ASSERT_EQ(1u, operations.size()); - EXPECT_EQ(MockCanvas::kDrawRect, operations[0].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[0].type); EXPECT_SKRECT_EQ(0, 50, 133, 30, operations[0].rect); } TEST_F(PrintContextTest, LinkTargetUnderInInlines) { - MockCanvas canvas; + MockPageContextCanvas canvas; SetBodyInnerHTML( "<span><b><i><img style='width: 40px; height: 40px'><br>" + InlineHtmlForLink("http://www.google3.com", "<img style='width: 144px; height: 40px'>") + "</i></b></span>"); PrintSinglePage(canvas); - const Vector<MockCanvas::Operation>& operations = canvas.RecordedOperations(); + const Vector<MockPageContextCanvas::Operation>& operations = + canvas.RecordedOperations(); ASSERT_EQ(1u, operations.size()); - EXPECT_EQ(MockCanvas::kDrawRect, operations[0].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[0].type); EXPECT_SKRECT_EQ(0, 40, 144, 40, operations[0].rect); } TEST_F(PrintContextTest, LinkTargetUnderRelativelyPositionedInline) { - MockCanvas canvas; + MockPageContextCanvas canvas; SetBodyInnerHTML( + "<span style='position: relative; top: 50px; left: 50px'><b><i><img style='width: 1px; height: 40px'><br>" + InlineHtmlForLink("http://www.google3.com", "<img style='width: 155px; height: 50px'>") + "</i></b></span>"); PrintSinglePage(canvas); - const Vector<MockCanvas::Operation>& operations = canvas.RecordedOperations(); + const Vector<MockPageContextCanvas::Operation>& operations = + canvas.RecordedOperations(); ASSERT_EQ(1u, operations.size()); - EXPECT_EQ(MockCanvas::kDrawRect, operations[0].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[0].type); EXPECT_SKRECT_EQ(50, 90, 155, 50, operations[0].rect); } TEST_F(PrintContextTest, LinkTargetSvg) { - MockCanvas canvas; + MockPageContextCanvas canvas; SetBodyInnerHTML( "<svg width='100' height='100'>" "<a xlink:href='http://www.w3.org'><rect x='20' y='20' width='50' " @@ -233,17 +238,18 @@ "</svg>"); PrintSinglePage(canvas); - const Vector<MockCanvas::Operation>& operations = canvas.RecordedOperations(); + const Vector<MockPageContextCanvas::Operation>& operations = + canvas.RecordedOperations(); ASSERT_EQ(2u, operations.size()); - EXPECT_EQ(MockCanvas::kDrawRect, operations[0].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[0].type); EXPECT_SKRECT_EQ(20, 20, 50, 50, operations[0].rect); - EXPECT_EQ(MockCanvas::kDrawRect, operations[1].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[1].type); EXPECT_EQ(10, operations[1].rect.x()); EXPECT_GE(90, operations[1].rect.y()); } TEST_F(PrintContextTest, LinkedTarget) { - MockCanvas canvas; + MockPageContextCanvas canvas; GetDocument().SetBaseURLOverride(KURL(kParsedURLString, "http://a.com/")); SetBodyInnerHTML( AbsoluteBlockHtmlForLink( @@ -258,39 +264,42 @@ "fragment-not-used")); // Generates no annotation PrintSinglePage(canvas); - const Vector<MockCanvas::Operation>& operations = canvas.RecordedOperations(); + const Vector<MockPageContextCanvas::Operation>& operations = + canvas.RecordedOperations(); ASSERT_EQ(2u, operations.size()); - EXPECT_EQ(MockCanvas::kDrawRect, operations[0].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[0].type); EXPECT_SKRECT_EQ(50, 60, 70, 80, operations[0].rect); - EXPECT_EQ(MockCanvas::kDrawPoint, operations[1].type); + EXPECT_EQ(MockPageContextCanvas::kDrawPoint, operations[1].type); EXPECT_SKRECT_EQ(250, 260, 0, 0, operations[1].rect); } TEST_F(PrintContextTest, EmptyLinkedTarget) { - MockCanvas canvas; + MockPageContextCanvas canvas; GetDocument().SetBaseURLOverride(KURL(kParsedURLString, "http://a.com/")); SetBodyInnerHTML(AbsoluteBlockHtmlForLink(50, 60, 70, 80, "#fragment") + HtmlForAnchor(250, 260, "fragment", "")); PrintSinglePage(canvas); - const Vector<MockCanvas::Operation>& operations = canvas.RecordedOperations(); + const Vector<MockPageContextCanvas::Operation>& operations = + canvas.RecordedOperations(); ASSERT_EQ(2u, operations.size()); - EXPECT_EQ(MockCanvas::kDrawRect, operations[0].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[0].type); EXPECT_SKRECT_EQ(50, 60, 70, 80, operations[0].rect); - EXPECT_EQ(MockCanvas::kDrawPoint, operations[1].type); + EXPECT_EQ(MockPageContextCanvas::kDrawPoint, operations[1].type); EXPECT_SKRECT_EQ(250, 260, 0, 0, operations[1].rect); } TEST_F(PrintContextTest, LinkTargetBoundingBox) { - MockCanvas canvas; + MockPageContextCanvas canvas; SetBodyInnerHTML( AbsoluteBlockHtmlForLink(50, 60, 70, 20, "http://www.google.com", "<img style='width: 200px; height: 100px'>")); PrintSinglePage(canvas); - const Vector<MockCanvas::Operation>& operations = canvas.RecordedOperations(); + const Vector<MockPageContextCanvas::Operation>& operations = + canvas.RecordedOperations(); ASSERT_EQ(1u, operations.size()); - EXPECT_EQ(MockCanvas::kDrawRect, operations[0].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[0].type); EXPECT_SKRECT_EQ(50, 60, 200, 100, operations[0].rect); } @@ -307,14 +316,15 @@ AbsoluteBlockHtmlForLink(250, 260, 270, 280, "http://www.google.com#fragment")); - MockCanvas canvas; + MockPageContextCanvas canvas; PrintSinglePage(canvas); - const Vector<MockCanvas::Operation>& operations = canvas.RecordedOperations(); + const Vector<MockPageContextCanvas::Operation>& operations = + canvas.RecordedOperations(); ASSERT_EQ(2u, operations.size()); - EXPECT_EQ(MockCanvas::kDrawRect, operations[0].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[0].type); EXPECT_SKRECT_EQ(250, 260, 170, 180, operations[0].rect); - EXPECT_EQ(MockCanvas::kDrawRect, operations[1].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[1].type); EXPECT_SKRECT_EQ(350, 360, 270, 280, operations[1].rect); } @@ -336,17 +346,18 @@ ChildDocument().domWindow()->scrollTo(100, 100); - MockCanvas canvas; + MockPageContextCanvas canvas; PrintSinglePage(canvas); - const Vector<MockCanvas::Operation>& operations = canvas.RecordedOperations(); + const Vector<MockPageContextCanvas::Operation>& operations = + canvas.RecordedOperations(); ASSERT_EQ(3u, operations.size()); - EXPECT_EQ(MockCanvas::kDrawRect, operations[0].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[0].type); EXPECT_SKRECT_EQ(50, 60, 70, 80, operations[0].rect); // FIXME: the rect should be clipped. - EXPECT_EQ(MockCanvas::kDrawRect, operations[1].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[1].type); EXPECT_SKRECT_EQ(150, 160, 170, 180, operations[1].rect); - EXPECT_EQ(MockCanvas::kDrawRect, operations[2].type); + EXPECT_EQ(MockPageContextCanvas::kDrawRect, operations[2].type); EXPECT_SKRECT_EQ(250, 260, 270, 280, operations[2].rect); }
diff --git a/third_party/WebKit/Source/core/paint/LinkHighlightImplTest.cpp b/third_party/WebKit/Source/core/paint/LinkHighlightImplTest.cpp index 7bcdd4c3..a8dae73b 100644 --- a/third_party/WebKit/Source/core/paint/LinkHighlightImplTest.cpp +++ b/third_party/WebKit/Source/core/paint/LinkHighlightImplTest.cpp
@@ -66,7 +66,7 @@ .TargetGestureEvent(scaled_event, true); } -std::string RegisterMockedURLLoad() { +std::string LinkRegisterMockedURLLoad() { WebURL url = URLTestHelpers::RegisterMockedURLLoadFromBase( WebString::FromUTF8("http://www.test.com/"), testing::CoreTestDataPath(), WebString::FromUTF8("test_touch_link_highlight.html")); @@ -76,7 +76,7 @@ } // namespace TEST(LinkHighlightImplTest, verifyWebViewImplIntegration) { - const std::string url = RegisterMockedURLLoad(); + const std::string url = LinkRegisterMockedURLLoad(); FrameTestHelpers::WebViewHelper web_view_helper; WebViewBase* web_view_impl = web_view_helper.InitializeAndLoad(url); int page_width = 640; @@ -133,7 +133,7 @@ } TEST(LinkHighlightImplTest, resetDuringNodeRemoval) { - const std::string url = RegisterMockedURLLoad(); + const std::string url = LinkRegisterMockedURLLoad(); FrameTestHelpers::WebViewHelper web_view_helper; WebViewBase* web_view_impl = web_view_helper.InitializeAndLoad(url); @@ -173,7 +173,7 @@ // A lifetime test: delete LayerTreeView while running LinkHighlights. TEST(LinkHighlightImplTest, resetLayerTreeView) { - const std::string url = RegisterMockedURLLoad(); + const std::string url = LinkRegisterMockedURLLoad(); FrameTestHelpers::WebViewHelper web_view_helper; WebViewBase* web_view_impl = web_view_helper.InitializeAndLoad(url); @@ -208,7 +208,7 @@ } TEST(LinkHighlightImplTest, multipleHighlights) { - const std::string url = RegisterMockedURLLoad(); + const std::string url = LinkRegisterMockedURLLoad(); FrameTestHelpers::WebViewHelper web_view_helper; WebViewBase* web_view_impl = web_view_helper.InitializeAndLoad(url);
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerScrollableAreaTest.cpp b/third_party/WebKit/Source/core/paint/PaintLayerScrollableAreaTest.cpp index 3d2a99f..9ac0fbb9 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerScrollableAreaTest.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerScrollableAreaTest.cpp
@@ -19,7 +19,7 @@ namespace blink { namespace { -class MockChromeClient : public EmptyChromeClient { +class ScrollableAreaMockChromeClient : public EmptyChromeClient { public: MOCK_METHOD3(MockSetToolTip, void(LocalFrame*, const String&, TextDirection)); void SetToolTip(LocalFrame& frame, @@ -35,13 +35,15 @@ public: PaintLayerScrollableAreaTest() : RenderingTest(EmptyLocalFrameClient::Create()), - chrome_client_(new MockChromeClient) {} + chrome_client_(new ScrollableAreaMockChromeClient) {} ~PaintLayerScrollableAreaTest() { ::testing::Mock::VerifyAndClearExpectations(&GetChromeClient()); } - MockChromeClient& GetChromeClient() const override { return *chrome_client_; } + ScrollableAreaMockChromeClient& GetChromeClient() const override { + return *chrome_client_; + } BackgroundPaintLocation GetBackgroundPaintLocation(const char* element_id) { PaintLayer* paint_layer = @@ -55,7 +57,7 @@ EnableCompositing(); } - Persistent<MockChromeClient> chrome_client_; + Persistent<ScrollableAreaMockChromeClient> chrome_client_; }; TEST_F(PaintLayerScrollableAreaTest,
diff --git a/third_party/WebKit/Source/platform/fonts/FontCache.cpp b/third_party/WebKit/Source/platform/fonts/FontCache.cpp index 0dc5a27..ca0d7dae 100644 --- a/third_party/WebKit/Source/platform/fonts/FontCache.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontCache.cpp
@@ -62,8 +62,6 @@ #include "public/platform/Platform.h" #include "ui/gfx/font_list.h" -using namespace WTF; - namespace blink { #if !defined(OS_WIN) && !defined(OS_LINUX) @@ -413,11 +411,11 @@ } FontDescription font_description_copy = *font_description; - debug::Alias(&font_description_copy); + WTF::debug::Alias(&font_description_copy); - debug::Alias(&font_cache); - debug::Alias(&font_mgr); - debug::Alias(&num_families); + WTF::debug::Alias(&font_cache); + WTF::debug::Alias(&font_mgr); + WTF::debug::Alias(&num_families); CHECK(false); }
diff --git a/third_party/WebKit/Source/platform/fonts/UTF16TextIterator.cpp b/third_party/WebKit/Source/platform/fonts/UTF16TextIterator.cpp index 70d0b31..9baf5bb 100644 --- a/third_party/WebKit/Source/platform/fonts/UTF16TextIterator.cpp +++ b/third_party/WebKit/Source/platform/fonts/UTF16TextIterator.cpp
@@ -23,9 +23,6 @@ #include "platform/fonts/UTF16TextIterator.h" -using namespace WTF; -using namespace Unicode; - namespace blink { UTF16TextIterator::UTF16TextIterator(const UChar* characters, int length) @@ -56,7 +53,7 @@ DCHECK(U16_IS_SURROGATE(character)); if (!IsValidSurrogatePair(character)) { - character = kReplacementCharacter; + character = WTF::Unicode::kReplacementCharacter; return true; }
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc index b232649..5991d5e 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc
@@ -1131,9 +1131,6 @@ break; case UseCase::NONE: - new_policy.compositor_queue_policy().priority = - main_thread_compositing_is_fast ? TaskQueue::HIGH_PRIORITY - : TaskQueue::NORMAL_PRIORITY; // It's only safe to block tasks that if we are expecting a compositor // driven gesture. if (touchstart_expected_soon &&
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc index 7b3e594..ba1cd50 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc
@@ -854,9 +854,9 @@ EnableIdleTasks(); RunUntilIdle(); EXPECT_THAT(run_order, - ::testing::ElementsAre(std::string("C1"), std::string("C2"), - std::string("L1"), std::string("D1"), - std::string("D2"), std::string("I1"))); + ::testing::ElementsAre(std::string("L1"), std::string("D1"), + std::string("C1"), std::string("D2"), + std::string("C2"), std::string("I1"))); EXPECT_EQ(RendererSchedulerImpl::UseCase::NONE, CurrentUseCase()); } @@ -2427,7 +2427,7 @@ EnableIdleTasks(); RunUntilIdle(); EXPECT_THAT(run_order, - ::testing::ElementsAre(std::string("C1"), std::string("D1"), + ::testing::ElementsAre(std::string("D1"), std::string("C1"), std::string("I1"))); // The rest queued tasks fire when the tab goes foregrounded. @@ -2459,7 +2459,7 @@ EnableIdleTasks(); RunUntilIdle(); EXPECT_THAT(run_order, - ::testing::ElementsAre(std::string("C1"), std::string("D1"), + ::testing::ElementsAre(std::string("D1"), std::string("C1"), std::string("I1"))); // The rest queued tasks fire when the renderer is resumed. @@ -2477,7 +2477,7 @@ EnableIdleTasks(); RunUntilIdle(); EXPECT_THAT(run_order, - ::testing::ElementsAre(std::string("C2"), std::string("D2"), + ::testing::ElementsAre(std::string("D2"), std::string("C2"), std::string("I2"))); // The rest queued tasks fire when the renderer is resumed.
diff --git a/third_party/WebKit/Source/web/BUILD.gn b/third_party/WebKit/Source/web/BUILD.gn index 8cd83c2..3f18b26 100644 --- a/third_party/WebKit/Source/web/BUILD.gn +++ b/third_party/WebKit/Source/web/BUILD.gn
@@ -45,8 +45,6 @@ "WebExport.h", "WebFactoryImpl.cpp", "WebFactoryImpl.h", - "WebFrameWidgetImpl.cpp", - "WebFrameWidgetImpl.h", "WebKit.cpp", "WebLocalFrameImpl.cpp", "WebLocalFrameImpl.h",
diff --git a/third_party/WebKit/Source/web/ChromeClientImpl.cpp b/third_party/WebKit/Source/web/ChromeClientImpl.cpp index 36377f5c..cf36ed93 100644 --- a/third_party/WebKit/Source/web/ChromeClientImpl.cpp +++ b/third_party/WebKit/Source/web/ChromeClientImpl.cpp
@@ -48,6 +48,7 @@ #include "core/frame/Settings.h" #include "core/frame/UseCounter.h" #include "core/frame/VisualViewport.h" +#include "core/frame/WebFrameWidgetImpl.h" #include "core/fullscreen/Fullscreen.h" #include "core/html/HTMLInputElement.h" #include "core/html/forms/ColorChooser.h" @@ -109,7 +110,6 @@ #include "public/web/WebUserGestureToken.h" #include "public/web/WebViewClient.h" #include "public/web/WebWindowFeatures.h" -#include "web/WebFrameWidgetImpl.h" #include "web/WebLocalFrameImpl.h" namespace blink {
diff --git a/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp b/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp index dfd05b91..355d863 100644 --- a/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp +++ b/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp
@@ -141,6 +141,7 @@ #include "core/frame/SuspendableScriptExecutor.h" #include "core/frame/UseCounter.h" #include "core/frame/VisualViewport.h" +#include "core/frame/WebFrameWidgetImpl.h" #include "core/html/HTMLAnchorElement.h" #include "core/html/HTMLCollection.h" #include "core/html/HTMLFormElement.h" @@ -233,7 +234,6 @@ #include "public/web/WebSerializedScriptValue.h" #include "public/web/WebTreeScopeType.h" #include "skia/ext/platform_canvas.h" -#include "web/WebFrameWidgetImpl.h" namespace blink {
diff --git a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp index 557e08a9..5b1cf1a 100644 --- a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp
@@ -199,18 +199,6 @@ EXPECT_EQ(expected.Height(), actual.Height()); \ } while (false) -#define EXPECT_SIZE_EQ(expected, actual) \ - do { \ - EXPECT_EQ(expected.Width(), actual.Width()); \ - EXPECT_EQ(expected.Height(), actual.Height()); \ - } while (false) - -#define EXPECT_FLOAT_POINT_EQ(expected, actual) \ - do { \ - EXPECT_FLOAT_EQ(expected.x(), actual.x()); \ - EXPECT_FLOAT_EQ(expected.y(), actual.y()); \ - } while (false) - class WebFrameTest : public ::testing::Test { protected: WebFrameTest()
diff --git a/tools/perf/benchmarks/v8_browsing.py b/tools/perf/benchmarks/v8_browsing.py index d8b40ed..0700085 100644 --- a/tools/perf/benchmarks/v8_browsing.py +++ b/tools/perf/benchmarks/v8_browsing.py
@@ -126,10 +126,15 @@ # V8 categories. 'blink.console', 'disabled-by-default-v8.gc', + 'disabled-by-default-v8.compile', 'renderer.scheduler', 'v8', 'webkit.console', 'disabled-by-default-v8.runtime_stats', + # TODO(crbug.com/616441, primiano): Remove this temporary workaround, + # which enables memory-infra V8 code stats in V8 code size benchmarks + # only (to not slow down detailed memory dumps in other benchmarks). + 'disabled-by-default-memory-infra.v8.code_stats', ] options = timeline_based_measurement.Options( chrome_trace_category_filter.ChromeTraceCategoryFilter( @@ -141,7 +146,8 @@ options.config.chrome_trace_config.SetMemoryDumpConfig(memory_dump_config) options.SetTimelineBasedMetrics([ - 'expectedQueueingTimeMetric', 'runtimeStatsTotalMetric', 'gcMetric']) + 'expectedQueueingTimeMetric', 'runtimeStatsTotalMetric', 'gcMetric', + 'memoryMetric']) return options
diff --git a/tools/perf/page_sets/data/.gitignore b/tools/perf/page_sets/data/.gitignore index 049319d..0b32beb 100644 --- a/tools/perf/page_sets/data/.gitignore +++ b/tools/perf/page_sets/data/.gitignore
@@ -1,2 +1 @@ -credentials.json -debug_credentials.json +*credentials.json
diff --git a/tools/perf/page_sets/data/chrome_signin_credentials.json b/tools/perf/page_sets/data/chrome_signin_credentials.json deleted file mode 100644 index 1f180cc..0000000 --- a/tools/perf/page_sets/data/chrome_signin_credentials.json +++ /dev/null
@@ -1,6 +0,0 @@ -{ - "chrome": { - "username": "chrometelemetry@gmail.com", - "password": "signinfortelemetry" - } -}
diff --git a/ui/webui/resources/html/md_select_css.html b/ui/webui/resources/html/md_select_css.html index 22d029d..2128ad5 100644 --- a/ui/webui/resources/html/md_select_css.html +++ b/ui/webui/resources/html/md_select_css.html
@@ -58,6 +58,7 @@ -webkit-margin-start: var(--md-select-side-padding); border-top: 1px solid var(--paper-grey-300); display: block; + height: 0; margin-bottom: 0; margin-top: 0; }