diff --git a/.gn b/.gn index a336834..b6a59c3 100644 --- a/.gn +++ b/.gn
@@ -209,6 +209,7 @@ "//build/config/ios/ios_sdk.gni", "//build/config/linux/BUILD.gn", "//build/config/linux/pkg_config.gni", + "//build/config/linux/atk/BUILD.gn", "//build/config/mac/mac_sdk.gni", "//build/config/posix/BUILD.gn", "//build/config/sysroot.gni",
diff --git a/BUILD.gn b/BUILD.gn index d89ba2c..284d100 100644 --- a/BUILD.gn +++ b/BUILD.gn
@@ -892,6 +892,24 @@ group("aura_builder") { } +if (is_android) { + group("optimize_gn_gen") { + deps = [ + # These run expensive scripts in non-default toolchains. Generally, host + # toolchain targets are loaded in the later part of the run, and the + # result is they push out the end of generation. By preloading these, the + # scripts can be parallelized with the rest of the load. + "//build/config/linux(//build/toolchain/linux:clang_x64)", + "//build/config/posix(//build/toolchain/linux:clang_x64)", + + # Include x86 toolchains as well since V8 uses them for 32-bit snapshot + # generation. + "//build/config/linux(//build/toolchain/linux:clang_x86)", + "//build/config/posix(//build/toolchain/linux:clang_x86)", + ] + } +} + # Because of the source assignment filter, many targets end up over-filtering # their sources if the output directory contains a platform name. Assert that # this doesn't happen. http://crbug.com/548283
diff --git a/DEPS b/DEPS index 8665384..23f6884 100644 --- a/DEPS +++ b/DEPS
@@ -39,11 +39,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': 'c4ce72fc15b109c40ad5ba46b06a17209b2a750e', + 'skia_revision': '27c565adbed6364550f77dea52af71f09b8d7e7c', # 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': '2b166190d1a52f07e779c7005d82216dceaff91a', + 'v8_revision': 'eeafcb65b504c3e24b2c2b7ec6784d1e6f4ae628', # 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.
diff --git a/android_webview/java/src/org/chromium/android_webview/AwGLFunctor.java b/android_webview/java/src/org/chromium/android_webview/AwGLFunctor.java index 0d681e6..06468ec 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwGLFunctor.java +++ b/android_webview/java/src/org/chromium/android_webview/AwGLFunctor.java
@@ -7,6 +7,7 @@ import android.graphics.Canvas; import android.view.ViewGroup; +import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.content.common.CleanupReference; @@ -19,7 +20,7 @@ * the render node hierarchy. */ @JNINamespace("android_webview") -class AwGLFunctor { +public class AwGLFunctor { private static final class DestroyRunnable implements Runnable { private final long mNativeAwGLFunctor; @@ -96,10 +97,20 @@ return nativeGetAwDrawGLViewContext(mNativeAwGLFunctor); } + /** + * Intended for test code. + * @return the number of native instances of this class. + */ + @VisibleForTesting + public static int getNativeInstanceCount() { + return nativeGetNativeInstanceCount(); + } + private native void nativeDeleteHardwareRenderer(long nativeAwGLFunctor); private native long nativeGetAwDrawGLViewContext(long nativeAwGLFunctor); private static native long nativeGetAwDrawGLFunction(); private static native void nativeDestroy(long nativeAwGLFunctor); private static native long nativeCreate(AwGLFunctor javaProxy); + private static native int nativeGetNativeInstanceCount(); }
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/AwContentsGarbageCollectionTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/AwContentsGarbageCollectionTest.java index 1166cac..f3bfa7f 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/AwContentsGarbageCollectionTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/AwContentsGarbageCollectionTest.java
@@ -13,6 +13,7 @@ import android.test.suitebuilder.annotation.SmallTest; import org.chromium.android_webview.AwContents; +import org.chromium.android_webview.AwGLFunctor; import org.chromium.base.annotations.SuppressFBWarnings; import org.chromium.base.test.util.Feature; import org.chromium.content.browser.test.util.Criteria; @@ -237,8 +238,10 @@ return runTestOnUiThreadAndGetResult(new Callable<Boolean>() { @Override public Boolean call() { - int count = AwContents.getNativeInstanceCount(); - return count <= MAX_IDLE_INSTANCES; + int count_aw_contents = AwContents.getNativeInstanceCount(); + int count_aw_functor = AwGLFunctor.getNativeInstanceCount(); + return count_aw_contents <= MAX_IDLE_INSTANCES + && count_aw_functor <= MAX_IDLE_INSTANCES; } }); } catch (Exception e) {
diff --git a/android_webview/native/aw_gl_functor.cc b/android_webview/native/aw_gl_functor.cc index 7a6f0d7..ff7f3bd 100644 --- a/android_webview/native/aw_gl_functor.cc +++ b/android_webview/native/aw_gl_functor.cc
@@ -25,13 +25,23 @@ namespace android_webview { +namespace { +int g_instance_count = 0; +} + AwGLFunctor::AwGLFunctor(const JavaObjectWeakGlobalRef& java_ref) : java_ref_(java_ref), render_thread_manager_( this, - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI)) {} + BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI)) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + ++g_instance_count; +} -AwGLFunctor::~AwGLFunctor() {} +AwGLFunctor::~AwGLFunctor() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + --g_instance_count; +} bool AwGLFunctor::RequestInvokeGL(bool wait_for_completion) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -52,6 +62,7 @@ void AwGLFunctor::Destroy(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); java_ref_.reset(); delete this; } @@ -59,22 +70,31 @@ void AwGLFunctor::DeleteHardwareRenderer( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); render_thread_manager_.DeleteHardwareRendererOnUI(); } jlong AwGLFunctor::GetAwDrawGLViewContext( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); return reinterpret_cast<intptr_t>(&render_thread_manager_); } +static jint GetNativeInstanceCount(JNIEnv* env, const JavaParamRef<jclass>&) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + return g_instance_count; +} + static jlong GetAwDrawGLFunction(JNIEnv* env, const JavaParamRef<jclass>&) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); return reinterpret_cast<intptr_t>(&DrawGLFunction); } static jlong Create(JNIEnv* env, const JavaParamRef<jclass>&, const base::android::JavaParamRef<jobject>& obj) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); return reinterpret_cast<intptr_t>( new AwGLFunctor(JavaObjectWeakGlobalRef(env, obj))); }
diff --git a/android_webview/test/BUILD.gn b/android_webview/test/BUILD.gn index 77de0226..64bf134d 100644 --- a/android_webview/test/BUILD.gn +++ b/android_webview/test/BUILD.gn
@@ -209,6 +209,9 @@ # GYP: //android_webview/android_webview_tests.gypi:android_webview_unittests test("android_webview_unittests") { + # Tests do not require any data, but our dependencies pull a lot in. + ignore_all_data_deps = true + deps = [ ":android_webview_unittests_assets", ":android_webview_unittests_java",
diff --git a/ash/shell.cc b/ash/shell.cc index fc7270b..05c8bc8e 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -856,6 +856,10 @@ void Shell::Init(const ShellInitParams& init_params) { in_mus_ = init_params.in_mus; +#if defined(OS_LINUX) && !defined(OS_CHROMEOS) + DCHECK(in_mus_) << "linux desktop does not support ash."; +#endif + wm_globals_.reset(new wm::WmGlobalsAura); window_positioner_.reset(new WindowPositioner(wm_globals_.get()));
diff --git a/base/BUILD.gn b/base/BUILD.gn index 32f10d0..c4a3aee 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -1864,6 +1864,8 @@ "task_scheduler/sequence_sort_key_unittest.cc", "task_scheduler/sequence_unittest.cc", "task_scheduler/task_tracker_unittest.cc", + "task_scheduler/test_task_factory.cc", + "task_scheduler/test_task_factory.h", "task_scheduler/test_utils.h", "task_scheduler/utils_unittest.cc", "template_util_unittest.cc",
diff --git a/base/base.gyp b/base/base.gyp index d71d1a8..d627511 100644 --- a/base/base.gyp +++ b/base/base.gyp
@@ -555,6 +555,8 @@ 'task_scheduler/sequence_sort_key_unittest.cc', 'task_scheduler/sequence_unittest.cc', 'task_scheduler/task_tracker_unittest.cc', + 'task_scheduler/test_task_factory.cc', + 'task_scheduler/test_task_factory.h', 'task_scheduler/test_utils.h', 'task_scheduler/utils_unittest.cc', 'template_util_unittest.cc',
diff --git a/base/base_paths_android.cc b/base/base_paths_android.cc index ca58179..62b07dde 100644 --- a/base/base_paths_android.cc +++ b/base/base_paths_android.cc
@@ -23,10 +23,11 @@ case base::FILE_EXE: { char bin_dir[PATH_MAX + 1]; int bin_dir_size = readlink(kProcSelfExe, bin_dir, PATH_MAX); - if (bin_dir_size < 0 || bin_dir_size > PATH_MAX) { - NOTREACHED() << "Unable to resolve " << kProcSelfExe << "."; - return false; - } + // TODO(falken): This PCHECK is for debugging crbug.com/600226. + // Revert to NOTREACHED when the cause of the bug is understood. + PCHECK(bin_dir_size > 0 && bin_dir_size <= PATH_MAX) + << "Unable to resolve " << kProcSelfExe + << ". bin_dir_size=" << bin_dir_size; bin_dir[bin_dir_size] = 0; *result = FilePath(bin_dir); return true;
diff --git a/base/task_scheduler/scheduler_thread_pool_unittest.cc b/base/task_scheduler/scheduler_thread_pool_unittest.cc index 7e1ec5c..39c28ab4 100644 --- a/base/task_scheduler/scheduler_thread_pool_unittest.cc +++ b/base/task_scheduler/scheduler_thread_pool_unittest.cc
@@ -23,6 +23,7 @@ #include "base/task_scheduler/sequence.h" #include "base/task_scheduler/sequence_sort_key.h" #include "base/task_scheduler/task_tracker.h" +#include "base/task_scheduler/test_task_factory.h" #include "base/threading/platform_thread.h" #include "base/threading/simple_thread.h" #include "testing/gtest/include/gtest/gtest.h" @@ -71,141 +72,67 @@ DISALLOW_COPY_AND_ASSIGN(TaskSchedulerThreadPoolTest); }; -class TaskFactory { - public: - // Constructs a TaskFactory that posts tasks with |execution_mode| to - // |thread_pool|. - TaskFactory(SchedulerThreadPool* thread_pool, ExecutionMode execution_mode) - : cv_(&lock_), - task_runner_(thread_pool->CreateTaskRunnerWithTraits(TaskTraits(), - execution_mode)), - execution_mode_(execution_mode) {} - - // Posts a task through |task_runner_|. If |post_nested_task| is true, the - // task will post a new task when it runs. If |event| is set, the task will - // block until it is signaled. - void PostTestTask(bool post_nested_task, WaitableEvent* event) { - AutoLock auto_lock(lock_); - EXPECT_TRUE(task_runner_->PostTask( - FROM_HERE, - Bind(&TaskFactory::RunTaskCallback, Unretained(this), - num_created_tasks_++, post_nested_task, Unretained(event)))); - } - - // Waits for all tasks posted by PostTestTask() to start running. It is not - // guaranteed that the tasks have completed their execution when this returns. - void WaitForAllTasksToRun() const { - AutoLock auto_lock(lock_); - while (ran_tasks_.size() < num_created_tasks_) - cv_.Wait(); - } - - size_t NumRunTasks() const { - AutoLock auto_lock(lock_); - return ran_tasks_.size(); - } - - const TaskRunner* task_runner() const { return task_runner_.get(); } - - private: - void RunTaskCallback(size_t task_index, - bool post_nested_task, - WaitableEvent* event) { - if (post_nested_task) - PostTestTask(false, nullptr); - - EXPECT_TRUE(task_runner_->RunsTasksOnCurrentThread()); - - { - AutoLock auto_lock(lock_); - - if (execution_mode_ == ExecutionMode::SEQUENCED && - task_index != ran_tasks_.size()) { - ADD_FAILURE() << "A SEQUENCED task didn't run in the expected order."; - } - - if (ran_tasks_.find(task_index) != ran_tasks_.end()) - ADD_FAILURE() << "A task ran more than once."; - ran_tasks_.insert(task_index); - - cv_.Signal(); - } - - if (event) - event->Wait(); - } - - // Synchronizes access to all members below. - mutable Lock lock_; - - // Condition variable signaled when a task runs. - mutable ConditionVariable cv_; - - // Task runner through which this factory posts tasks. - const scoped_refptr<TaskRunner> task_runner_; - - // Execution mode of |task_runner_|. - const ExecutionMode execution_mode_; - - // Number of tasks posted by PostTestTask(). - size_t num_created_tasks_ = 0; - - // Indexes of tasks that ran. - std::unordered_set<size_t> ran_tasks_; - - DISALLOW_COPY_AND_ASSIGN(TaskFactory); -}; +using PostNestedTask = test::TestTaskFactory::PostNestedTask; class ThreadPostingTasks : public SimpleThread { public: + enum class WaitBeforePostTask { + NO_WAIT, + WAIT_FOR_ALL_THREADS_IDLE, + }; + // Constructs a thread that posts tasks to |thread_pool| through an - // |execution_mode| task runner. If |wait_for_all_threads_idle| is true, the - // thread wait until all worker threads in |thread_pool| are idle before - // posting a new task. If |post_nested_task| is true, each task posted by this - // thread posts another task when it runs. + // |execution_mode| task runner. If |wait_before_post_task| is + // WAIT_FOR_ALL_THREADS_IDLE, the thread waits until all worker threads in + // |thread_pool| are idle before posting a new task. If |post_nested_task| is + // YES, each task posted by this thread posts another task when it runs. ThreadPostingTasks(SchedulerThreadPool* thread_pool, ExecutionMode execution_mode, - bool wait_for_all_threads_idle, - bool post_nested_task) + WaitBeforePostTask wait_before_post_task, + PostNestedTask post_nested_task) : SimpleThread("ThreadPostingTasks"), thread_pool_(thread_pool), - wait_for_all_threads_idle_(wait_for_all_threads_idle), + wait_before_post_task_(wait_before_post_task), post_nested_task_(post_nested_task), - factory_(thread_pool_, execution_mode) { + factory_(thread_pool_->CreateTaskRunnerWithTraits(TaskTraits(), + execution_mode), + execution_mode) { DCHECK(thread_pool_); } - const TaskFactory* factory() const { return &factory_; } + const test::TestTaskFactory* factory() const { return &factory_; } private: void Run() override { EXPECT_FALSE(factory_.task_runner()->RunsTasksOnCurrentThread()); for (size_t i = 0; i < kNumTasksPostedPerThread; ++i) { - if (wait_for_all_threads_idle_) + if (wait_before_post_task_ == + WaitBeforePostTask::WAIT_FOR_ALL_THREADS_IDLE) { thread_pool_->WaitForAllWorkerThreadsIdleForTesting(); - factory_.PostTestTask(post_nested_task_, nullptr); + } + EXPECT_TRUE(factory_.PostTask(post_nested_task_, nullptr)); } } SchedulerThreadPool* const thread_pool_; const scoped_refptr<TaskRunner> task_runner_; - const bool wait_for_all_threads_idle_; - const bool post_nested_task_; - TaskFactory factory_; + const WaitBeforePostTask wait_before_post_task_; + const PostNestedTask post_nested_task_; + test::TestTaskFactory factory_; DISALLOW_COPY_AND_ASSIGN(ThreadPostingTasks); }; +using WaitBeforePostTask = ThreadPostingTasks::WaitBeforePostTask; + TEST_P(TaskSchedulerThreadPoolTest, PostTasks) { // Create threads to post tasks. std::vector<std::unique_ptr<ThreadPostingTasks>> threads_posting_tasks; for (size_t i = 0; i < kNumThreadsPostingTasks; ++i) { - const bool kWaitForAllThreadIdle = false; - const bool kPostNestedTasks = false; - threads_posting_tasks.push_back(WrapUnique( - new ThreadPostingTasks(thread_pool_.get(), GetParam(), - kWaitForAllThreadIdle, kPostNestedTasks))); + threads_posting_tasks.push_back(WrapUnique(new ThreadPostingTasks( + thread_pool_.get(), GetParam(), WaitBeforePostTask::NO_WAIT, + PostNestedTask::NO))); threads_posting_tasks.back()->Start(); } @@ -213,12 +140,10 @@ for (const auto& thread_posting_tasks : threads_posting_tasks) { thread_posting_tasks->Join(); thread_posting_tasks->factory()->WaitForAllTasksToRun(); - EXPECT_EQ(kNumTasksPostedPerThread, - thread_posting_tasks->factory()->NumRunTasks()); } // Wait until all worker threads are idle to be sure that no task accesses - // its TaskFactory after |thread_posting_tasks| is destroyed. + // its TestTaskFactory after |thread_posting_tasks| is destroyed. thread_pool_->WaitForAllWorkerThreadsIdleForTesting(); } @@ -228,11 +153,9 @@ // before posting a new task. std::vector<std::unique_ptr<ThreadPostingTasks>> threads_posting_tasks; for (size_t i = 0; i < kNumThreadsPostingTasks; ++i) { - const bool kWaitForAllThreadIdle = true; - const bool kPostNestedTasks = false; - threads_posting_tasks.push_back(WrapUnique( - new ThreadPostingTasks(thread_pool_.get(), GetParam(), - kWaitForAllThreadIdle, kPostNestedTasks))); + threads_posting_tasks.push_back(WrapUnique(new ThreadPostingTasks( + thread_pool_.get(), GetParam(), + WaitBeforePostTask::WAIT_FOR_ALL_THREADS_IDLE, PostNestedTask::NO))); threads_posting_tasks.back()->Start(); } @@ -240,12 +163,10 @@ for (const auto& thread_posting_tasks : threads_posting_tasks) { thread_posting_tasks->Join(); thread_posting_tasks->factory()->WaitForAllTasksToRun(); - EXPECT_EQ(kNumTasksPostedPerThread, - thread_posting_tasks->factory()->NumRunTasks()); } // Wait until all worker threads are idle to be sure that no task accesses - // its TaskFactory after |thread_posting_tasks| is destroyed. + // its TestTaskFactory after |thread_posting_tasks| is destroyed. thread_pool_->WaitForAllWorkerThreadsIdleForTesting(); } @@ -254,11 +175,9 @@ // another task when it runs. std::vector<std::unique_ptr<ThreadPostingTasks>> threads_posting_tasks; for (size_t i = 0; i < kNumThreadsPostingTasks; ++i) { - const bool kWaitForAllThreadIdle = false; - const bool kPostNestedTasks = true; - threads_posting_tasks.push_back(WrapUnique( - new ThreadPostingTasks(thread_pool_.get(), GetParam(), - kWaitForAllThreadIdle, kPostNestedTasks))); + threads_posting_tasks.push_back(WrapUnique(new ThreadPostingTasks( + thread_pool_.get(), GetParam(), WaitBeforePostTask::NO_WAIT, + PostNestedTask::YES))); threads_posting_tasks.back()->Start(); } @@ -266,12 +185,10 @@ for (const auto& thread_posting_tasks : threads_posting_tasks) { thread_posting_tasks->Join(); thread_posting_tasks->factory()->WaitForAllTasksToRun(); - EXPECT_EQ(2 * kNumTasksPostedPerThread, - thread_posting_tasks->factory()->NumRunTasks()); } // Wait until all worker threads are idle to be sure that no task accesses - // its TaskFactory after |thread_posting_tasks| is destroyed. + // its TestTaskFactory after |thread_posting_tasks| is destroyed. thread_pool_->WaitForAllWorkerThreadsIdleForTesting(); } @@ -280,26 +197,30 @@ // Use different factories so that tasks are added to different sequences and // can run simultaneously when the execution mode is SEQUENCED. WaitableEvent event(true, false); - std::vector<std::unique_ptr<TaskFactory>> blocked_task_factories; + std::vector<std::unique_ptr<test::TestTaskFactory>> blocked_task_factories; for (size_t i = 0; i < (kNumThreadsInThreadPool - 1); ++i) { - blocked_task_factories.push_back( - WrapUnique(new TaskFactory(thread_pool_.get(), GetParam()))); - blocked_task_factories.back()->PostTestTask(false, &event); + blocked_task_factories.push_back(WrapUnique(new test::TestTaskFactory( + thread_pool_->CreateTaskRunnerWithTraits(TaskTraits(), GetParam()), + GetParam()))); + EXPECT_TRUE( + blocked_task_factories.back()->PostTask(PostNestedTask::NO, &event)); blocked_task_factories.back()->WaitForAllTasksToRun(); } // Post |kNumTasksPostedPerThread| tasks that should all run despite the fact // that only one thread in |thread_pool_| isn't busy. - TaskFactory short_task_factory(thread_pool_.get(), GetParam()); + test::TestTaskFactory short_task_factory( + thread_pool_->CreateTaskRunnerWithTraits(TaskTraits(), GetParam()), + GetParam()); for (size_t i = 0; i < kNumTasksPostedPerThread; ++i) - short_task_factory.PostTestTask(false, nullptr); + EXPECT_TRUE(short_task_factory.PostTask(PostNestedTask::NO, nullptr)); short_task_factory.WaitForAllTasksToRun(); // Release tasks waiting on |event|. event.Signal(); // Wait until all worker threads are idle to be sure that no task accesses - // its TaskFactory after it is destroyed. + // its TestTaskFactory after it is destroyed. thread_pool_->WaitForAllWorkerThreadsIdleForTesting(); } @@ -309,11 +230,12 @@ // tasks are added to different sequences and can run simultaneously when the // execution mode is SEQUENCED. WaitableEvent event(true, false); - std::vector<std::unique_ptr<TaskFactory>> factories; + std::vector<std::unique_ptr<test::TestTaskFactory>> factories; for (size_t i = 0; i < kNumThreadsInThreadPool; ++i) { - factories.push_back( - WrapUnique(new TaskFactory(thread_pool_.get(), GetParam()))); - factories.back()->PostTestTask(false, &event); + factories.push_back(WrapUnique(new test::TestTaskFactory( + thread_pool_->CreateTaskRunnerWithTraits(TaskTraits(), GetParam()), + GetParam()))); + EXPECT_TRUE(factories.back()->PostTask(PostNestedTask::NO, &event)); factories.back()->WaitForAllTasksToRun(); } @@ -321,7 +243,7 @@ event.Signal(); // Wait until all worker threads are idle to be sure that no task accesses - // its TaskFactory after it is destroyed. + // its TestTaskFactory after it is destroyed. thread_pool_->WaitForAllWorkerThreadsIdleForTesting(); }
diff --git a/base/task_scheduler/test_task_factory.cc b/base/task_scheduler/test_task_factory.cc new file mode 100644 index 0000000..5edf3dd --- /dev/null +++ b/base/task_scheduler/test_task_factory.cc
@@ -0,0 +1,82 @@ +// 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 "base/task_scheduler/test_task_factory.h" + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/location.h" +#include "base/logging.h" +#include "base/synchronization/waitable_event.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace base { +namespace internal { +namespace test { + +TestTaskFactory::TestTaskFactory(scoped_refptr<TaskRunner> task_runner, + ExecutionMode execution_mode) + : cv_(&lock_), + task_runner_(std::move(task_runner)), + execution_mode_(execution_mode) { + // Detach |thread_checker_| from the current thread. It will be attached to + // the first thread that calls ThreadCheckerImpl::CalledOnValidThread(). + thread_checker_.DetachFromThread(); +} + +TestTaskFactory::~TestTaskFactory() { + WaitForAllTasksToRun(); +} + +bool TestTaskFactory::PostTask(PostNestedTask post_nested_task, + WaitableEvent* event) { + AutoLock auto_lock(lock_); + return task_runner_->PostTask( + FROM_HERE, + Bind(&TestTaskFactory::RunTaskCallback, Unretained(this), + num_posted_tasks_++, post_nested_task, Unretained(event))); +} + +void TestTaskFactory::WaitForAllTasksToRun() const { + AutoLock auto_lock(lock_); + while (ran_tasks_.size() < num_posted_tasks_) + cv_.Wait(); +} + +void TestTaskFactory::RunTaskCallback(size_t task_index, + PostNestedTask post_nested_task, + WaitableEvent* event) { + if (post_nested_task == PostNestedTask::YES) + PostTask(PostNestedTask::NO, nullptr); + + EXPECT_TRUE(task_runner_->RunsTasksOnCurrentThread()); + + { + AutoLock auto_lock(lock_); + + DCHECK_LE(task_index, num_posted_tasks_); + + if ((execution_mode_ == ExecutionMode::SINGLE_THREADED || + execution_mode_ == ExecutionMode::SEQUENCED) && + task_index != ran_tasks_.size()) { + ADD_FAILURE() << "A task didn't run in the expected order."; + } + + if (execution_mode_ == ExecutionMode::SINGLE_THREADED) + EXPECT_TRUE(thread_checker_.CalledOnValidThread()); + + if (ran_tasks_.find(task_index) != ran_tasks_.end()) + ADD_FAILURE() << "A task ran more than once."; + ran_tasks_.insert(task_index); + + cv_.Signal(); + } + + if (event) + event->Wait(); +} + +} // namespace test +} // namespace internal +} // namespace base
diff --git a/base/task_scheduler/test_task_factory.h b/base/task_scheduler/test_task_factory.h new file mode 100644 index 0000000..9a118822 --- /dev/null +++ b/base/task_scheduler/test_task_factory.h
@@ -0,0 +1,93 @@ +// 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 BASE_TASK_SCHEDULER_TEST_TASK_FACTORY_H_ +#define BASE_TASK_SCHEDULER_TEST_TASK_FACTORY_H_ + +#include <stddef.h> + +#include <unordered_set> + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/synchronization/condition_variable.h" +#include "base/synchronization/lock.h" +#include "base/task_runner.h" +#include "base/task_scheduler/task_traits.h" +#include "base/threading/thread_checker_impl.h" + +namespace base { + +class WaitableEvent; + +namespace internal { +namespace test { + +// A TestTaskFactory posts tasks to a TaskRunner and verifies that they run as +// expected. Generates a test failure when: +// - The ExecutionMode of the TaskRunner is SEQUENCED or SINGLE_THREADED and +// Tasks don't run in posting order. +// - The ExecutionMode of the TaskRunner is SINGLE_THREADED and Tasks don't +// run on the same thread. +// - A Task runs more than once. +class TestTaskFactory { + public: + enum class PostNestedTask { + YES, + NO, + }; + + // Constructs a TestTaskFactory that posts tasks to |task_runner|. + // |execution_mode| is the ExecutionMode of |task_runner|. + TestTaskFactory(scoped_refptr<TaskRunner> task_runner, + ExecutionMode execution_mode); + + ~TestTaskFactory(); + + // Posts a task. If |post_nested_task| is YES, the task will post a new task + // when it runs. If |event| is set, the task will block until it is signaled. + // Returns true if the task is posted. + bool PostTask(PostNestedTask post_nested_task, WaitableEvent* event); + + // Waits for all tasks posted by PostTask() to start running. It is not + // guaranteed that the tasks have completed their execution when this returns. + void WaitForAllTasksToRun() const; + + const TaskRunner* task_runner() const { return task_runner_.get(); } + + private: + void RunTaskCallback(size_t task_index, + PostNestedTask post_nested_task, + WaitableEvent* event); + + // Synchronizes access to all members. + mutable Lock lock_; + + // Condition variable signaled when a task runs. + mutable ConditionVariable cv_; + + // Task runner through which this factory posts tasks. + const scoped_refptr<TaskRunner> task_runner_; + + // Execution mode of |task_runner_|. + const ExecutionMode execution_mode_; + + // Number of tasks posted by PostTask(). + size_t num_posted_tasks_ = 0; + + // Indexes of tasks that ran. + std::unordered_set<size_t> ran_tasks_; + + // Used to verify that all tasks run on the same thread when |execution_mode_| + // is SINGLE_THREADED. + ThreadCheckerImpl thread_checker_; + + DISALLOW_COPY_AND_ASSIGN(TestTaskFactory); +}; + +} // namespace test +} // namespace internal +} // namespace base + +#endif // BASE_TASK_SCHEDULER_TEST_TASK_FACTORY_H_
diff --git a/build/android/pylib/gtest/gtest_test_instance.py b/build/android/pylib/gtest/gtest_test_instance.py index c21ef7b..282b81d2 100644 --- a/build/android/pylib/gtest/gtest_test_instance.py +++ b/build/android/pylib/gtest/gtest_test_instance.py
@@ -12,6 +12,7 @@ from pylib.constants import host_paths from pylib.base import base_test_result from pylib.base import test_instance +from pylib.utils import isolator with host_paths.SysPath(host_paths.BUILD_COMMON_PATH): import unittest_util # pylint: disable=import-error @@ -196,7 +197,8 @@ args.isolate_file_path = os.path.join( host_paths.DIR_SOURCE_ROOT, default_isolate_file_path) - if args.isolate_file_path: + if (args.isolate_file_path and + not isolator.IsIsolateEmpty(args.isolate_file_path)): self._isolate_abs_path = os.path.abspath(args.isolate_file_path) self._isolate_delegate = isolate_delegate self._isolated_abs_path = os.path.join(
diff --git a/build/android/pylib/instrumentation/instrumentation_test_instance.py b/build/android/pylib/instrumentation/instrumentation_test_instance.py index e9c33f1c..9f1e439 100644 --- a/build/android/pylib/instrumentation/instrumentation_test_instance.py +++ b/build/android/pylib/instrumentation/instrumentation_test_instance.py
@@ -17,6 +17,7 @@ from pylib.constants import host_paths from pylib.instrumentation import test_result from pylib.instrumentation import instrumentation_parser +from pylib.utils import isolator from pylib.utils import proguard with host_paths.SysPath(host_paths.BUILD_COMMON_PATH): @@ -292,7 +293,8 @@ def _initializeDataDependencyAttributes(self, args, isolate_delegate): self._data_deps = [] - if args.isolate_file_path: + if (args.isolate_file_path and + not isolator.IsIsolateEmpty(args.isolate_file_path)): if os.path.isabs(args.isolate_file_path): self._isolate_abs_path = args.isolate_file_path else:
diff --git a/build/android/pylib/utils/isolator.py b/build/android/pylib/utils/isolator.py index c1281ff..68faa38 100644 --- a/build/android/pylib/utils/isolator.py +++ b/build/android/pylib/utils/isolator.py
@@ -54,6 +54,12 @@ } +def IsIsolateEmpty(isolate_path): + """Returns whether there are no files in the .isolate.""" + with open(isolate_path) as f: + return "'files': []" in f.read() + + class Isolator(object): """Manages calls to isolate.py for the android test runner scripts."""
diff --git a/build/common.gypi b/build/common.gypi index 9368049d..74836e7 100644 --- a/build/common.gypi +++ b/build/common.gypi
@@ -3575,15 +3575,6 @@ ], }, }], - [ 'OS=="ios"', { - 'Archive': { - 'inherit_from': ['Common_Base', 'x86_Base', 'Release_Base'], - 'xcode_settings': { - 'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES', # -fvisibility=hidden - 'STRIP_INSTALLED_PRODUCT': 'YES', - }, - }, - }], [ 'OS=="win"', { # TODO(bradnelson): add a gyp mechanism to make this more graceful. 'Debug_x64': { @@ -5041,6 +5032,7 @@ # GCC_INLINES_ARE_PRIVATE_EXTERN maps to -fvisibility-inlines-hidden 'GCC_INLINES_ARE_PRIVATE_EXTERN': 'YES', 'GCC_OBJC_CALL_CXX_CDTORS': 'YES', # -fobjc-call-cxx-cdtors + 'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES', # -fvisibility=hidden 'GCC_THREADSAFE_STATICS': 'NO', # -fno-threadsafe-statics 'GCC_TREAT_WARNINGS_AS_ERRORS': 'YES', # -Werror 'GCC_VERSION': 'com.apple.compilers.llvm.clang.1_0', @@ -5129,20 +5121,6 @@ }], ], }], - ['OS=="mac"', { - 'xcode_settings': { - 'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES', # -fvisibility=hidden - }, - }], - ['OS=="ios"', { - 'xcode_settings': { - # XCTests inject a dynamic library into the application. If - # fvisibility is set to hidden, then some symbols needed by - # XCTests are not available. This setting is enabled for the - # Archive configuration. - 'GCC_SYMBOLS_PRIVATE_EXTERN': 'NO', - }, - }], ], 'target_conditions': [ ['_type!="static_library"', { @@ -5447,7 +5425,7 @@ 'Release_Base': { 'xcode_settings': { 'DEPLOYMENT_POSTPROCESSING': 'YES', - 'STRIP_INSTALLED_PRODUCT': 'NO', + 'STRIP_INSTALLED_PRODUCT': 'YES', 'conditions': [ ['buildtype=="Official"', { 'DEBUG_INFORMATION_FORMAT': 'dwarf-with-dsym',
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni index 3b60f66..a11f4a0 100644 --- a/build/config/android/internal_rules.gni +++ b/build/config/android/internal_rules.gni
@@ -2100,6 +2100,7 @@ depfile = "$target_gen_dir/$target_name.d" data_deps += [ "//build/android:test_runner_py" ] + data = [] test_runner_args = [ _test_type, @@ -2184,6 +2185,7 @@ } } if (defined(invoker.isolate_file)) { + data += [ invoker.isolate_file ] test_runner_args += [ "--isolate-file-path", rebase_path(invoker.isolate_file, root_build_dir), @@ -2214,9 +2216,7 @@ depfile, generated_script, ] - data = [ - generated_script, - ] + data += [ generated_script ] args = [ "--depfile",
diff --git a/build/config/linux/BUILD.gn b/build/config/linux/BUILD.gn index c0871f88..9e56b77 100644 --- a/build/config/linux/BUILD.gn +++ b/build/config/linux/BUILD.gn
@@ -3,9 +3,10 @@ # found in the LICENSE file. import("//build/config/linux/pkg_config.gni") -import("//build/config/features.gni") -import("//build/config/sysroot.gni") -import("//build/config/ui.gni") + +group("linux") { + visibility = [ "//:optimize_gn_gen" ] +} # This is included by reference in the //build/config/compiler config that # is applied to all targets. It is here to separate out the logic that is @@ -29,47 +30,9 @@ config("fontconfig") { visibility = [ "//build/linux:fontconfig" ] - libs = [ "fontconfig" ] } -pkg_config("freetype2") { - visibility = [ "//build/linux:freetype2" ] - - packages = [ "freetype2" ] -} - -pkg_config("glib") { - packages = [ - "glib-2.0", - "gmodule-2.0", - "gobject-2.0", - "gthread-2.0", - ] -} - -if (use_pango || use_cairo) { - pkg_config("pangocairo") { - packages = [ "pangocairo" ] - } -} - -if (use_pango) { - pkg_config("pangoft2") { - packages = [ "pangoft2" ] - } -} - -# Note: if your target also depends on //dbus, you don't need to add this -# config (it will get added automatically if you depend on //dbus). -pkg_config("dbus") { - packages = [ "dbus-1" ] -} - -pkg_config("libffi") { - packages = [ "libffi" ] -} - config("x11") { libs = [ "X11", @@ -120,41 +83,11 @@ libs = [ "resolv" ] } -# CrOS doesn't install GTK, gconf or any gnome packages. -if (!is_chromeos && use_gconf) { - # These packages should _only_ be expected when building for a target. - # If these extra checks are not run, gconf is required when building host - # tools for a CrOS build. - if (current_toolchain == default_toolchain) { - pkg_config("atk") { - packages = [ "atk" ] - atk_lib_dir = exec_script(pkg_config_script, - pkg_config_args + [ - "--libdir", - "atk", - ], - "string") - defines = [ "ATK_LIB_DIR=\"$atk_lib_dir\"" ] - } - - # gn orders flags on a target before flags from configs. The default config - # adds -Wall, and these flags have to be after -Wall -- so they need to - # come from a config and can't be on the target directly. - config("atk_warnings") { - cflags = [ - # glib uses the pre-c++11 typedef-as-static_assert hack. - "-Wno-unused-local-typedef", - - # G_DEFINE_TYPE automatically generates a *get_instance_private - # inline function after glib 2.37. That's unused. Prevent to - # complain about it. - "-Wno-unused-function", - ] - } - - pkg_config("gconf") { - packages = [ "gconf-2.0" ] - defines = [ "USE_GCONF" ] - } - } +pkg_config("glib") { + packages = [ + "glib-2.0", + "gmodule-2.0", + "gobject-2.0", + "gthread-2.0", + ] }
diff --git a/build/config/linux/atk/BUILD.gn b/build/config/linux/atk/BUILD.gn new file mode 100644 index 0000000..96bf8c0a --- /dev/null +++ b/build/config/linux/atk/BUILD.gn
@@ -0,0 +1,40 @@ +# 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. + +import("//build/config/features.gni") +import("//build/config/linux/pkg_config.gni") + +# CrOS doesn't install GTK, gconf or any gnome packages. +assert(!is_chromeos && use_gconf) + +# These packages should _only_ be expected when building for a target. +# If these extra checks are not run, gconf is required when building host +# tools for a CrOS build. +assert(current_toolchain == default_toolchain) + +pkg_config("atk") { + packages = [ "atk" ] + atk_lib_dir = exec_script(pkg_config_script, + pkg_config_args + [ + "--libdir", + "atk", + ], + "string") + defines = [ "ATK_LIB_DIR=\"$atk_lib_dir\"" ] +} + +# gn orders flags on a target before flags from configs. The default config +# adds -Wall, and these flags have to be after -Wall -- so they need to +# come from a config and can't be on the target directly. +config("warnings") { + cflags = [ + # glib uses the pre-c++11 typedef-as-static_assert hack. + "-Wno-unused-local-typedef", + + # G_DEFINE_TYPE automatically generates a *get_instance_private + # inline function after glib 2.37. That's unused. Prevent to + # complain about it. + "-Wno-unused-function", + ] +}
diff --git a/build/config/linux/dbus/BUILD.gn b/build/config/linux/dbus/BUILD.gn new file mode 100644 index 0000000..a26ca92 --- /dev/null +++ b/build/config/linux/dbus/BUILD.gn
@@ -0,0 +1,11 @@ +# 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. + +import("//build/config/linux/pkg_config.gni") + +# Note: if your target also depends on //dbus, you don't need to add this +# config (it will get added automatically if you depend on //dbus). +pkg_config("dbus") { + packages = [ "dbus-1" ] +}
diff --git a/build/config/linux/gconf/BUILD.gn b/build/config/linux/gconf/BUILD.gn new file mode 100644 index 0000000..262e96a --- /dev/null +++ b/build/config/linux/gconf/BUILD.gn
@@ -0,0 +1,19 @@ +# 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. + +import("//build/config/features.gni") +import("//build/config/linux/pkg_config.gni") + +# CrOS doesn't install GTK, gconf or any gnome packages. +assert(!is_chromeos && use_gconf) + +# These packages should _only_ be expected when building for a target. +# If these extra checks are not run, gconf is required when building host +# tools for a CrOS build. +assert(current_toolchain == default_toolchain) + +pkg_config("gconf") { + packages = [ "gconf-2.0" ] + defines = [ "USE_GCONF" ] +}
diff --git a/build/config/linux/libffi/BUILD.gn b/build/config/linux/libffi/BUILD.gn new file mode 100644 index 0000000..a404172 --- /dev/null +++ b/build/config/linux/libffi/BUILD.gn
@@ -0,0 +1,9 @@ +# 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. + +import("//build/config/linux/pkg_config.gni") + +pkg_config("libffi") { + packages = [ "libffi" ] +}
diff --git a/build/config/linux/pangocairo/BUILD.gn b/build/config/linux/pangocairo/BUILD.gn new file mode 100644 index 0000000..727b52d5 --- /dev/null +++ b/build/config/linux/pangocairo/BUILD.gn
@@ -0,0 +1,9 @@ +# 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. + +import("//build/config/linux/pkg_config.gni") + +pkg_config("pangocairo") { + packages = [ "pangocairo" ] +}
diff --git a/build/config/posix/BUILD.gn b/build/config/posix/BUILD.gn index e862c50..fc5dd43 100644 --- a/build/config/posix/BUILD.gn +++ b/build/config/posix/BUILD.gn
@@ -6,6 +6,10 @@ assert(is_posix) +group("posix") { + visibility = [ "//:optimize_gn_gen" ] +} + # This is included by reference in the //build/config/compiler:runtime_library # config that is applied to all targets. It is here to separate out the logic # that is Posix-only. Please see that target for advice on what should go in
diff --git a/build/linux/BUILD.gn b/build/linux/BUILD.gn index 97428b4..a44c117 100644 --- a/build/linux/BUILD.gn +++ b/build/linux/BUILD.gn
@@ -115,6 +115,13 @@ } } +if (!is_chromecast) { + pkg_config("freetype2_config") { + visibility = [ ":freetype2" ] + packages = [ "freetype2" ] + } +} + group("freetype2") { if (is_chromecast) { # Chromecast platform doesn't provide freetype, so use Chromium's. @@ -123,6 +130,6 @@ "//third_party/freetype-android:freetype", ] } else { - public_configs = [ "//build/config/linux:freetype2" ] + public_configs = [ ":freetype2_config" ] } }
diff --git a/cc/BUILD.gn b/cc/BUILD.gn index d369260..fd1e9c8 100644 --- a/cc/BUILD.gn +++ b/cc/BUILD.gn
@@ -922,9 +922,11 @@ ] configs += [ "//build/config:precompiled_headers" ] - data = [ - "test/data/", - ] + if (!is_android) { + data = [ + "test/data/", + ] + } deps = [ ":cc",
diff --git a/cc/debug/debug_rect_history.cc b/cc/debug/debug_rect_history.cc index f89b9f77..53381cf 100644 --- a/cc/debug/debug_rect_history.cc +++ b/cc/debug/debug_rect_history.cc
@@ -160,8 +160,7 @@ void DebugRectHistory::SaveTouchEventHandlerRects(LayerTreeImpl* tree_impl) { LayerTreeHostCommon::CallFunctionForEveryLayer( tree_impl, - [this](LayerImpl* layer) { SaveTouchEventHandlerRectsCallback(layer); }, - CallFunctionLayerType::ALL_LAYERS); + [this](LayerImpl* layer) { SaveTouchEventHandlerRectsCallback(layer); }); } void DebugRectHistory::SaveTouchEventHandlerRectsCallback(LayerImpl* layer) { @@ -200,8 +199,7 @@ void DebugRectHistory::SaveScrollEventHandlerRects(LayerTreeImpl* tree_impl) { LayerTreeHostCommon::CallFunctionForEveryLayer( tree_impl, - [this](LayerImpl* layer) { SaveScrollEventHandlerRectsCallback(layer); }, - CallFunctionLayerType::ALL_LAYERS); + [this](LayerImpl* layer) { SaveScrollEventHandlerRectsCallback(layer); }); } void DebugRectHistory::SaveScrollEventHandlerRectsCallback(LayerImpl* layer) { @@ -217,8 +215,7 @@ void DebugRectHistory::SaveNonFastScrollableRects(LayerTreeImpl* tree_impl) { LayerTreeHostCommon::CallFunctionForEveryLayer( tree_impl, - [this](LayerImpl* layer) { SaveNonFastScrollableRectsCallback(layer); }, - CallFunctionLayerType::ALL_LAYERS); + [this](LayerImpl* layer) { SaveNonFastScrollableRectsCallback(layer); }); } void DebugRectHistory::SaveNonFastScrollableRectsCallback(LayerImpl* layer) {
diff --git a/cc/debug/invalidation_benchmark.cc b/cc/debug/invalidation_benchmark.cc index c6f0a4f5..681e29e 100644 --- a/cc/debug/invalidation_benchmark.cc +++ b/cc/debug/invalidation_benchmark.cc
@@ -65,8 +65,7 @@ void InvalidationBenchmark::DidUpdateLayers(LayerTreeHost* host) { LayerTreeHostCommon::CallFunctionForEveryLayer( - host, [this](Layer* layer) { layer->RunMicroBenchmark(this); }, - CallFunctionLayerType::ALL_LAYERS); + host, [this](Layer* layer) { layer->RunMicroBenchmark(this); }); } void InvalidationBenchmark::RunOnLayer(PictureLayer* layer) {
diff --git a/cc/debug/rasterize_and_record_benchmark.cc b/cc/debug/rasterize_and_record_benchmark.cc index fcd2946..5babc0e 100644 --- a/cc/debug/rasterize_and_record_benchmark.cc +++ b/cc/debug/rasterize_and_record_benchmark.cc
@@ -72,8 +72,7 @@ void RasterizeAndRecordBenchmark::DidUpdateLayers(LayerTreeHost* host) { host_ = host; LayerTreeHostCommon::CallFunctionForEveryLayer( - host, [this](Layer* layer) { layer->RunMicroBenchmark(this); }, - CallFunctionLayerType::ALL_LAYERS); + host, [this](Layer* layer) { layer->RunMicroBenchmark(this); }); DCHECK(!results_.get()); results_ = base::WrapUnique(new base::DictionaryValue);
diff --git a/cc/debug/rasterize_and_record_benchmark_impl.cc b/cc/debug/rasterize_and_record_benchmark_impl.cc index ee819349..7264d5c 100644 --- a/cc/debug/rasterize_and_record_benchmark_impl.cc +++ b/cc/debug/rasterize_and_record_benchmark_impl.cc
@@ -126,12 +126,10 @@ void RasterizeAndRecordBenchmarkImpl::DidCompleteCommit( LayerTreeHostImpl* host) { LayerTreeHostCommon::CallFunctionForEveryLayer( - host->active_tree(), - [this](LayerImpl* layer) { + host->active_tree(), [this](LayerImpl* layer) { rasterize_results_.total_layers++; layer->RunMicroBenchmark(this); - }, - CallFunctionLayerType::ALL_LAYERS); + }); std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue()); result->SetDouble("rasterize_time_ms",
diff --git a/cc/layers/layer_proto_converter.cc b/cc/layers/layer_proto_converter.cc index 05e360b..32e681a9 100644 --- a/cc/layers/layer_proto_converter.cc +++ b/cc/layers/layer_proto_converter.cc
@@ -85,8 +85,7 @@ LayerIdMap* layer_id_map) { LayerTreeHostCommon::CallFunctionForEveryLayer( root_layer->layer_tree_host(), - [layer_id_map](Layer* layer) { (*layer_id_map)[layer->id()] = layer; }, - CallFunctionLayerType::ALL_LAYERS); + [layer_id_map](Layer* layer) { (*layer_id_map)[layer->id()] = layer; }); } // static
diff --git a/cc/trees/draw_property_utils.cc b/cc/trees/draw_property_utils.cc index 67a8b70..686711e6 100644 --- a/cc/trees/draw_property_utils.cc +++ b/cc/trees/draw_property_utils.cc
@@ -426,32 +426,29 @@ const TransformTree& transform_tree, const EffectTree& effect_tree, LayerList* update_layer_list) { - LayerTreeHostCommon::CallFunctionForEveryLayer( - layer_tree_host, - [&](Layer* layer) { - bool layer_is_drawn = - effect_tree.Node(layer->effect_tree_index())->data.is_drawn; + for (auto* layer : *layer_tree_host) { + bool layer_is_drawn = + effect_tree.Node(layer->effect_tree_index())->data.is_drawn; - if (!IsRootLayer(layer) && - LayerShouldBeSkipped(layer, layer_is_drawn, transform_tree, - effect_tree)) - return; + if (!IsRootLayer(layer) && + LayerShouldBeSkipped(layer, layer_is_drawn, transform_tree, + effect_tree)) + continue; - if (LayerNeedsUpdate(layer, layer_is_drawn, transform_tree)) { - update_layer_list->push_back(layer); - } + if (LayerNeedsUpdate(layer, layer_is_drawn, transform_tree)) { + update_layer_list->push_back(layer); + } - // Append mask layers to the update layer list. They don't have valid - // visible rects, so need to get added after the above calculation. - // Replica layers don't need to be updated. - if (Layer* mask_layer = layer->mask_layer()) - update_layer_list->push_back(mask_layer); - if (Layer* replica_layer = layer->replica_layer()) { - if (Layer* mask_layer = replica_layer->mask_layer()) - update_layer_list->push_back(mask_layer); - } - }, - CallFunctionLayerType::BASIC_LAYER); + // Append mask layers to the update layer list. They don't have valid + // visible rects, so need to get added after the above calculation. + // Replica layers don't need to be updated. + if (Layer* mask_layer = layer->mask_layer()) + update_layer_list->push_back(mask_layer); + if (Layer* replica_layer = layer->replica_layer()) { + if (Layer* mask_layer = replica_layer->mask_layer()) + update_layer_list->push_back(mask_layer); + } + } } static void ResetIfHasNanCoordinate(gfx::RectF* rect) {
diff --git a/cc/trees/layer_tree_host.cc b/cc/trees/layer_tree_host.cc index 60ad5f8..d6c4f328 100644 --- a/cc/trees/layer_tree_host.cc +++ b/cc/trees/layer_tree_host.cc
@@ -412,8 +412,7 @@ frame_viewer_instrumentation::IsTracingLayerTreeSnapshots() && root_layer()) { LayerTreeHostCommon::CallFunctionForEveryLayer( - this, [](Layer* layer) { layer->DidBeginTracing(); }, - CallFunctionLayerType::ALL_LAYERS); + this, [](Layer* layer) { layer->DidBeginTracing(); }); } LayerTreeImpl* sync_tree = host_impl->sync_tree(); @@ -1650,12 +1649,9 @@ // updated for other reasons. All layers that at this point are part of the // layer tree are valid, so it is OK that they have a valid sequence number. int seq_num = property_trees_.sequence_number; - LayerTreeHostCommon::CallFunctionForEveryLayer( - this, - [seq_num](Layer* layer) { - layer->set_property_tree_sequence_number(seq_num); - }, - CallFunctionLayerType::ALL_LAYERS); + LayerTreeHostCommon::CallFunctionForEveryLayer(this, [seq_num](Layer* layer) { + layer->set_property_tree_sequence_number(seq_num); + }); surface_id_namespace_ = proto.surface_id_namespace(); next_surface_sequence_ = proto.next_surface_sequence();
diff --git a/cc/trees/layer_tree_host_common.h b/cc/trees/layer_tree_host_common.h index 8d1b5e7..5f2d720b 100644 --- a/cc/trees/layer_tree_host_common.h +++ b/cc/trees/layer_tree_host_common.h
@@ -36,13 +36,6 @@ class SwapPromise; class PropertyTrees; -enum CallFunctionLayerType : uint32_t { - BASIC_LAYER = 0, - MASK_LAYER = 1, - REPLICA_LAYER = 2, - ALL_LAYERS = MASK_LAYER | REPLICA_LAYER -}; - class CC_EXPORT LayerTreeHostCommon { public: struct CC_EXPORT CalcDrawPropsMainInputsForTesting { @@ -138,13 +131,11 @@ template <typename Function> static void CallFunctionForEveryLayer(LayerTreeHost* layer, - const Function& function, - const CallFunctionLayerType& type); + const Function& function); template <typename Function> static void CallFunctionForEveryLayer(LayerTreeImpl* layer, - const Function& function, - const CallFunctionLayerType& type); + const Function& function); struct CC_EXPORT ScrollUpdateInfo { int layer_id; @@ -178,51 +169,30 @@ }; template <typename LayerType, typename Function> -static void CallFunctionForLayer(LayerType* layer, - const Function& function, - const CallFunctionLayerType& type) { +static void CallFunctionForLayer(LayerType* layer, const Function& function) { function(layer); - LayerType* mask_layer = layer->mask_layer(); - if ((type & CallFunctionLayerType::MASK_LAYER) && mask_layer) + if (LayerType* mask_layer = layer->mask_layer()) function(mask_layer); - LayerType* replica_layer = layer->replica_layer(); - if ((type & CallFunctionLayerType::REPLICA_LAYER) && replica_layer) { + if (LayerType* replica_layer = layer->replica_layer()) { function(replica_layer); - mask_layer = replica_layer->mask_layer(); - if ((type & CallFunctionLayerType::MASK_LAYER) && mask_layer) + if (LayerType* mask_layer = replica_layer->mask_layer()) function(mask_layer); } } template <typename Function> -static void CallFunctionForEveryLayerInternal( - Layer* layer, - const Function& function, - const CallFunctionLayerType& type) { - CallFunctionForLayer(layer, function, type); - - for (size_t i = 0; i < layer->children().size(); ++i) { - CallFunctionForEveryLayerInternal(layer->children()[i].get(), function, - type); - } +void LayerTreeHostCommon::CallFunctionForEveryLayer(LayerTreeHost* host, + const Function& function) { + for (auto* layer : *host) + CallFunctionForLayer(layer, function); } template <typename Function> -void LayerTreeHostCommon::CallFunctionForEveryLayer( - LayerTreeHost* host, - const Function& function, - const CallFunctionLayerType& type) { - CallFunctionForEveryLayerInternal(host->root_layer(), function, type); -} - -template <typename Function> -void LayerTreeHostCommon::CallFunctionForEveryLayer( - LayerTreeImpl* host_impl, - const Function& function, - const CallFunctionLayerType& type) { +void LayerTreeHostCommon::CallFunctionForEveryLayer(LayerTreeImpl* host_impl, + const Function& function) { for (auto* layer : *host_impl) - CallFunctionForLayer(layer, function, type); + CallFunctionForLayer(layer, function); } CC_EXPORT PropertyTrees* GetPropertyTrees(Layer* layer);
diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc index 4f2f1e4..c07b00b1 100644 --- a/cc/trees/layer_tree_host_impl.cc +++ b/cc/trees/layer_tree_host_impl.cc
@@ -1628,12 +1628,10 @@ if (is_new_trace) { if (pending_tree_) { LayerTreeHostCommon::CallFunctionForEveryLayer( - pending_tree(), [](LayerImpl* layer) { layer->DidBeginTracing(); }, - CallFunctionLayerType::ALL_LAYERS); + pending_tree(), [](LayerImpl* layer) { layer->DidBeginTracing(); }); } LayerTreeHostCommon::CallFunctionForEveryLayer( - active_tree(), [](LayerImpl* layer) { layer->DidBeginTracing(); }, - CallFunctionLayerType::ALL_LAYERS); + active_tree(), [](LayerImpl* layer) { layer->DidBeginTracing(); }); } {
diff --git a/cc/trees/layer_tree_host_unittest.cc b/cc/trees/layer_tree_host_unittest.cc index bb14ac8..64ad1f8 100644 --- a/cc/trees/layer_tree_host_unittest.cc +++ b/cc/trees/layer_tree_host_unittest.cc
@@ -6226,16 +6226,14 @@ void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) override { LayerTreeHostCommon::CallFunctionForEveryLayer( - host_impl->sync_tree(), - [this](LayerImpl* layer) { + host_impl->sync_tree(), [this](LayerImpl* layer) { const std::vector<int>& list = layer->IsAffectedByPageScale() ? this->affected_by_page_scale_ : this->not_affected_by_page_scale_; EXPECT_TRUE(std::find(list.begin(), list.end(), layer->id()) != list.end()); - }, - CallFunctionLayerType::ALL_LAYERS); + }); EndTest(); }
diff --git a/cc/trees/layer_tree_host_unittest_serialization.cc b/cc/trees/layer_tree_host_unittest_serialization.cc index da18690..2e4dc0da0 100644 --- a/cc/trees/layer_tree_host_unittest_serialization.cc +++ b/cc/trees/layer_tree_host_unittest_serialization.cc
@@ -47,12 +47,10 @@ void VerifyHostHasAllExpectedLayersInTree(Layer* root_layer) { LayerTreeHostCommon::CallFunctionForEveryLayer( - root_layer->layer_tree_host(), - [root_layer](Layer* layer) { + root_layer->layer_tree_host(), [root_layer](Layer* layer) { DCHECK(layer->layer_tree_host()); EXPECT_EQ(layer, layer->layer_tree_host()->LayerById(layer->id())); - }, - CallFunctionLayerType::ALL_LAYERS); + }); } void VerifySerializationAndDeserialization() { @@ -174,11 +172,9 @@ if (layer_tree_host_dst_->property_trees_.sequence_number) { int seq_num = layer_tree_host_dst_->property_trees_.sequence_number; LayerTreeHostCommon::CallFunctionForEveryLayer( - layer_tree_host_dst_.get(), - [seq_num](Layer* layer) { + layer_tree_host_dst_.get(), [seq_num](Layer* layer) { EXPECT_EQ(seq_num, layer->property_tree_sequence_number()); - }, - CallFunctionLayerType::ALL_LAYERS); + }); } }
diff --git a/cc/trees/layer_tree_impl.cc b/cc/trees/layer_tree_impl.cc index 9817125..06b34d3e 100644 --- a/cc/trees/layer_tree_impl.cc +++ b/cc/trees/layer_tree_impl.cc
@@ -106,16 +106,14 @@ void LayerTreeImpl::ReleaseResources() { if (root_layer_) { LayerTreeHostCommon::CallFunctionForEveryLayer( - this, [](LayerImpl* layer) { layer->ReleaseResources(); }, - CallFunctionLayerType::ALL_LAYERS); + this, [](LayerImpl* layer) { layer->ReleaseResources(); }); } } void LayerTreeImpl::RecreateResources() { if (root_layer_) { LayerTreeHostCommon::CallFunctionForEveryLayer( - this, [](LayerImpl* layer) { layer->RecreateResources(); }, - CallFunctionLayerType::ALL_LAYERS); + this, [](LayerImpl* layer) { layer->RecreateResources(); }); } } @@ -555,12 +553,9 @@ // frame to a newly-committed property tree. if (!root_layer()) return; - LayerTreeHostCommon::CallFunctionForEveryLayer( - this, - [](LayerImpl* layer) { - layer->UpdatePropertyTreeForScrollingAndAnimationIfNeeded(); - }, - CallFunctionLayerType::ALL_LAYERS); + LayerTreeHostCommon::CallFunctionForEveryLayer(this, [](LayerImpl* layer) { + layer->UpdatePropertyTreeForScrollingAndAnimationIfNeeded(); + }); } void LayerTreeImpl::SetPageScaleOnActiveTree(float active_page_scale) { @@ -1073,8 +1068,7 @@ if (root_layer()) { LayerTreeHostCommon::CallFunctionForEveryLayer( - this, [](LayerImpl* layer) { layer->DidBecomeActive(); }, - CallFunctionLayerType::ALL_LAYERS); + this, [](LayerImpl* layer) { layer->DidBecomeActive(); }); } for (const auto& swap_promise : swap_promise_list_)
diff --git a/chrome/BUILD.gn b/chrome/BUILD.gn index 7828eb14..290cc149 100644 --- a/chrome/BUILD.gn +++ b/chrome/BUILD.gn
@@ -201,7 +201,7 @@ if (use_pango || use_cairo) { # Needed for chrome_main.cc initialization of libraries. - configs += [ "//build/config/linux:pangocairo" ] + configs += [ "//build/config/linux/pangocairo" ] } if (use_x11) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeBackgroundService.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeBackgroundService.java index b7edc74..b8c90d0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeBackgroundService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeBackgroundService.java
@@ -33,7 +33,7 @@ @Override @VisibleForTesting public int onRunTask(final TaskParams params) { - Log.i(TAG, "Woken up at " + new java.util.Date().toString()); + Log.i(TAG, "[" + params.getTag() + "] Woken up at " + new java.util.Date().toString()); final Context context = this; ThreadUtils.runOnUiThread(new Runnable() { @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/accessibility/FontSizePrefs.java b/chrome/android/java/src/org/chromium/chrome/browser/accessibility/FontSizePrefs.java index 2ed12ea..c3fbb69 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/accessibility/FontSizePrefs.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/accessibility/FontSizePrefs.java
@@ -33,6 +33,8 @@ */ public static final float FORCE_ENABLE_ZOOM_THRESHOLD_MULTIPLIER = 1.3f; + private static final float EPSILON = 0.001f; + static final String PREF_USER_SET_FORCE_ENABLE_ZOOM = "user_set_force_enable_zoom"; static final String PREF_USER_FONT_SCALE_FACTOR = "user_font_scale_factor"; @@ -114,10 +116,18 @@ public float getUserFontScaleFactor() { float userFontScaleFactor = mSharedPreferences.getFloat(PREF_USER_FONT_SCALE_FACTOR, 0f); if (userFontScaleFactor == 0f) { - // Initialize userFontScaleFactor based on fontScaleFactor, since userFontScaleFactor - // was added long after fontScaleFactor. - userFontScaleFactor = MathUtils.clamp(getFontScaleFactor() / getSystemFontScale(), - 0.5f, 2f); + float fontScaleFactor = getFontScaleFactor(); + + if (Math.abs(fontScaleFactor - 1f) <= EPSILON) { + // If the font scale factor is 1, assume that the user hasn't customized their font + // scale and/or wants the default value + userFontScaleFactor = 1f; + } else { + // Initialize userFontScaleFactor based on fontScaleFactor, since + // userFontScaleFactor was added long after fontScaleFactor. + userFontScaleFactor = + MathUtils.clamp(fontScaleFactor / getSystemFontScale(), 0.5f, 2f); + } SharedPreferences.Editor sharedPreferencesEditor = mSharedPreferences.edit(); sharedPreferencesEditor.putFloat(PREF_USER_FONT_SCALE_FACTOR, userFontScaleFactor); sharedPreferencesEditor.apply(); @@ -126,8 +136,8 @@ } /** - * Returns the fontScaleFactor. This is the produce of the userFontScaleFactor and the system - * fon scale, and is the amount by which webpage text will be scaled during font boosting. + * Returns the fontScaleFactor. This is the product of the userFontScaleFactor and the system + * font scale, and is the amount by which webpage text will be scaled during font boosting. */ public float getFontScaleFactor() { return nativeGetFontScaleFactor(mFontSizePrefsAndroidPtr);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java index 1652fbc4..eecc0579 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java
@@ -22,6 +22,7 @@ import android.view.View; import org.chromium.base.ApiCompatibilityUtils; +import org.chromium.base.Callback; import org.chromium.base.CommandLine; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; @@ -532,7 +533,16 @@ @Override public void onSnippetDismissed(SnippetArticle dismissedSnippet) { if (mIsDestroyed) return; - NewTabPageUma.recordSnippetAction(NewTabPageUma.SNIPPETS_ACTION_DISMISSED); + + mSnippetsBridge.getSnippedVisited(dismissedSnippet, new Callback<Boolean>() { + @Override + public void onResult(Boolean result) { + NewTabPageUma.recordSnippetAction(result + ? NewTabPageUma.SNIPPETS_ACTION_DISMISSED_VISITED + : NewTabPageUma.SNIPPETS_ACTION_DISMISSED_UNVISITED); + } + }); + mSnippetsBridge.discardSnippet(dismissedSnippet); } };
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPageUma.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPageUma.java index 245a3c45..03d2c2e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPageUma.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPageUma.java
@@ -60,9 +60,11 @@ // The number of possible NTP impression types private static final int NUM_NTP_IMPRESSION = 2; - /** Possible interactions with the snippets. */ + /** Possible interactions with the snippets. + * Do not remove or change existing values other than NUM_SNIPPETS_ACTIONS. */ @IntDef({SNIPPETS_ACTION_SHOWN, SNIPPETS_ACTION_SCROLLED, SNIPPETS_ACTION_CLICKED, - SNIPPETS_ACTION_DISMISSED}) + SNIPPETS_ACTION_DISMISSED_OBSOLETE, SNIPPETS_ACTION_DISMISSED_VISITED, + SNIPPETS_ACTION_DISMISSED_UNVISITED}) @Retention(RetentionPolicy.SOURCE) public @interface SnippetsAction {} /** Snippets are enabled and are being shown to the user. */ @@ -71,10 +73,14 @@ public static final int SNIPPETS_ACTION_SCROLLED = 1; /** A snippet has been clicked. */ public static final int SNIPPETS_ACTION_CLICKED = 2; - /** A snippet has been swiped away. */ - public static final int SNIPPETS_ACTION_DISMISSED = 3; + /** A snippet has been dismissed, made obsolete by the next two actions. */ + public static final int SNIPPETS_ACTION_DISMISSED_OBSOLETE = 3; + /** A snippet has been swiped away, it had been viewed by the user (on this device). */ + public static final int SNIPPETS_ACTION_DISMISSED_VISITED = 4; + /** A snippet has been swiped away, it had not been viewed by the user (on this device). */ + public static final int SNIPPETS_ACTION_DISMISSED_UNVISITED = 5; /** The number of possible actions. */ - private static final int NUM_SNIPPETS_ACTIONS = 4; + private static final int NUM_SNIPPETS_ACTIONS = 6; /** * Records an action taken by the user on the NTP.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/NewTabPageRecyclerView.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/NewTabPageRecyclerView.java index ac67695..d78d9e9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/NewTabPageRecyclerView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/NewTabPageRecyclerView.java
@@ -5,9 +5,7 @@ package org.chromium.chrome.browser.ntp.cards; import android.content.Context; -import android.graphics.PointF; import android.support.v7.widget.LinearLayoutManager; -import android.support.v7.widget.LinearSmoothScroller; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.GestureDetector; @@ -22,7 +20,7 @@ */ public class NewTabPageRecyclerView extends RecyclerView { private GestureDetector mGestureDetector; - private LinearLayoutManagerWithSmoothScroller mLayoutManager; + private LinearLayoutManager mLayoutManager; /** * Constructor needed to inflate from XML. @@ -39,7 +37,7 @@ return retVal; } }); - mLayoutManager = new LinearLayoutManagerWithSmoothScroller(getContext()); + mLayoutManager = new LinearLayoutManager(getContext()); setLayoutManager(mLayoutManager); } @@ -76,32 +74,4 @@ outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_FULLSCREEN; return super.onCreateInputConnection(outAttrs); } - - private static class LinearLayoutManagerWithSmoothScroller extends LinearLayoutManager { - private final Context mContext; - - public LinearLayoutManagerWithSmoothScroller(Context context) { - super(context); - mContext = context; - } - - @Override - public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, - int position) { - LinearSmoothScroller scroller = new LinearSmoothScroller(mContext) { - @Override - public PointF computeScrollVectorForPosition(int targetPosition) { - return LinearLayoutManagerWithSmoothScroller.this - .computeScrollVectorForPosition(targetPosition); - } - - @Override - protected int getVerticalSnapPreference() { - return SNAP_TO_START; - } - }; - scroller.setTargetPosition(position); - startSmoothScroll(scroller); - } - } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetsBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetsBridge.java index c91e6b92..fafb73b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetsBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetsBridge.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.ntp.snippets; +import org.chromium.base.Callback; import org.chromium.base.annotations.CalledByNative; import org.chromium.chrome.browser.profiles.Profile; @@ -73,6 +74,22 @@ } /** + * Checks whether a snippet has been visited by querying the history for the snippet's URL. + */ + public void getSnippedVisited(SnippetArticle snippet, Callback<Boolean> callback) { + assert mNativeSnippetsBridge != 0; + nativeSnippetVisited(mNativeSnippetsBridge, callback, snippet.mUrl); + } + + /** + * {@link Callback#onResult} is not annotated with CalledByNative, so we must use this wrapper. + */ + @CalledByNative + private static void runCallback(Callback<Boolean> callback, boolean result) { + callback.onResult(result); + } + + /** * Sets the recipient for the fetched snippets. * * An observer needs to be set before the native code attempts to transmit snippets them to @@ -110,4 +127,6 @@ private static native void nativeRescheduleFetching(); private native void nativeDiscardSnippet(long nativeNTPSnippetsBridge, String snippetUrl); private native void nativeSetObserver(long nativeNTPSnippetsBridge, SnippetsBridge bridge); + private static native void nativeSnippetVisited(long nativeNTPSnippetsBridge, + Callback<Boolean> callback, String url); }
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index d182216..d153f91e 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -876,7 +876,7 @@ if (is_linux) { if (use_aura) { - configs += [ "//build/config/linux:dbus" ] + configs += [ "//build/config/linux/dbus" ] deps += [ "//build/linux:fontconfig", "//dbus", @@ -1233,7 +1233,7 @@ "chromeos/system/fake_input_device_settings.cc", "chromeos/system/fake_input_device_settings.h", ] - configs += [ "//build/config/linux:dbus" ] + configs += [ "//build/config/linux/dbus" ] deps += [ "//chromeos:test_support" ] }
diff --git a/chrome/browser/android/ntp/ntp_snippets_bridge.cc b/chrome/browser/android/ntp/ntp_snippets_bridge.cc index ac248694..569b3c7a 100644 --- a/chrome/browser/android/ntp/ntp_snippets_bridge.cc +++ b/chrome/browser/android/ntp/ntp_snippets_bridge.cc
@@ -10,10 +10,12 @@ #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" +#include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/ntp_snippets/ntp_snippets_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_android.h" #include "chrome/browser/profiles/profile_manager.h" +#include "components/history/core/browser/history_service.h" #include "components/ntp_snippets/ntp_snippet.h" #include "components/ntp_snippets/ntp_snippets_service.h" #include "jni/SnippetsBridge_jni.h" @@ -23,6 +25,22 @@ using base::android::ToJavaArrayOfStrings; using base::android::ToJavaLongArray; +namespace { + +void SnippetVisitedHistoryRequestCallback( + base::android::ScopedJavaGlobalRef<jobject> callback, + bool success, + const history::URLRow& row, + const history::VisitVector& visitVector) { + bool visited = success && row.visit_count() != 0; + + JNIEnv* env = base::android::AttachCurrentThread(); + Java_SnippetsBridge_runCallback(env, callback.obj(), + static_cast<jboolean>(visited)); +} + +} // namespace + static jlong Init(JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jobject>& j_profile) { @@ -49,6 +67,9 @@ : snippet_service_observer_(this) { Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile); ntp_snippets_service_ = NTPSnippetsServiceFactory::GetForProfile(profile); + history_service_ = + HistoryServiceFactory::GetForProfile(profile, + ServiceAccessType::EXPLICIT_ACCESS); snippet_service_observer_.Add(ntp_snippets_service_); } @@ -72,6 +93,19 @@ GURL(ConvertJavaStringToUTF8(env, url))); } +void NTPSnippetsBridge::SnippetVisited(JNIEnv* env, + const JavaParamRef<jobject>& obj, + const JavaParamRef<jobject>& jcallback, + const JavaParamRef<jstring>& jurl) { + base::android::ScopedJavaGlobalRef<jobject> callback(jcallback); + + history_service_->QueryURL( + GURL(ConvertJavaStringToUTF8(env, jurl)), + false, + base::Bind(&SnippetVisitedHistoryRequestCallback, callback), + &tracker_); +} + void NTPSnippetsBridge::NTPSnippetsServiceLoaded() { if (observer_.is_null()) return;
diff --git a/chrome/browser/android/ntp/ntp_snippets_bridge.h b/chrome/browser/android/ntp/ntp_snippets_bridge.h index 0011c99c..088b5d53 100644 --- a/chrome/browser/android/ntp/ntp_snippets_bridge.h +++ b/chrome/browser/android/ntp/ntp_snippets_bridge.h
@@ -9,6 +9,8 @@ #include "base/android/scoped_java_ref.h" #include "base/scoped_observer.h" +#include "base/task/cancelable_task_tracker.h" +#include "components/history/core/browser/history_service.h" #include "components/ntp_snippets/ntp_snippets_service.h" // The C++ counterpart to SnippetsBridge.java. Enables Java code to access @@ -28,6 +30,12 @@ const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jstring>& url); + // Checks if the URL has been visited. + void SnippetVisited(JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj, + const base::android::JavaParamRef<jobject>& callback, + const base::android::JavaParamRef<jstring>& jurl); + static bool Register(JNIEnv* env); private: @@ -38,6 +46,8 @@ void NTPSnippetsServiceShutdown() override; ntp_snippets::NTPSnippetsService* ntp_snippets_service_; + history::HistoryService* history_service_; + base::CancelableTaskTracker tracker_; // Used to notify the Java side when new snippets have been fetched. base::android::ScopedJavaGlobalRef<jobject> observer_;
diff --git a/chrome/browser/chromeos/arc/arc_auth_service.cc b/chrome/browser/chromeos/arc/arc_auth_service.cc index 435ffdbf..58f9a48 100644 --- a/chrome/browser/chromeos/arc/arc_auth_service.cc +++ b/chrome/browser/chromeos/arc/arc_auth_service.cc
@@ -222,8 +222,11 @@ Shutdown(); - if (profile->IsLegacySupervised()) { - VLOG(2) << "Supervised profiles are not supported in Arc."; + user_manager::User const* const user = + chromeos::ProfileHelper::Get()->GetUserByProfile(profile); + if (profile->IsLegacySupervised() || !user->HasGaiaAccount()) { + VLOG(2) << "Supervised users and users without GAIA accounts are not " + "supported in Arc."; return; }
diff --git a/chrome/browser/chromeos/arc/arc_auth_service_unittest.cc b/chrome/browser/chromeos/arc/arc_auth_service_unittest.cc index 7ce9bbc7..5b9d661 100644 --- a/chrome/browser/chromeos/arc/arc_auth_service_unittest.cc +++ b/chrome/browser/chromeos/arc/arc_auth_service_unittest.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> #include <string> #include <vector> @@ -12,6 +13,9 @@ #include "base/macros.h" #include "base/run_loop.h" #include "chrome/browser/chromeos/arc/arc_auth_service.h" +#include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" +#include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/prefs/pref_service_syncable_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" @@ -19,7 +23,9 @@ #include "components/arc/arc_bridge_service.h" #include "components/arc/test/fake_arc_bridge_service.h" #include "components/prefs/pref_service.h" +#include "components/signin/core/account_id/account_id.h" #include "components/syncable_prefs/testing_pref_service_syncable.h" +#include "components/user_manager/user_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread_bundle.h" #include "google_apis/gaia/gaia_constants.h" @@ -41,7 +47,8 @@ class ArcAuthServiceTest : public testing::Test { public: ArcAuthServiceTest() - : thread_bundle_(new content::TestBrowserThreadBundle(kThreadOptions)) {} + : thread_bundle_(new content::TestBrowserThreadBundle(kThreadOptions)), + user_manager_enabler_(new chromeos::FakeChromeUserManager) {} ~ArcAuthServiceTest() override = default; void SetUp() override { @@ -62,10 +69,20 @@ EXPECT_EQ(true, !ArcBridgeService::Get()->available()); EXPECT_EQ(ArcBridgeService::State::STOPPED, ArcBridgeService::Get()->state()); + + const AccountId account_id( + AccountId::FromUserEmailGaiaId("user@gmail.com", "1234567890")); + GetFakeUserManager()->AddUser(account_id); + GetFakeUserManager()->LoginUser(account_id); } void TearDown() override {} + chromeos::FakeChromeUserManager* GetFakeUserManager() const { + return static_cast<chromeos::FakeChromeUserManager*>( + user_manager::UserManager::Get()); + } + protected: Profile* profile() { return profile_.get(); } FakeArcBridgeService* bridge_service() { return bridge_service_.get(); } @@ -86,6 +103,7 @@ std::unique_ptr<arc::FakeArcBridgeService> bridge_service_; std::unique_ptr<arc::ArcAuthService> auth_service_; std::unique_ptr<TestingProfile> profile_; + chromeos::ScopedUserManagerEnabler user_manager_enabler_; base::ScopedTempDir temp_dir_; DISALLOW_COPY_AND_ASSIGN(ArcAuthServiceTest); @@ -94,7 +112,7 @@ TEST_F(ArcAuthServiceTest, PrefChangeTriggersService) { ASSERT_EQ(ArcAuthService::State::STOPPED, auth_service()->state()); - PrefService* pref = profile()->GetPrefs(); + PrefService* const pref = profile()->GetPrefs(); DCHECK_EQ(false, pref->GetBoolean(prefs::kArcEnabled)); auth_service()->OnPrimaryUserProfilePrepared(profile()); @@ -155,7 +173,7 @@ } TEST_F(ArcAuthServiceTest, CancelFetchingDisablesArc) { - PrefService* pref = profile()->GetPrefs(); + PrefService* const pref = profile()->GetPrefs(); auth_service()->OnPrimaryUserProfilePrepared(profile()); pref->SetBoolean(prefs::kArcEnabled, true); @@ -170,7 +188,7 @@ } TEST_F(ArcAuthServiceTest, CloseUIKeepsArcEnabled) { - PrefService* pref = profile()->GetPrefs(); + PrefService* const pref = profile()->GetPrefs(); auth_service()->OnPrimaryUserProfilePrepared(profile()); pref->SetBoolean(prefs::kArcEnabled, true); @@ -188,7 +206,7 @@ } TEST_F(ArcAuthServiceTest, EnableDisablesArc) { - PrefService* pref = profile()->GetPrefs(); + const PrefService* pref = profile()->GetPrefs(); auth_service()->OnPrimaryUserProfilePrepared(profile()); EXPECT_FALSE(pref->GetBoolean(prefs::kArcEnabled)); @@ -202,7 +220,7 @@ } TEST_F(ArcAuthServiceTest, SignInStatus) { - PrefService* prefs = profile()->GetPrefs(); + PrefService* const prefs = profile()->GetPrefs(); EXPECT_FALSE(prefs->GetBoolean(prefs::kArcSignedIn)); prefs->SetBoolean(prefs::kArcEnabled, true); @@ -238,4 +256,26 @@ auth_service()->Shutdown(); } +TEST_F(ArcAuthServiceTest, DisabledForDeviceLocalAccount) { + PrefService* const prefs = profile()->GetPrefs(); + EXPECT_FALSE(prefs->GetBoolean(prefs::kArcSignedIn)); + prefs->SetBoolean(prefs::kArcEnabled, true); + + // Create device local account and set it as active. + const std::string email = "device-local-account@fake-email.com"; + TestingProfile::Builder profile_builder; + profile_builder.SetProfileName(email); + std::unique_ptr<TestingProfile> device_local_profile(profile_builder.Build()); + const AccountId account_id(AccountId::FromUserEmail(email)); + GetFakeUserManager()->AddPublicAccountUser(account_id); + GetFakeUserManager()->SwitchActiveUser(account_id); + + // Check that user without GAIA account can't use ARC. + auth_service()->OnPrimaryUserProfilePrepared(device_local_profile.get()); + EXPECT_EQ(ArcAuthService::State::STOPPED, auth_service()->state()); + + // Correctly stop service. + auth_service()->Shutdown(); +} + } // namespace arc
diff --git a/chrome/browser/chromeos/login/users/fake_chrome_user_manager.cc b/chrome/browser/chromeos/login/users/fake_chrome_user_manager.cc index 1ffe41b8..36fb73c 100644 --- a/chrome/browser/chromeos/login/users/fake_chrome_user_manager.cc +++ b/chrome/browser/chromeos/login/users/fake_chrome_user_manager.cc
@@ -78,6 +78,7 @@ IDR_PROFILE_PICTURE_LOADING))), user_manager::User::USER_IMAGE_PROFILE, false); users_.push_back(user); + chromeos::ProfileHelper::Get()->SetProfileToUserMappingForTesting(user); return user; }
diff --git a/chrome/browser/chromeos/policy/bluetooth_policy_handler.cc b/chrome/browser/chromeos/policy/bluetooth_policy_handler.cc index b6379d8..4635a99 100644 --- a/chrome/browser/chromeos/policy/bluetooth_policy_handler.cc +++ b/chrome/browser/chromeos/policy/bluetooth_policy_handler.cc
@@ -8,21 +8,10 @@ #include "base/memory/ref_counted.h" #include "chromeos/settings/cros_settings_names.h" #include "chromeos/settings/cros_settings_provider.h" -#include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_adapter_factory.h" namespace policy { -namespace { - -void SetBluetoothPolicy(bool allow_bluetooth, - scoped_refptr<device::BluetoothAdapter> adapter) { - if (!allow_bluetooth) - adapter->Shutdown(); -} - -} // namespace - BluetoothPolicyHandler::BluetoothPolicyHandler( chromeos::CrosSettings* cros_settings) : cros_settings_(cros_settings), weak_factory_(this) { @@ -45,12 +34,20 @@ if (status != chromeos::CrosSettingsProvider::TRUSTED) return; + device::BluetoothAdapterFactory::GetAdapter(base::Bind( + &BluetoothPolicyHandler::SetBluetoothPolicy, weak_factory_.GetWeakPtr())); +} + +void BluetoothPolicyHandler::SetBluetoothPolicy( + scoped_refptr<device::BluetoothAdapter> adapter) { // Get the updated policy. bool allow_bluetooth = true; cros_settings_->GetBoolean(chromeos::kAllowBluetooth, &allow_bluetooth); - device::BluetoothAdapterFactory::GetAdapter( - base::Bind(&SetBluetoothPolicy, allow_bluetooth)); + if (!allow_bluetooth) { + adapter_ = adapter; + adapter_->Shutdown(); + } } } // namespace policy
diff --git a/chrome/browser/chromeos/policy/bluetooth_policy_handler.h b/chrome/browser/chromeos/policy/bluetooth_policy_handler.h index 0d1200a7..55a6841 100644 --- a/chrome/browser/chromeos/policy/bluetooth_policy_handler.h +++ b/chrome/browser/chromeos/policy/bluetooth_policy_handler.h
@@ -8,13 +8,15 @@ #include <memory> #include "base/macros.h" +#include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/chromeos/settings/cros_settings.h" +#include "device/bluetooth/bluetooth_adapter.h" namespace policy { // This class observes the device setting |DeviceAllowBluetooth|, and calls -// BluetoothAdapter::SetDisabled() appropriately based on the value of that +// BluetoothAdapter::Shutdown() appropriately based on the value of that // setting. class BluetoothPolicyHandler { public: @@ -23,13 +25,19 @@ private: // Once a trusted set of policies is established, this function calls - // |SetDisabled| with the trusted state of the |DeviceAllowBluetooth| policy + // |Shutdown| with the trusted state of the |DeviceAllowBluetooth| policy // through helper function |SetBluetoothPolicy|. void OnBluetoothPolicyChanged(); + // Helper function used in device::BluetoothAdapterFactory::GetAdapter + // callback. Saves a reference to the adapter (so it stays alive) and calls + // |Shutdown| on the Bluetooth stack in order to disable it. + void SetBluetoothPolicy(scoped_refptr<device::BluetoothAdapter> adapter); + chromeos::CrosSettings* cros_settings_; std::unique_ptr<chromeos::CrosSettings::ObserverSubscription> bluetooth_policy_subscription_; + scoped_refptr<device::BluetoothAdapter> adapter_; base::WeakPtrFactory<BluetoothPolicyHandler> weak_factory_; DISALLOW_COPY_AND_ASSIGN(BluetoothPolicyHandler);
diff --git a/chrome/browser/chromeos/profiles/profile_helper.cc b/chrome/browser/chromeos/profiles/profile_helper.cc index d492f72b..b909db13 100644 --- a/chrome/browser/chromeos/profiles/profile_helper.cc +++ b/chrome/browser/chromeos/profiles/profile_helper.cc
@@ -24,6 +24,7 @@ #include "chromeos/chromeos_constants.h" #include "chromeos/chromeos_switches.h" #include "components/guest_view/browser/guest_view_manager.h" +#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_thread.h" @@ -339,7 +340,7 @@ user_list_for_testing_.begin(); it != user_list_for_testing_.end(); ++it) { - if ((*it)->email() == user_name) + if ((*it)->GetAccountId().GetUserEmail() == user_name) return *it; }
diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index 35aeeaa9..e2d50dc3 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn
@@ -99,7 +99,7 @@ ".", "//chrome") sources -= [ "api/music_manager_private/device_id_linux.cc" ] - configs += [ "//build/config/linux:dbus" ] + configs += [ "//build/config/linux/dbus" ] deps += [ "//components/chrome_apps", "//remoting/host/it2me:common",
diff --git a/chrome/browser/password_manager/auto_signin_first_run_dialog_android_unittest.cc b/chrome/browser/password_manager/auto_signin_first_run_dialog_android_unittest.cc index 6c42f10..8a0333a 100644 --- a/chrome/browser/password_manager/auto_signin_first_run_dialog_android_unittest.cc +++ b/chrome/browser/password_manager/auto_signin_first_run_dialog_android_unittest.cc
@@ -49,3 +49,33 @@ EXPECT_TRUE(prefs()->GetBoolean( password_manager::prefs::kWasAutoSignInFirstRunExperienceShown)); } + +TEST_F(AutoSigninFirstRunDialogAndroidTest, + CheckResetOfPrefAfterFirstRunMessageWasShownOnTurnOkClicked) { + prefs()->SetBoolean( + password_manager::prefs::kWasAutoSignInFirstRunExperienceShown, false); + prefs()->SetBoolean(password_manager::prefs::kCredentialsEnableAutosignin, + true); + std::unique_ptr<AutoSigninFirstRunDialogAndroid> dialog(CreateDialog()); + dialog->OnOkClicked(base::android::AttachCurrentThread(), nullptr); + dialog.reset(); + EXPECT_TRUE(prefs()->GetBoolean( + password_manager::prefs::kWasAutoSignInFirstRunExperienceShown)); + EXPECT_TRUE(prefs()->GetBoolean( + password_manager::prefs::kCredentialsEnableAutosignin)); +} + +TEST_F(AutoSigninFirstRunDialogAndroidTest, + CheckResetOfPrefAfterFirstRunMessageWasShownOnTurnOffClicked) { + prefs()->SetBoolean( + password_manager::prefs::kWasAutoSignInFirstRunExperienceShown, false); + prefs()->SetBoolean(password_manager::prefs::kCredentialsEnableAutosignin, + true); + std::unique_ptr<AutoSigninFirstRunDialogAndroid> dialog(CreateDialog()); + dialog->OnTurnOffClicked(base::android::AttachCurrentThread(), nullptr); + dialog.reset(); + EXPECT_TRUE(prefs()->GetBoolean( + password_manager::prefs::kWasAutoSignInFirstRunExperienceShown)); + EXPECT_FALSE(prefs()->GetBoolean( + password_manager::prefs::kCredentialsEnableAutosignin)); +}
diff --git a/chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc b/chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc index 5f5a1c7..8960d99 100644 --- a/chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc +++ b/chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc
@@ -232,8 +232,8 @@ } }; -// Disable on Mac due to ongoing flakiness. (crbug.com/442785) -#if defined(OS_MACOSX) +// Disable on Windows and Mac due to ongoing flakiness. (crbug.com/442785) +#if defined(OS_WIN) || defined(OS_MACOSX) #define MAYBE_ProcessPerTab DISABLED_ProcessPerTab #else #define MAYBE_ProcessPerTab ProcessPerTab @@ -361,8 +361,8 @@ #endif // TODO(nasko): crbug.com/173137 -// Disable on Mac 10.9 due to ongoing flakiness. (crbug.com/442785) -#if defined(OS_MACOSX) +// Disable on Windows and Mac due to ongoing flakiness. (crbug.com/442785) +#if defined(OS_WIN) || defined(OS_MACOSX) #define MAYBE_ProcessOverflow DISABLED_ProcessOverflow #else #define MAYBE_ProcessOverflow ProcessOverflow @@ -374,8 +374,8 @@ TestProcessOverflow(); } -// Disable on Mac 10.9 due to ongoing flakiness. (crbug.com/442785) -#if defined(OS_MACOSX) +// Disable on Windows and Mac due to ongoing flakiness. (crbug.com/442785) +#if defined(OS_WIN) || defined(OS_MACOSX) #define MAYBE_ProcessOverflowCommandLine DISABLED_ProcessOverflowCommandLine #else #define MAYBE_ProcessOverflowCommandLine ProcessOverflowCommandLine
diff --git a/chrome/browser/resources/md_history/history_list.js b/chrome/browser/resources/md_history/history_list.js index d44903ee..c5216ed 100644 --- a/chrome/browser/resources/md_history/history_list.js +++ b/chrome/browser/resources/md_history/history_list.js
@@ -157,17 +157,29 @@ * @param {number} overallItemCount The number of items selected. */ removeDeletedHistory: function(overallItemCount) { + var splices = []; for (var i = this.historyData.length - 1; i >= 0; i--) { if (!this.historyData[i].selected) continue; - // Removes the selected item from historyData. - this.splice('historyData', i, 1); + // Removes the selected item from historyData. Use unshift so |splices| + // ends up in index order. + splices.unshift({ + index: i, + removed: [this.historyData[i]], + addedCount: 0, + object: this.historyData, + type: 'splice' + }); + this.historyData.splice(i, 1); overallItemCount--; if (overallItemCount == 0) break; } + // notifySplices gives better performance than individually splicing as it + // batches all of the updates together. + this.notifySplices('historyData', splices); }, /**
diff --git a/chrome/browser/resources/snippets_internals.html b/chrome/browser/resources/snippets_internals.html index 640520f..b214bf3 100644 --- a/chrome/browser/resources/snippets_internals.html +++ b/chrome/browser/resources/snippets_internals.html
@@ -67,6 +67,7 @@ <div class="detail" id="snippets-empty"></div> <div class="forms"> <input id="submit-clear" type="submit" value="Clear the list"> + <input id="submit-dump" type="submit" value="Dump the list to downloads"> </div> <div class="forms"> <input id="submit-download" type="submit" value="Add snippets">
diff --git a/chrome/browser/resources/snippets_internals.js b/chrome/browser/resources/snippets_internals.js index e49205b6..84164bb 100644 --- a/chrome/browser/resources/snippets_internals.js +++ b/chrome/browser/resources/snippets_internals.js
@@ -6,27 +6,25 @@ 'use strict'; function initialize() { - function submitDownload(event) { + $('submit-download').addEventListener('click', function(event) { chrome.send('download', [$('hosts-input').value]); event.preventDefault(); - } + }); - $('submit-download').addEventListener('click', submitDownload); - - function submitClear(event) { + $('submit-clear').addEventListener('click', function(event) { chrome.send('clear'); event.preventDefault(); - } + }); - $('submit-clear').addEventListener('click', submitClear); + $('submit-dump').addEventListener('click', function(event) { + chrome.send('dump'); + event.preventDefault(); + }); - function submitClearDiscarded(event) { + $('discarded-snippets-clear').addEventListener('click', function(event) { chrome.send('clearDiscarded'); event.preventDefault(); - } - - $('discarded-snippets-clear').addEventListener('click', - submitClearDiscarded); + }); chrome.send('loaded'); } @@ -38,7 +36,8 @@ function receiveHosts(hosts) { displayList(hosts, 'hosts'); - $('hosts-input').value = hosts.list.map(host => host.url).join(' '); + $('hosts-input').value = hosts.list.map( + function(host) { return host.url;}).join(' '); } function receiveSnippets(snippets) { @@ -50,6 +49,16 @@ 'discarded-snippet-title'); } + function receiveJson(json) { + // Redirect the browser to download data in |json| as a file "snippets.json" + // (Setting Content-Disposition: attachment via a data: URL is not possible; + // create a link with download attribute and simulate a click, instead.) + var link = document.createElement('a'); + link.download = 'snippets.json'; + link.href = 'data:,' + json; + link.click(); + } + function displayList(object, domId, titleClass) { jstProcess(new JsEvalContext(object), $(domId)); @@ -67,16 +76,13 @@ if ($(domId + '-empty')) $(domId + '-empty').textContent = text; if ($(domId + '-clear')) $(domId + '-clear').style.display = display; - function trigger(event) { - // The id of the snippet is stored to 'snippet-id' attribute of the link. - var id = event.currentTarget.getAttribute('snippet-id'); - $(id).classList.toggle('snippet-hidden'); - event.preventDefault(); - } - var links = document.getElementsByClassName(titleClass); for (var link of links) { - link.addEventListener('click', trigger); + link.addEventListener('click', function(event) { + var id = event.currentTarget.getAttribute('snippet-id'); + $(id).classList.toggle('snippet-hidden'); + event.preventDefault(); + }); } } @@ -87,6 +93,7 @@ receiveHosts: receiveHosts, receiveSnippets: receiveSnippets, receiveDiscardedSnippets: receiveDiscardedSnippets, + receiveJson: receiveJson, }; });
diff --git a/chrome/browser/resources/translate_internals/prefs.html b/chrome/browser/resources/translate_internals/prefs.html index 4a3aa70..5352237 100644 --- a/chrome/browser/resources/translate_internals/prefs.html +++ b/chrome/browser/resources/translate_internals/prefs.html
@@ -45,4 +45,8 @@ <h2>Dump</h2> <p class="dump"><p> </section> + <section> + <h2 id="override-variations-country">Override Variations Country</h2> + <p id="country-override"></p> + </section> </div>
diff --git a/chrome/browser/resources/translate_internals/translate_internals.js b/chrome/browser/resources/translate_internals/translate_internals.js index e6ecc1b..a18d468 100644 --- a/chrome/browser/resources/translate_internals/translate_internals.js +++ b/chrome/browser/resources/translate_internals/translate_internals.js
@@ -253,7 +253,56 @@ } /** - * Addes '0's to |number| as a string. |width| is length of the string + * Handles the message of 'countryUpdated' from the browser. + * + * @param {Object} details the object containing the country + * information. + */ + function onCountryUpdated(details) { + var p; + p = $('country-override'); + + p.innerHTML = ''; + + if ('country' in details) { + var country = details['country']; + + var h2 = $('override-variations-country'); + h2.title = ( + 'Changing this value will override the permanent country stored ' + + 'by variations. Normally, this value gets automatically updated ' + + 'with a new value received from the variations server when ' + + 'Chrome is updated.'); + + var input = document.createElement('input'); + input.type = 'text'; + input.value = country; + + var button = document.createElement('button'); + button.textContent = 'update'; + button.addEventListener('click', function() { + chrome.send('overrideCountry', [input.value]); + }, false); + p.appendChild(input); + p.appendChild(document.createElement('br')); + p.appendChild(button); + + if ('update' in details && details['update']) { + var div1 = document.createElement('div'); + div1.textContent = 'Permanent stored country updated.'; + var div2 = document.createElement('div'); + div2.textContent = ('You will need to restart your browser ' + + 'for the changes to take effect.'); + p.appendChild(div1); + p.appendChild(div2); + } + } else { + p.textContent = 'Could not load country info from Variations.'; + } + } + + /** + * Adds '0's to |number| as a string. |width| is length of the string * including '0's. * * @param {string} number The number to be converted into a string. @@ -405,6 +454,9 @@ case 'supportedLanguagesUpdated': onSupportedLanguagesUpdated(details); break; + case 'countryUpdated': + onCountryUpdated(details); + break; case 'translateErrorDetailsAdded': onTranslateErrorDetailsAdded(details); break;
diff --git a/chrome/browser/safe_browsing/srt_global_error_win.cc b/chrome/browser/safe_browsing/srt_global_error_win.cc index 69f40626..81732f0d 100644 --- a/chrome/browser/safe_browsing/srt_global_error_win.cc +++ b/chrome/browser/safe_browsing/srt_global_error_win.cc
@@ -14,7 +14,6 @@ #include "base/thread_task_runner_handle.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/safe_browsing/srt_field_trial_win.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/global_error/global_error_service.h" @@ -55,7 +54,7 @@ if (base::PathExists(downloaded_path)) { base::FilePath executable_path( downloaded_path.ReplaceExtension(kExecutableExtension)); - if (base::ReplaceFile(downloaded_path, executable_path, NULL)) { + if (base::ReplaceFile(downloaded_path, executable_path, nullptr)) { base::CommandLine srt_command_line(executable_path); srt_command_line.AppendSwitch(kChromePromptSwitch); base::Process srt_process( @@ -158,17 +157,12 @@ } void SRTGlobalError::BubbleViewAcceptButtonPressed(Browser* browser) { - RecordSRTPromptHistogram(SRT_PROMPT_ACCEPTED); - interacted_ = true; - global_error_service_->RemoveGlobalError(this); + OnUserinteractionStarted(SRT_PROMPT_ACCEPTED); MaybeExecuteSRT(); } void SRTGlobalError::BubbleViewCancelButtonPressed(Browser* browser) { - RecordSRTPromptHistogram(SRT_PROMPT_DENIED); - interacted_ = true; - global_error_service_->RemoveGlobalError(this); - + OnUserinteractionStarted(SRT_PROMPT_DENIED); BrowserThread::PostBlockingPoolTask( FROM_HERE, base::Bind(&DeleteFilesFromBlockingPool, downloaded_path_)); OnUserinteractionDone(); @@ -210,6 +204,20 @@ OnUserinteractionDone(); } +void SRTGlobalError::OnUserinteractionStarted( + SRTPromptHistogramValue histogram_value) { + // This is for cases where the UI doesn't go away quickly enough and user + // might click on the button more than once, or more than one button. + if (interacted_) + return; + RecordSRTPromptHistogram(histogram_value); + interacted_ = true; + if (global_error_service_) { + global_error_service_->RemoveGlobalError(this); + global_error_service_ = nullptr; + } +} + void SRTGlobalError::OnUserinteractionDone() { DCHECK(interacted_); // Once the user interacted with the bubble, we can forget about any pending
diff --git a/chrome/browser/safe_browsing/srt_global_error_win.h b/chrome/browser/safe_browsing/srt_global_error_win.h index b79a226..8a6d7a0 100644 --- a/chrome/browser/safe_browsing/srt_global_error_win.h +++ b/chrome/browser/safe_browsing/srt_global_error_win.h
@@ -9,6 +9,7 @@ #include "base/files/file_path.h" #include "base/macros.h" +#include "chrome/browser/safe_browsing/srt_field_trial_win.h" #include "chrome/browser/ui/global_error/global_error.h" class GlobalErrorService; @@ -59,6 +60,9 @@ // download and execute the SRT. void FallbackToDownloadPage(); + // Called when user interaction has started. + void OnUserinteractionStarted(SRTPromptHistogramValue histogram_value); + // Called when user interaction is done. void OnUserinteractionDone();
diff --git a/chrome/browser/ui/libgtk2ui/BUILD.gn b/chrome/browser/ui/libgtk2ui/BUILD.gn index 318f307..6ce8097 100644 --- a/chrome/browser/ui/libgtk2ui/BUILD.gn +++ b/chrome/browser/ui/libgtk2ui/BUILD.gn
@@ -70,7 +70,7 @@ "gconf_listener.cc", "gconf_listener.h", ] - configs += [ "//build/config/linux:gconf" ] + configs += [ "//build/config/linux/gconf" ] } defines = [ "LIBGTK2UI_IMPLEMENTATION" ]
diff --git a/chrome/browser/ui/webui/options/browser_options_handler.cc b/chrome/browser/ui/webui/options/browser_options_handler.cc index b44523c..f2aea20 100644 --- a/chrome/browser/ui/webui/options/browser_options_handler.cc +++ b/chrome/browser/ui/webui/options/browser_options_handler.cc
@@ -1065,7 +1065,10 @@ "BrowserOptions.enableFactoryResetSection"); } - Profile* profile = Profile::FromWebUI(web_ui()); + Profile* const profile = Profile::FromWebUI(web_ui()); + user_manager::User const* const user = + chromeos::ProfileHelper::Get()->GetUserByProfile(profile); + OnAccountPictureManagedChanged( policy::ProfilePolicyConnectorFactory::GetForBrowserContext(profile) ->policy_service() @@ -1075,7 +1078,7 @@ OnWallpaperManagedChanged( chromeos::WallpaperManager::Get()->IsPolicyControlled( - user_manager::UserManager::Get()->GetActiveUser()->GetAccountId())); + user->GetAccountId())); policy::ConsumerManagementService* consumer_management = g_browser_process->platform_part()->browser_policy_connector_chromeos()-> @@ -1088,7 +1091,7 @@ if (!arc::ArcBridgeService::GetEnabled( base::CommandLine::ForCurrentProcess()) || arc::ArcAuthService::IsOptInVerificationDisabled() || - profile->IsLegacySupervised()) { + profile->IsLegacySupervised() || !user->HasGaiaAccount()) { web_ui()->CallJavascriptFunction("BrowserOptions.hideAndroidAppsSection"); } OnSystemTimezoneAutomaticDetectionPolicyChanged();
diff --git a/chrome/browser/ui/webui/options/password_manager_handler.cc b/chrome/browser/ui/webui/options/password_manager_handler.cc index 66c9effe..c55d106 100644 --- a/chrome/browser/ui/webui/options/password_manager_handler.cc +++ b/chrome/browser/ui/webui/options/password_manager_handler.cc
@@ -405,10 +405,9 @@ UMA_HISTOGRAM_COUNTS("PasswordManager.ExportedPasswordsPerUserInCSV", password_list.size()); password_manager::PasswordExporter::Export( - path, std::move(password_list), - content::BrowserThread::GetMessageLoopProxyForThread( - content::BrowserThread::FILE) - .get()); + path, password_list, content::BrowserThread::GetMessageLoopProxyForThread( + content::BrowserThread::FILE) + .get()); } } // namespace options
diff --git a/chrome/browser/ui/webui/snippets_internals_message_handler.cc b/chrome/browser/ui/webui/snippets_internals_message_handler.cc index bd3fe9e4..e7a7d23 100644 --- a/chrome/browser/ui/webui/snippets_internals_message_handler.cc +++ b/chrome/browser/ui/webui/snippets_internals_message_handler.cc
@@ -6,7 +6,6 @@ #include <memory> #include <set> -#include <sstream> #include <vector> #include "base/bind.h" @@ -14,6 +13,7 @@ #include "base/command_line.h" #include "base/feature_list.h" #include "base/i18n/time_formatting.h" +#include "base/json/json_writer.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" @@ -23,7 +23,9 @@ #include "chrome/browser/ntp_snippets/ntp_snippets_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "components/ntp_snippets/ntp_snippet.h" +#include "components/ntp_snippets/pref_names.h" #include "components/ntp_snippets/switches.h" +#include "components/prefs/pref_service.h" #include "content/public/browser/web_ui.h" namespace { @@ -86,6 +88,10 @@ base::Unretained(this))); web_ui()->RegisterMessageCallback( + "dump", base::Bind(&SnippetsInternalsMessageHandler::HandleDump, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( "download", base::Bind(&SnippetsInternalsMessageHandler::HandleDownload, base::Unretained(this))); @@ -110,6 +116,19 @@ ntp_snippets_service_->ClearSnippets(); } +void SnippetsInternalsMessageHandler::HandleDump(const base::ListValue* args) { + DCHECK_EQ(0u, args->GetSize()); + + PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs(); + + std::string json; + base::JSONWriter::Write( + *pref_service->GetList(ntp_snippets::prefs::kSnippets), &json); + + web_ui()->CallJavascriptFunction("chrome.SnippetsInternals.receiveJson", + base::StringValue(json)); +} + void SnippetsInternalsMessageHandler::HandleClearDiscarded( const base::ListValue* args) { DCHECK_EQ(0u, args->GetSize());
diff --git a/chrome/browser/ui/webui/snippets_internals_message_handler.h b/chrome/browser/ui/webui/snippets_internals_message_handler.h index 89ef4ee..1b6bcf5 100644 --- a/chrome/browser/ui/webui/snippets_internals_message_handler.h +++ b/chrome/browser/ui/webui/snippets_internals_message_handler.h
@@ -37,6 +37,7 @@ void HandleLoaded(const base::ListValue* args); void HandleClear(const base::ListValue* args); + void HandleDump(const base::ListValue* args); void HandleClearDiscarded(const base::ListValue* args); void HandleDownload(const base::ListValue* args);
diff --git a/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc b/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc index d4e8ba9..f885e4db7 100644 --- a/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc +++ b/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc
@@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/values.h" +#include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/translate/chrome_translate_client.h" @@ -22,6 +23,7 @@ #include "components/translate/core/browser/translate_prefs.h" #include "components/translate/core/common/language_detection_details.h" #include "components/translate/core/common/translate_pref_names.h" +#include "components/variations/service/variations_service.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" @@ -60,6 +62,10 @@ &TranslateInternalsHandler::OnRemovePrefItem, base::Unretained(this))); web_ui()->RegisterMessageCallback("requestInfo", base::Bind( &TranslateInternalsHandler::OnRequestInfo, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "overrideCountry", + base::Bind(&TranslateInternalsHandler::OnOverrideCountry, + base::Unretained(this))); } void TranslateInternalsHandler::Observe( @@ -169,9 +175,22 @@ SendPrefsToJs(); } +void TranslateInternalsHandler::OnOverrideCountry(const base::ListValue* args) { + std::string country; + if (args->GetString(0, &country)) { + variations::VariationsService* variations_service = + g_browser_process->variations_service(); + if (variations_service) { + SendCountryToJs( + variations_service->OverrideStoredPermanentCountry(country)); + } + } +} + void TranslateInternalsHandler::OnRequestInfo(const base::ListValue* /*args*/) { SendPrefsToJs(); SendSupportedLanguagesToJs(); + SendCountryToJs(false); } void TranslateInternalsHandler::SendMessageToJs(const std::string& message, @@ -232,3 +251,18 @@ new base::FundamentalValue(last_updated.ToJsTime())); SendMessageToJs("supportedLanguagesUpdated", dict); } + +void TranslateInternalsHandler::SendCountryToJs(bool was_updated) { + std::string country; + variations::VariationsService* variations_service = + g_browser_process->variations_service(); + if (variations_service) + country = variations_service->GetStoredPermanentCountry(); + + base::DictionaryValue dict; + if (!country.empty()) { + dict.Set("country", new base::StringValue(country)); + dict.Set("update", new base::FundamentalValue(was_updated)); + } + SendMessageToJs("countryUpdated", dict); +}
diff --git a/chrome/browser/ui/webui/translate_internals/translate_internals_handler.h b/chrome/browser/ui/webui/translate_internals/translate_internals_handler.h index 7293dc674..c834dabe 100644 --- a/chrome/browser/ui/webui/translate_internals/translate_internals_handler.h +++ b/chrome/browser/ui/webui/translate_internals/translate_internals_handler.h
@@ -61,6 +61,10 @@ // when UI requests to remove an item in the preference. void OnRemovePrefItem(const base::ListValue* args); + // Handles the Javascript message 'overrideCountry'. This message is sent + // when UI requests to override the stored country. + void OnOverrideCountry(const base::ListValue* country); + // Handles the Javascript message 'requestInfo'. This message is sent // when UI needs to show information concerned with the translation. // For now, this returns only prefs to Javascript. @@ -76,6 +80,10 @@ // Sends the languages currently supported by the server to JavaScript. void SendSupportedLanguagesToJs(); + // Sends the stored permanent country to Javascript. + // |was_updated| tells Javascript if the country has been updated or not. + void SendCountryToJs(bool was_updated); + // Subscription for translate events coming from the translate language list. std::unique_ptr< translate::TranslateLanguageList::EventCallbackList::Subscription>
diff --git a/chromeos/BUILD.gn b/chromeos/BUILD.gn index cd5a37e..276a6576 100644 --- a/chromeos/BUILD.gn +++ b/chromeos/BUILD.gn
@@ -58,7 +58,7 @@ # can be converted to a source set. static_library("test_support") { testonly = true - configs += [ "//build/config/linux:dbus" ] + configs += [ "//build/config/linux/dbus" ] public_deps = [ ":chromeos", ":cryptohome_proto", @@ -118,7 +118,7 @@ static_library("test_support_without_gmock") { testonly = true - configs += [ "//build/config/linux:dbus" ] + configs += [ "//build/config/linux/dbus" ] deps = [ ":chromeos", ":cryptohome_proto", @@ -139,7 +139,7 @@ test("chromeos_unittests") { configs += [ - "//build/config/linux:dbus", + "//build/config/linux/dbus", "//third_party/nss:system_nss_no_ssl_config", ] deps = [
diff --git a/components/cronet/android/test/javatests/src/org/chromium/net/BidirectionalStreamQuicTest.java b/components/cronet/android/test/javatests/src/org/chromium/net/BidirectionalStreamQuicTest.java index a6591ef3..fc26c9d 100644 --- a/components/cronet/android/test/javatests/src/org/chromium/net/BidirectionalStreamQuicTest.java +++ b/components/cronet/android/test/javatests/src/org/chromium/net/BidirectionalStreamQuicTest.java
@@ -134,9 +134,9 @@ callback.blockForDone(); assertTrue(stream.isDone()); // Server terminated on us, so the stream must fail. - // QUIC reports this as QUIC_PROTOCOL_ERROR. + // QUIC reports this as ERR_QUIC_PROTOCOL_ERROR. Sometimes we get ERR_CONNECTION_REFUSED. assertNotNull(callback.mError); - assertEquals( - NetError.ERR_QUIC_PROTOCOL_ERROR, callback.mError.getCronetInternalErrorCode()); + assertTrue(NetError.ERR_QUIC_PROTOCOL_ERROR == callback.mError.getCronetInternalErrorCode() + || NetError.ERR_CONNECTION_REFUSED == callback.mError.getCronetInternalErrorCode()); } }
diff --git a/components/cronet/tools/cr_cronet.py b/components/cronet/tools/cr_cronet.py index 906657d..d3448c9 100755 --- a/components/cronet/tools/cr_cronet.py +++ b/components/cronet/tools/cr_cronet.py
@@ -88,7 +88,7 @@ gyp_defines = 'GYP_DEFINES="OS=' + target_os + ' enable_websockets=0 '+ \ 'disable_file_support=1 disable_ftp_support=1 '+ \ 'enable_errorprone=1 use_platform_icu_alternatives=1 ' + \ - 'disable_brotli_filter=1 use_openssl=1"' + 'disable_brotli_filter=1"' gn_args = 'target_os="' + target_os + '" enable_websockets=false '+ \ 'disable_file_support=true disable_ftp_support=true '+ \ 'use_errorprone_java_compiler=true use_platform_icu_alternatives=true '+ \
diff --git a/components/cronet/tools/package_ios.py b/components/cronet/tools/package_ios.py index 5ac62e3..520cb65b 100755 --- a/components/cronet/tools/package_ios.py +++ b/components/cronet/tools/package_ios.py
@@ -68,8 +68,7 @@ gyp_defines = 'GYP_DEFINES="OS=ios enable_websockets=0 '+ \ 'disable_file_support=1 disable_ftp_support=1 '+ \ 'enable_errorprone=1 use_platform_icu_alternatives=1 ' + \ - 'disable_brotli_filter=1 use_openssl=1 ' + \ - 'target_subarch=both"' + 'disable_brotli_filter=1 target_subarch=both"' if not options.skip_gyp: run (gyp_defines + ' gclient runhooks')
diff --git a/components/ntp_snippets/ntp_snippets_fetcher.cc b/components/ntp_snippets/ntp_snippets_fetcher.cc index 0dbf702..ac39f5d7 100644 --- a/components/ntp_snippets/ntp_snippets_fetcher.cc +++ b/components/ntp_snippets/ntp_snippets_fetcher.cc
@@ -56,7 +56,7 @@ "%s" " }," " \"global_scoring_params\": {" - " \"num_to_return\": 10" + " \"num_to_return\": %i" " }" " }" "}"; @@ -77,15 +77,15 @@ url_request_context_getter_(url_request_context_getter), is_stable_channel_(is_stable_channel) {} -NTPSnippetsFetcher::~NTPSnippetsFetcher() { -} +NTPSnippetsFetcher::~NTPSnippetsFetcher() {} scoped_ptr<NTPSnippetsFetcher::SnippetsAvailableCallbackList::Subscription> NTPSnippetsFetcher::AddCallback(const SnippetsAvailableCallback& callback) { return callback_list_.Add(callback); } -void NTPSnippetsFetcher::FetchSnippets(const std::set<std::string>& hosts) { +void NTPSnippetsFetcher::FetchSnippets(const std::set<std::string>& hosts, + int count) { // TODO(treib): What to do if there's already a pending request? const std::string& key = is_stable_channel_ ? google_apis::GetAPIKey() @@ -104,7 +104,8 @@ host_restricts += base::StringPrintf(kHostRestrictFormat, host.c_str()); url_fetcher_->SetUploadData("application/json", base::StringPrintf(kRequestParameterFormat, - host_restricts.c_str())); + host_restricts.c_str(), + count)); // Fetchers are sometimes cancelled because a network change was detected. url_fetcher_->SetAutomaticallyRetryOnNetworkChanges(3);
diff --git a/components/ntp_snippets/ntp_snippets_fetcher.h b/components/ntp_snippets/ntp_snippets_fetcher.h index 1c0b7d4..39c48e5d 100644 --- a/components/ntp_snippets/ntp_snippets_fetcher.h +++ b/components/ntp_snippets/ntp_snippets_fetcher.h
@@ -42,7 +42,7 @@ // Fetches snippets from the server. |hosts| can be used to restrict the // results to a set of hosts, e.g. "www.google.com". If it is empty, no // restrictions are applied. - void FetchSnippets(const std::set<std::string>& hosts); + void FetchSnippets(const std::set<std::string>& hosts, int count); private: // URLFetcherDelegate implementation.
diff --git a/components/ntp_snippets/ntp_snippets_service.cc b/components/ntp_snippets/ntp_snippets_service.cc index 84a13b1e..d1d349b 100644 --- a/components/ntp_snippets/ntp_snippets_service.cc +++ b/components/ntp_snippets/ntp_snippets_service.cc
@@ -33,6 +33,8 @@ namespace { +const int kMaxSnippetCount = 10; + const int kFetchingIntervalWifiChargingSeconds = 30 * 60; const int kFetchingIntervalWifiSeconds = 2 * 60 * 60; const int kFetchingIntervalFallbackSeconds = 24 * 60 * 60; @@ -235,11 +237,11 @@ const std::set<std::string>& hosts) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDontRestrict)) { - snippets_fetcher_->FetchSnippets(std::set<std::string>()); + snippets_fetcher_->FetchSnippets(std::set<std::string>(), kMaxSnippetCount); return; } if (!hosts.empty()) { - snippets_fetcher_->FetchSnippets(hosts); + snippets_fetcher_->FetchSnippets(hosts, kMaxSnippetCount); } else { last_fetch_status_ = kStatusMessageEmptyHosts; LoadingSnippetsFinished(); @@ -310,6 +312,11 @@ observers_.RemoveObserver(observer); } +// static +int NTPSnippetsService::GetMaxSnippetCountForTesting() { + return kMaxSnippetCount; +} + void NTPSnippetsService::OnSuggestionsChanged( const SuggestionsProfile& suggestions) { std::set<std::string> hosts = GetSuggestionsHostsImpl(suggestions); @@ -414,6 +421,11 @@ std::make_move_iterator(new_snippets.begin()), std::make_move_iterator(new_snippets.end())); + // If there are more snippets now than we want to show, drop the extra ones + // from the end of the list. + if (snippets_.size() > kMaxSnippetCount) + snippets_.resize(kMaxSnippetCount); + return true; }
diff --git a/components/ntp_snippets/ntp_snippets_service.h b/components/ntp_snippets/ntp_snippets_service.h index e6dac62e..e5e7282b 100644 --- a/components/ntp_snippets/ntp_snippets_service.h +++ b/components/ntp_snippets/ntp_snippets_service.h
@@ -95,7 +95,7 @@ // a snippet was discarded. bool DiscardSnippet(const GURL& url); - // Returns the lists of snippets previously discarded by the user (that are + // Returns the list of snippets previously discarded by the user (that are // not expired yet). const NTPSnippetStorage& discarded_snippets() const { return discarded_snippets_; @@ -124,6 +124,9 @@ const_iterator begin() const { return const_iterator(snippets_.begin()); } const_iterator end() const { return const_iterator(snippets_.end()); } + // Returns the maximum number of snippets that will be shown at once. + static int GetMaxSnippetCountForTesting(); + private: friend class NTPSnippetsServiceTest;
diff --git a/components/ntp_snippets/ntp_snippets_service_unittest.cc b/components/ntp_snippets/ntp_snippets_service_unittest.cc index 532385cf..a2c6d7a 100644 --- a/components/ntp_snippets/ntp_snippets_service_unittest.cc +++ b/components/ntp_snippets/ntp_snippets_service_unittest.cc
@@ -8,6 +8,7 @@ #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/thread_task_runner_handle.h" #include "base/time/time.h" @@ -256,6 +257,29 @@ EXPECT_EQ(first_snippet.url(), GURL("http://second")); } +TEST_F(NTPSnippetsServiceTest, LimitNumSnippets) { + int max_snippet_count = NTPSnippetsService::GetMaxSnippetCountForTesting(); + int snippets_per_load = max_snippet_count / 2 + 1; + + const char snippet_format[] = + "{ \"contentInfo\": { \"url\" : \"http://localhost/%i\" }}"; + std::vector<std::string> snippets1; + std::vector<std::string> snippets2; + for (int i = 0; i < snippets_per_load; i++) { + snippets1.push_back(base::StringPrintf(snippet_format, i)); + snippets2.push_back(base::StringPrintf(snippet_format, + snippets_per_load + i)); + } + + LoadFromJSONString( + "{ \"recos\": [ " + base::JoinString(snippets1, ", ") + "]}"); + ASSERT_EQ(snippets1.size(), service()->size()); + + LoadFromJSONString( + "{ \"recos\": [ " + base::JoinString(snippets2, ", ") + "]}"); + EXPECT_EQ(max_snippet_count, (int)service()->size()); +} + TEST_F(NTPSnippetsServiceTest, LoadInvalidJson) { SetExpectJsonParseSuccess(false); LoadFromJSONString(GetInvalidJson());
diff --git a/components/password_manager/core/browser/export/password_exporter.cc b/components/password_manager/core/browser/export/password_exporter.cc index d78f88c..01a4e01 100644 --- a/components/password_manager/core/browser/export/password_exporter.cc +++ b/components/password_manager/core/browser/export/password_exporter.cc
@@ -28,7 +28,7 @@ // static void PasswordExporter::Export( const base::FilePath& path, - std::vector<std::unique_ptr<autofill::PasswordForm>> passwords, + const std::vector<std::unique_ptr<autofill::PasswordForm>>& passwords, scoped_refptr<base::TaskRunner> blocking_task_runner) { blocking_task_runner->PostTask( FROM_HERE,
diff --git a/components/password_manager/core/browser/export/password_exporter.h b/components/password_manager/core/browser/export/password_exporter.h index 8adda0e..b8a96b5 100644 --- a/components/password_manager/core/browser/export/password_exporter.h +++ b/components/password_manager/core/browser/export/password_exporter.h
@@ -32,7 +32,7 @@ // the export will be selected based on the file extension in |path|. static void Export( const base::FilePath& path, - std::vector<std::unique_ptr<autofill::PasswordForm>> passwords, + const std::vector<std::unique_ptr<autofill::PasswordForm>>& passwords, scoped_refptr<base::TaskRunner> blocking_task_runner); // Returns the file extensions corresponding to supported formats.
diff --git a/components/password_manager/core/browser/export/password_exporter_unittest.cc b/components/password_manager/core/browser/export/password_exporter_unittest.cc index ad9a11d..57aefd1 100644 --- a/components/password_manager/core/browser/export/password_exporter_unittest.cc +++ b/components/password_manager/core/browser/export/password_exporter_unittest.cc
@@ -40,7 +40,7 @@ void StartExportAndWaitUntilCompleteThenReadOutput( const base::FilePath::StringType& provided_extension, const base::FilePath::StringType& expected_extension, - std::vector<std::unique_ptr<autofill::PasswordForm>> passwords, + const std::vector<std::unique_ptr<autofill::PasswordForm>>& passwords, std::string* output) { base::FilePath temporary_dir; ASSERT_TRUE(base::CreateNewTempDirectory(base::FilePath::StringType(), @@ -48,7 +48,7 @@ base::FilePath output_file = temporary_dir.AppendASCII("passwords").AddExtension(provided_extension); - PasswordExporter::Export(output_file, std::move(passwords), + PasswordExporter::Export(output_file, passwords, message_loop_.task_runner()); base::RunLoop run_loop;
diff --git a/components/password_manager/core/browser/password_bubble_experiment.cc b/components/password_manager/core/browser/password_bubble_experiment.cc index 6c9d60f..5171787 100644 --- a/components/password_manager/core/browser/password_bubble_experiment.cc +++ b/components/password_manager/core/browser/password_bubble_experiment.cc
@@ -93,8 +93,8 @@ } void TurnOffAutoSignin(PrefService* prefs) { - prefs->SetBoolean( - password_manager::prefs::kWasAutoSignInFirstRunExperienceShown, true); + prefs->SetBoolean(password_manager::prefs::kCredentialsEnableAutosignin, + false); } } // namespace password_bubble_experiment
diff --git a/components/user_manager/fake_user_manager.cc b/components/user_manager/fake_user_manager.cc index b91df2e5..0a968910 100644 --- a/components/user_manager/fake_user_manager.cc +++ b/components/user_manager/fake_user_manager.cc
@@ -105,10 +105,7 @@ if (active_account_id_.is_valid()) { for (user_manager::UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) { - // TODO (alemate): Chenge this to GetAccountId(), once a real AccountId - // is - // passed. crbug.com/546876 - if ((*it)->GetEmail() == active_account_id_.GetUserEmail()) + if ((*it)->GetAccountId() == active_account_id_) return *it; } }
diff --git a/components/variations/service/variations_service.cc b/components/variations/service/variations_service.cc index 9e0c4c7..67e98840 100644 --- a/components/variations/service/variations_service.cc +++ b/components/variations/service/variations_service.cc
@@ -31,7 +31,6 @@ #include "components/variations/variations_seed_simulator.h" #include "components/variations/variations_switches.h" #include "components/variations/variations_url_constants.h" -#include "components/version_info/version_info.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" #include "net/base/network_change_notifier.h" @@ -842,12 +841,17 @@ } // Otherwise, update the pref with the current Chrome version and country. + StorePermanentCountry(version, latest_country); + return latest_country; +} + +void VariationsService::StorePermanentCountry(const base::Version& version, + const std::string& country) { base::ListValue new_list_value; new_list_value.AppendString(version.GetString()); - new_list_value.AppendString(latest_country); + new_list_value.AppendString(country); local_state_->Set(prefs::kVariationsPermanentConsistencyCountry, new_list_value); - return latest_country; } std::string VariationsService::GetStoredPermanentCountry() { @@ -862,4 +866,26 @@ return stored_country; } +bool VariationsService::OverrideStoredPermanentCountry( + const std::string& country_override) { + DCHECK(thread_checker_.CalledOnValidThread()); + + if (country_override.empty()) + return false; + + const base::ListValue* list_value = + local_state_->GetList(prefs::kVariationsPermanentConsistencyCountry); + + std::string stored_country; + const bool got_stored_country = + list_value->GetSize() == 2 && list_value->GetString(1, &stored_country); + + if (got_stored_country && stored_country == country_override) + return false; + + base::Version version(version_info::GetVersionNumber()); + StorePermanentCountry(version, country_override); + return true; +} + } // namespace variations
diff --git a/components/variations/service/variations_service.h b/components/variations/service/variations_service.h index 61c61731..49acabf 100644 --- a/components/variations/service/variations_service.h +++ b/components/variations/service/variations_service.h
@@ -21,6 +21,7 @@ #include "components/variations/variations_request_scheduler.h" #include "components/variations/variations_seed_simulator.h" #include "components/variations/variations_seed_store.h" +#include "components/version_info/version_info.h" #include "components/web_resource/resource_request_allowed_notifier.h" #include "net/url_request/url_fetcher_delegate.h" #include "url/gurl.h" @@ -121,6 +122,12 @@ // in the format of lowercase ISO 3166-1 alpha-2. Example: us, br, in std::string GetStoredPermanentCountry(); + // Forces an override of the stored permanent country. Returns true + // if the variable has been updated. Return false if the override country is + // the same as the stored variable, or if the update failed for any other + // reason. + bool OverrideStoredPermanentCountry(const std::string& override_country); + // Exposed for testing. static std::string GetDefaultVariationsServerURLForTesting(); @@ -219,6 +226,10 @@ // so that it can be overridden by tests. virtual bool LoadSeed(VariationsSeed* seed); + // Sets the stored permanent country pref for this client. + void StorePermanentCountry(const base::Version& version, + const std::string& country); + // Checks if prerequisites for fetching the Variations seed are met, and if // so, performs the actual fetch using |DoActualFetch|. void FetchVariationsSeed();
diff --git a/components/variations/service/variations_service_unittest.cc b/components/variations/service/variations_service_unittest.cc index aea08e3..edbb8ccd 100644 --- a/components/variations/service/variations_service_unittest.cc +++ b/components/variations/service/variations_service_unittest.cc
@@ -728,4 +728,64 @@ } } +TEST_F(VariationsServiceTest, OverrideStoredPermanentCountry) { + const std::string kTestVersion = version_info::GetVersionNumber(); + const std::string kPrefCa = version_info::GetVersionNumber() + ",ca"; + const std::string kPrefUs = version_info::GetVersionNumber() + ",us"; + + struct { + // Comma separated list, empty string if the pref isn't set initially. + const std::string pref_value_before; + const std::string country_code_override; + // Comma separated list. + const std::string expected_pref_value_after; + // Is the pref expected to be updated or not. + const bool has_updated; + } test_cases[] = { + {kPrefUs, "ca", kPrefCa, true}, + {kPrefUs, "us", kPrefUs, false}, + {kPrefUs, "", kPrefUs, false}, + {"", "ca", kPrefCa, true}, + {"", "", "", false}, + {"19.0.0.0,us", "ca", kPrefCa, true}, + {"19.0.0.0,us", "us", "19.0.0.0,us", false}, + }; + + for (const auto& test : test_cases) { + TestingPrefServiceSimple prefs; + VariationsService::RegisterPrefs(prefs.registry()); + TestVariationsService service( + make_scoped_ptr(new web_resource::TestRequestAllowedNotifier(&prefs)), + &prefs); + + if (!test.pref_value_before.empty()) { + base::ListValue list_value; + for (const std::string& component : + base::SplitString(test.pref_value_before, ",", base::TRIM_WHITESPACE, + base::SPLIT_WANT_ALL)) { + list_value.AppendString(component); + } + prefs.Set(prefs::kVariationsPermanentConsistencyCountry, list_value); + } + + variations::VariationsSeed seed(CreateTestSeed()); + + EXPECT_EQ(test.has_updated, service.OverrideStoredPermanentCountry( + test.country_code_override)) + << test.pref_value_before << ", " << test.country_code_override; + + base::ListValue expected_list_value; + for (const std::string& component : + base::SplitString(test.expected_pref_value_after, ",", + base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { + expected_list_value.AppendString(component); + } + const base::ListValue* pref_value = + prefs.GetList(prefs::kVariationsPermanentConsistencyCountry); + EXPECT_EQ(ListValueToString(expected_list_value), + ListValueToString(*pref_value)) + << test.pref_value_before << ", " << test.country_code_override; + } +} + } // namespace variations
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 9b9b44fb..b98c5f9 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -281,9 +281,9 @@ "//content") configs += [ - "//build/config/linux:atk", - "//build/config/linux:atk_warnings", - "//build/config/linux:gconf", + "//build/config/linux/atk", + "//build/config/linux/atk:warnings", + "//build/config/linux/gconf", "//build/config/linux:glib", ] } @@ -323,7 +323,7 @@ } if (use_pango) { - configs += [ "//build/config/linux:pangocairo" ] + configs += [ "//build/config/linux/pangocairo" ] } if (is_android) {
diff --git a/content/browser/frame_host/navigator_impl.cc b/content/browser/frame_host/navigator_impl.cc index b7da1a0..0cf5f6e 100644 --- a/content/browser/frame_host/navigator_impl.cc +++ b/content/browser/frame_host/navigator_impl.cc
@@ -675,7 +675,7 @@ // Send the navigation to the current FrameTreeNode if it's destined for a // subframe in the current tab. We'll assume it's for the main frame // (possibly of a new or different WebContents) otherwise. - if (SiteIsolationPolicy::AreCrossProcessFramesPossible() && + if (SiteIsolationPolicy::UseSubframeNavigationEntries() && disposition == CURRENT_TAB && render_frame_host->GetParent()) { frame_tree_node_id = render_frame_host->frame_tree_node()->frame_tree_node_id();
diff --git a/content/browser/frame_host/render_frame_host_manager_browsertest.cc b/content/browser/frame_host/render_frame_host_manager_browsertest.cc index e53c889..f9cb30e 100644 --- a/content/browser/frame_host/render_frame_host_manager_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_manager_browsertest.cc
@@ -2654,9 +2654,11 @@ // a.com window. NavigateToURL(new_shell, embedded_test_server()->GetURL( "b.com", "/cross-site/a.com/title1.html")); - if (AreAllSitesIsolatedForTesting()) { + if (AreAllSitesIsolatedForTesting() || IsBrowserSideNavigationEnabled()) { // In --site-per-process mode, both windows will actually be in the same // process. + // PlzNavigate: the SiteInstance for the navigation is determined after the + // redirect. So both windows will actually be in the same process. EXPECT_EQ(shell()->web_contents()->GetSiteInstance(), new_shell->web_contents()->GetSiteInstance()); } else { @@ -2675,7 +2677,7 @@ " }\n" "})())", &result)); - if (AreAllSitesIsolatedForTesting()) { + if (AreAllSitesIsolatedForTesting() || IsBrowserSideNavigationEnabled()) { EXPECT_THAT(result, ::testing::MatchesRegex("http://a.com:\\d+/title1.html")); } else {
diff --git a/content/browser/renderer_host/media/media_stream_dispatcher_host.cc b/content/browser/renderer_host/media/media_stream_dispatcher_host.cc index 033dbb65..f325e92 100644 --- a/content/browser/renderer_host/media/media_stream_dispatcher_host.cc +++ b/content/browser/renderer_host/media/media_stream_dispatcher_host.cc
@@ -90,6 +90,14 @@ render_frame_id, page_request_id, label, video_device)); } +void MediaStreamDispatcherHost::DevicesChanged(MediaStreamType type) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + DVLOG(1) << "MediaStreamDispatcherHost::DevicesChanged(" + << "{type = " << type << "})"; + // TODO(guidou): check permissions and forward notifications to renderer. + // crbug.com/388648 +} + bool MediaStreamDispatcherHost::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(MediaStreamDispatcherHost, message)
diff --git a/content/browser/renderer_host/media/media_stream_dispatcher_host.h b/content/browser/renderer_host/media/media_stream_dispatcher_host.h index a101067c6..088154b 100644 --- a/content/browser/renderer_host/media/media_stream_dispatcher_host.h +++ b/content/browser/renderer_host/media/media_stream_dispatcher_host.h
@@ -54,6 +54,7 @@ int page_request_id, const std::string& label, const StreamDeviceInfo& video_device) override; + void DevicesChanged(MediaStreamType type) override; // BrowserMessageFilter implementation. bool OnMessageReceived(const IPC::Message& message) override;
diff --git a/content/browser/renderer_host/media/media_stream_manager.cc b/content/browser/renderer_host/media/media_stream_manager.cc index d1db867..c63084f 100644 --- a/content/browser/renderer_host/media/media_stream_manager.cc +++ b/content/browser/renderer_host/media/media_stream_manager.cc
@@ -7,6 +7,7 @@ #include <stddef.h> #include <stdint.h> #include <string.h> +#include <algorithm> #include <cctype> #include <list> #include <utility> @@ -419,6 +420,7 @@ DVLOG(1) << "~MediaStreamManager"; DCHECK(requests_.empty()); DCHECK(!device_task_runner_.get()); + DCHECK(device_change_subscribers_.empty()); base::PowerMonitor* power_monitor = base::PowerMonitor::Get(); // The PowerMonitor instance owned by BrowserMainLoops always outlives the @@ -1708,6 +1710,7 @@ // Only cache the device list when the device list has been changed. bool need_update_clients = false; + bool need_update_device_change_subscribers = false; EnumerationCache* cache = stream_type == MEDIA_DEVICE_AUDIO_CAPTURE ? &audio_enumeration_cache_ : &video_enumeration_cache_; @@ -1715,8 +1718,13 @@ !std::equal(devices.begin(), devices.end(), cache->devices.begin(), StreamDeviceInfo::IsEqual)) { StopRemovedDevices(cache->devices, devices); - cache->devices = devices; need_update_clients = true; + // Device-change subscribers should not be notified the first time the cache + // is loaded , as this is not a change in the set of devices. The same + // applies to enumerations listing no devices when the cache is empty. + need_update_device_change_subscribers = + cache->valid && (devices.size() != 0 || cache->devices.size() != 0); + cache->devices = devices; // The device might not be able to be enumerated when it is not warmed up, // for example, when the machine just wakes up from sleep. We set the cache @@ -1728,6 +1736,9 @@ if (need_update_clients && monitoring_started_) NotifyDevicesChanged(stream_type, devices); + if (need_update_device_change_subscribers) + NotifyDeviceChangeSubscribers(stream_type); + // Publish the result for all requests waiting for device list(s). // Find the requests waiting for this device list, store their labels and // release the iterator before calling device settings. We might get a call @@ -2083,6 +2094,33 @@ log_callbacks_.erase(renderer_host_id); } +void MediaStreamManager::SubscribeToDeviceChangeNotifications( + MediaStreamRequester* subscriber) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK(subscriber); + DCHECK(std::find_if(device_change_subscribers_.begin(), + device_change_subscribers_.end(), + [subscriber](MediaStreamRequester* item) { + return subscriber == item; + }) == device_change_subscribers_.end()); + device_change_subscribers_.push_back(subscriber); +} + +void MediaStreamManager::CancelDeviceChangeNotifications( + MediaStreamRequester* subscriber) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + auto it = std::find(device_change_subscribers_.begin(), + device_change_subscribers_.end(), subscriber); + DCHECK(it != device_change_subscribers_.end()); + device_change_subscribers_.erase(it); +} + +void MediaStreamManager::NotifyDeviceChangeSubscribers(MediaStreamType type) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + for (auto* subscriber : device_change_subscribers_) + subscriber->DevicesChanged(type); +} + // static std::string MediaStreamManager::GetHMACForMediaDeviceID( const ResourceContext::SaltCallback& sc,
diff --git a/content/browser/renderer_host/media/media_stream_manager.h b/content/browser/renderer_host/media/media_stream_manager.h index 52c3fa7..afca478 100644 --- a/content/browser/renderer_host/media/media_stream_manager.h +++ b/content/browser/renderer_host/media/media_stream_manager.h
@@ -31,6 +31,7 @@ #include <memory> #include <string> #include <utility> +#include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" @@ -222,6 +223,15 @@ const base::Callback<void(const std::string&)>& callback); void UnregisterNativeLogCallback(int renderer_host_id); + // Register and unregister subscribers for device-change notifications. + // It is an error to try to subscribe a |subscriber| that is already + // subscribed or to cancel the subscription of a |subscriber| that is not + // subscribed. Also, subscribers must make sure to invoke + // CancelDeviceChangeNotifications() before destruction. Otherwise, dangling + // pointers and use-after-destruction problems will occur. + void SubscribeToDeviceChangeNotifications(MediaStreamRequester* subscriber); + void CancelDeviceChangeNotifications(MediaStreamRequester* subscriber); + // Generates a hash of a device's unique ID usable by one // particular security origin. static std::string GetHMACForMediaDeviceID( @@ -401,6 +411,8 @@ const base::Callback<void(const std::string&)>& callback); void DoNativeLogCallbackUnregistration(int renderer_host_id); + void NotifyDeviceChangeSubscribers(MediaStreamType type); + // Task runner shared by VideoCaptureManager and AudioInputDeviceManager and // used for enumerating audio output devices. // Note: Enumeration tasks may take seconds to complete so must never be run @@ -436,6 +448,9 @@ // Maps render process hosts to log callbacks. Used on the IO thread. std::map<int, base::Callback<void(const std::string&)>> log_callbacks_; + // Objects subscribed to changes in the set of media devices. + std::vector<MediaStreamRequester*> device_change_subscribers_; + DISALLOW_COPY_AND_ASSIGN(MediaStreamManager); };
diff --git a/content/browser/renderer_host/media/media_stream_manager_unittest.cc b/content/browser/renderer_host/media/media_stream_manager_unittest.cc index 6e7bec31..d93d7cb 100644 --- a/content/browser/renderer_host/media/media_stream_manager_unittest.cc +++ b/content/browser/renderer_host/media/media_stream_manager_unittest.cc
@@ -74,17 +74,23 @@ : AudioManagerPlatform(base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get(), &fake_audio_log_factory_), - num_output_devices_(2) {} + num_output_devices_(2), + num_input_devices_(2) {} ~MockAudioManager() override {} void GetAudioInputDeviceNames( media::AudioDeviceNames* device_names) override { DCHECK(device_names->empty()); - if (HasAudioInputDevices()) { - AudioManagerBase::GetAudioInputDeviceNames(device_names); - } else { - device_names->push_back(media::AudioDeviceName("fake_device_name", - "fake_device_id")); + + // AudioManagers add a default device when there is at least one real device + if (num_input_devices_ > 0) { + device_names->push_back(media::AudioDeviceName( + "Default", AudioManagerBase::kDefaultDeviceId)); + } + for (size_t i = 0; i < num_input_devices_; i++) { + device_names->push_back(media::AudioDeviceName( + std::string("fake_device_name_") + base::SizeTToString(i), + std::string("fake_device_id_") + base::SizeTToString(i))); } } @@ -119,17 +125,32 @@ num_output_devices_ = num_devices; } + void SetNumAudioInputDevices(size_t num_devices) { + num_input_devices_ = num_devices; + } + private: media::FakeAudioLogFactory fake_audio_log_factory_; size_t num_output_devices_; + size_t num_input_devices_; DISALLOW_COPY_AND_ASSIGN(MockAudioManager); }; class MockMediaStreamRequester : public MediaStreamRequester { public: - MockMediaStreamRequester(base::RunLoop* run_loop, size_t num_expected_devices) - : run_loop_(run_loop), num_expected_devices_(num_expected_devices) {} - virtual ~MockMediaStreamRequester() {} + MockMediaStreamRequester(MediaStreamManager* media_stream_manager, + base::RunLoop* run_loop_enumeration, + size_t num_expected_devices, + base::RunLoop* run_loop_devices_changed) + : media_stream_manager_(media_stream_manager), + run_loop_enumeration_(run_loop_enumeration), + num_expected_devices_(num_expected_devices), + run_loop_devices_changed_(run_loop_devices_changed), + is_device_change_subscriber_(false) {} + virtual ~MockMediaStreamRequester() { + if (is_device_change_subscriber_) + media_stream_manager_->CancelDeviceChangeNotifications(this); + } // MediaStreamRequester implementation. MOCK_METHOD5(StreamGenerated, @@ -153,7 +174,8 @@ MockDevicesEnumerated(render_frame_id, page_request_id, label, devices); EXPECT_EQ(num_expected_devices_, devices.size()); - run_loop_->Quit(); + if (run_loop_enumeration_) + run_loop_enumeration_->Quit(); } MOCK_METHOD4(MockDevicesEnumerated, void(int render_frame_id, @@ -165,11 +187,28 @@ int page_request_id, const std::string& label, const StreamDeviceInfo& device_info)); + void DevicesChanged(MediaStreamType type) override { + MockDevicesChanged(type); + if (run_loop_devices_changed_) + run_loop_devices_changed_->Quit(); + } + MOCK_METHOD1(MockDevicesChanged, void(MediaStreamType type)); + + void SubscribeToDeviceChangeNotifications() { + if (is_device_change_subscriber_) + return; + + media_stream_manager_->SubscribeToDeviceChangeNotifications(this); + is_device_change_subscriber_ = true; + } private: - DISALLOW_COPY_AND_ASSIGN(MockMediaStreamRequester); - base::RunLoop* run_loop_; + MediaStreamManager* media_stream_manager_; + base::RunLoop* run_loop_enumeration_; size_t num_expected_devices_; + base::RunLoop* run_loop_devices_changed_; + bool is_device_change_subscriber_; + DISALLOW_COPY_AND_ASSIGN(MockMediaStreamRequester); }; } // namespace @@ -311,8 +350,9 @@ for (size_t num_devices = 0; num_devices < 3; num_devices++) { audio_manager_->SetNumAudioOutputDevices(num_devices); base::RunLoop run_loop; - MockMediaStreamRequester requester(&run_loop, - num_devices == 0 ? 0 : num_devices + 1); + MockMediaStreamRequester requester(media_stream_manager_.get(), &run_loop, + num_devices == 0 ? 0 : num_devices + 1, + nullptr); const int render_process_id = 1; const int render_frame_id = 1; const int page_request_id = 1; @@ -328,4 +368,63 @@ } } +TEST_F(MediaStreamManagerTest, NotifyDeviceChanges) { + const int render_process_id = 1; + const int render_frame_id = 1; + const int page_request_id = 1; + const GURL security_origin("http://localhost"); + + // Check that device change notifications are received + { + // First run an enumeration to warm up the cache + base::RunLoop run_loop_enumeration; + base::RunLoop run_loop_device_change; + MockMediaStreamRequester requester(media_stream_manager_.get(), + &run_loop_enumeration, 3, + &run_loop_device_change); + audio_manager_->SetNumAudioInputDevices(2); + requester.SubscribeToDeviceChangeNotifications(); + + EXPECT_CALL(requester, + MockDevicesEnumerated(render_frame_id, page_request_id, _, _)); + EXPECT_CALL(requester, MockDevicesChanged(_)).Times(0); + std::string label = media_stream_manager_->EnumerateDevices( + &requester, render_process_id, render_frame_id, GetMockSaltCallback(), + page_request_id, MEDIA_DEVICE_AUDIO_CAPTURE, security_origin); + run_loop_enumeration.Run(); + media_stream_manager_->CancelRequest(label); + + // Simulate device change + EXPECT_CALL(requester, MockDevicesChanged(_)); + audio_manager_->SetNumAudioInputDevices(3); + media_stream_manager_->OnDevicesChanged( + base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE); + run_loop_device_change.Run(); + } + + // Check that bogus device changes where devices have not changed + // do not trigger a notification. + { + base::RunLoop run_loop; + MockMediaStreamRequester requester(media_stream_manager_.get(), &run_loop, + 4, &run_loop); + requester.SubscribeToDeviceChangeNotifications(); + + // Bogus OnDeviceChange, as devices have not changed. Should not trigger + // notification. + EXPECT_CALL(requester, MockDevicesChanged(_)).Times(0); + media_stream_manager_->OnDevicesChanged( + base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE); + + // Do enumeration to be able to quit the RunLoop. + EXPECT_CALL(requester, + MockDevicesEnumerated(render_frame_id, page_request_id, _, _)); + std::string label = media_stream_manager_->EnumerateDevices( + &requester, render_process_id, render_frame_id, GetMockSaltCallback(), + page_request_id, MEDIA_DEVICE_AUDIO_CAPTURE, security_origin); + run_loop.Run(); + media_stream_manager_->CancelRequest(label); + } +} + } // namespace content
diff --git a/content/browser/renderer_host/media/media_stream_requester.h b/content/browser/renderer_host/media/media_stream_requester.h index c36f1666..fc475dde 100644 --- a/content/browser/renderer_host/media/media_stream_requester.h +++ b/content/browser/renderer_host/media/media_stream_requester.h
@@ -44,6 +44,9 @@ int page_request_id, const std::string& label, const StreamDeviceInfo& device_info) = 0; + // Called when the set of media devices has changed, provided the + // MediaStreamRequester is subscribed and authorized to receive such messages. + virtual void DevicesChanged(MediaStreamType type) = 0; protected: virtual ~MediaStreamRequester() {
diff --git a/content/browser/renderer_host/media/video_capture_host_unittest.cc b/content/browser/renderer_host/media/video_capture_host_unittest.cc index a5f56706..93c8d583 100644 --- a/content/browser/renderer_host/media/video_capture_host_unittest.cc +++ b/content/browser/renderer_host/media/video_capture_host_unittest.cc
@@ -121,6 +121,7 @@ int page_request_id, const std::string& label, const StreamDeviceInfo& device_info)); + MOCK_METHOD1(DevicesChanged, void(MediaStreamType type)); private: DISALLOW_COPY_AND_ASSIGN(MockMediaStreamRequester);
diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index 30101b4a..20196095 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn
@@ -287,7 +287,7 @@ } if (use_pango) { - configs += [ "//build/config/linux:pangocairo" ] + configs += [ "//build/config/linux/pangocairo" ] if (use_ozone) { # If we're using pango, never use this ozone file (it was removed in all # non-ozone cases above).
diff --git a/content/common/frame_messages.h b/content/common/frame_messages.h index b128439d..72baac5 100644 --- a/content/common/frame_messages.h +++ b/content/common/frame_messages.h
@@ -669,7 +669,7 @@ IPC_MESSAGE_ROUTED1(FrameMsg_CSSInsertRequest, std::string /* css */) -// Add message to the devtools console. +// Add message to the frame console. IPC_MESSAGE_ROUTED2(FrameMsg_AddMessageToConsole, content::ConsoleMessageLevel /* level */, std::string /* message */)
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/input/ImeTest.java b/content/public/android/javatests/src/org/chromium/content/browser/input/ImeTest.java index 500fe84a..75809c5 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/input/ImeTest.java +++ b/content/public/android/javatests/src/org/chromium/content/browser/input/ImeTest.java
@@ -197,6 +197,7 @@ @SmallTest @Feature({"TextInput"}) + @FlakyTest(message = "crbug.com/603991") public void testImeCopy() throws Exception { commitText("hello", 1); waitAndVerifyUpdateSelection(0, 5, 5, -1, -1); @@ -531,6 +532,7 @@ @SmallTest @Feature({"TextInput"}) + @FlakyTest(message = "crbug.com/603991") public void testImeCut() throws Exception { commitText("snarful", 1); waitAndVerifyUpdateSelection(0, 7, 7, -1, -1);
diff --git a/content/renderer/devtools/devtools_agent.cc b/content/renderer/devtools/devtools_agent.cc index 9d638d57..78dcd5a 100644 --- a/content/renderer/devtools/devtools_agent.cc +++ b/content/renderer/devtools/devtools_agent.cc
@@ -21,11 +21,9 @@ #include "ipc/ipc_channel.h" #include "third_party/WebKit/public/platform/WebPoint.h" #include "third_party/WebKit/public/platform/WebString.h" -#include "third_party/WebKit/public/web/WebConsoleMessage.h" #include "third_party/WebKit/public/web/WebDevToolsAgent.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" -using blink::WebConsoleMessage; using blink::WebDevToolsAgent; using blink::WebDevToolsAgentClient; using blink::WebLocalFrame; @@ -245,29 +243,6 @@ GetWebAgent()->failedToRequestDevTools(); } -void DevToolsAgent::AddMessageToConsole(ConsoleMessageLevel level, - const std::string& message) { - WebLocalFrame* web_frame = frame_->GetWebFrame(); - - WebConsoleMessage::Level target_level = WebConsoleMessage::LevelLog; - switch (level) { - case CONSOLE_MESSAGE_LEVEL_DEBUG: - target_level = WebConsoleMessage::LevelDebug; - break; - case CONSOLE_MESSAGE_LEVEL_LOG: - target_level = WebConsoleMessage::LevelLog; - break; - case CONSOLE_MESSAGE_LEVEL_WARNING: - target_level = WebConsoleMessage::LevelWarning; - break; - case CONSOLE_MESSAGE_LEVEL_ERROR: - target_level = WebConsoleMessage::LevelError; - break; - } - web_frame->addMessageToConsole( - WebConsoleMessage(target_level, WebString::fromUTF8(message))); -} - void DevToolsAgent::ContinueProgram() { GetWebAgent()->continueProgram(); }
diff --git a/content/renderer/devtools/devtools_agent.h b/content/renderer/devtools/devtools_agent.h index 4ae5d7f5..7fc1d06 100644 --- a/content/renderer/devtools/devtools_agent.h +++ b/content/renderer/devtools/devtools_agent.h
@@ -11,7 +11,6 @@ #include "base/callback.h" #include "base/macros.h" #include "content/common/content_export.h" -#include "content/public/common/console_message_level.h" #include "content/public/renderer/render_frame_observer.h" #include "third_party/WebKit/public/web/WebDevToolsAgentClient.h" @@ -48,9 +47,6 @@ bool IsAttached(); - void AddMessageToConsole(ConsoleMessageLevel level, - const std::string& message); - private: friend class DevToolsAgentTest;
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 301ffe6..316bda4 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -161,6 +161,7 @@ #include "third_party/WebKit/public/platform/WebURLResponse.h" #include "third_party/WebKit/public/platform/WebVector.h" #include "third_party/WebKit/public/web/WebColorSuggestion.h" +#include "third_party/WebKit/public/web/WebConsoleMessage.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFindOptions.h" #include "third_party/WebKit/public/web/WebFrameSerializer.h" @@ -2359,8 +2360,25 @@ void RenderFrameImpl::AddMessageToConsole(ConsoleMessageLevel level, const std::string& message) { - if (devtools_agent_) - devtools_agent_->AddMessageToConsole(level, message); + blink::WebConsoleMessage::Level target_level = + blink::WebConsoleMessage::LevelLog; + switch (level) { + case CONSOLE_MESSAGE_LEVEL_DEBUG: + target_level = blink::WebConsoleMessage::LevelDebug; + break; + case CONSOLE_MESSAGE_LEVEL_LOG: + target_level = blink::WebConsoleMessage::LevelLog; + break; + case CONSOLE_MESSAGE_LEVEL_WARNING: + target_level = blink::WebConsoleMessage::LevelWarning; + break; + case CONSOLE_MESSAGE_LEVEL_ERROR: + target_level = blink::WebConsoleMessage::LevelError; + break; + } + + blink::WebConsoleMessage wcm(target_level, WebString::fromUTF8(message)); + frame_->addMessageToConsole(wcm); } bool RenderFrameImpl::IsUsingLoFi() const {
diff --git a/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py b/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py index afe11eb..11200f8 100644 --- a/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py +++ b/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py
@@ -312,6 +312,10 @@ 'tex-2d-rgba8-rgba-unsigned_byte.html', ['win', 'debug'], bug=542901) + # Win / NVidia + self.Fail('deqp/functional/gles3/texturefiltering/cube_sizes_00.html', + ['win', 'nvidia'], bug=606021) + # Win / AMD # It's unfortunate that this suppression needs to be so broad, but # basically any test that uses readPixels is potentially flaky, and @@ -319,7 +323,7 @@ self.Flaky('conformance2/*', ['win', ('amd', 0x6779)], bug=491419) self.Flaky('deqp/*', ['win', ('amd', 0x6779)], bug=491419) self.Fail('deqp/functional/gles3/texturefiltering/cube_sizes_00.html', - ['win', ('amd', 0x6779), ('nvidia', 0x104a)], bug=606021) + ['win', ('amd', 0x6779)], bug=606021) # Win / Intel self.Fail('conformance2/buffers/uniform-buffers.html',
diff --git a/content/test/gpu/gpu_tests/webgl_conformance_expectations.py b/content/test/gpu/gpu_tests/webgl_conformance_expectations.py index 03737dd..5ccc6b09 100644 --- a/content/test/gpu/gpu_tests/webgl_conformance_expectations.py +++ b/content/test/gpu/gpu_tests/webgl_conformance_expectations.py
@@ -284,7 +284,7 @@ ['linux', 'intel'], bug=1312) # ANGLE bug id. See also 598910 self.Fail('conformance/glsl/bugs/sampler-array-using-loop-index.html', ['linux', 'intel', 'opengl'], bug=598924) - self.Fail('conformance/uniforms/gl-uniform-arrays.html', + self.Skip('conformance/uniforms/gl-uniform-arrays.html', ['linux', 'debug', ('intel', 0x412)], bug=604140) self.Fail('conformance/extensions/webgl-draw-buffers.html', ['linux', ('intel', 0x412), 'opengl'], bug=586536)
diff --git a/dbus/BUILD.gn b/dbus/BUILD.gn index dbeee0c..1502ca75 100644 --- a/dbus/BUILD.gn +++ b/dbus/BUILD.gn
@@ -45,7 +45,7 @@ "//base", ] - public_configs = [ "//build/config/linux:dbus" ] + public_configs = [ "//build/config/linux/dbus" ] } proto_library("test_proto") { @@ -76,7 +76,7 @@ "//testing/gmock", ] - configs += [ "//build/config/linux:dbus" ] + configs += [ "//build/config/linux/dbus" ] } test("dbus_unittests") { @@ -109,7 +109,7 @@ "//third_party/protobuf:protobuf_lite", ] - configs += [ "//build/config/linux:dbus" ] + configs += [ "//build/config/linux/dbus" ] } executable("dbus_test_server") { @@ -127,5 +127,5 @@ "//build/config/sanitizers:deps", ] - configs += [ "//build/config/linux:dbus" ] + configs += [ "//build/config/linux/dbus" ] }
diff --git a/device/BUILD.gn b/device/BUILD.gn index 7dbd214..acfb715 100644 --- a/device/BUILD.gn +++ b/device/BUILD.gn
@@ -154,7 +154,7 @@ } if ((is_chromeos || is_linux) && use_dbus) { - configs += [ "//build/config/linux:dbus" ] + configs += [ "//build/config/linux/dbus" ] sources += [ "bluetooth/bluez/bluetooth_adapter_profile_bluez_unittest.cc",
diff --git a/device/battery/BUILD.gn b/device/battery/BUILD.gn index 9876bc6..70c1d26 100644 --- a/device/battery/BUILD.gn +++ b/device/battery/BUILD.gn
@@ -36,7 +36,7 @@ ] if (is_chromeos) { - configs += [ "//build/config/linux:dbus" ] + configs += [ "//build/config/linux/dbus" ] deps += [ "//chromeos:chromeos", "//chromeos:power_manager_proto", @@ -49,7 +49,7 @@ if (is_linux && !is_chromeos) { if (use_dbus) { - configs += [ "//build/config/linux:dbus" ] + configs += [ "//build/config/linux/dbus" ] deps += [ "//dbus" ] sources -= [ "battery_status_manager_default.cc" ] } else {
diff --git a/extensions/browser/BUILD.gn b/extensions/browser/BUILD.gn index e044a7a..419afc8 100644 --- a/extensions/browser/BUILD.gn +++ b/extensions/browser/BUILD.gn
@@ -83,7 +83,7 @@ sources += nonchromeos_sources if (is_linux) { - configs += [ "//build/config/linux:dbus" ] + configs += [ "//build/config/linux/dbus" ] deps += [ "//dbus" ] linux_sources = rebase_path( extensions_gypi_values.extensions_browser_sources_linux_nonchromeos,
diff --git a/gpu/gpu.gyp b/gpu/gpu.gyp index 5186fe9..61ebe80 100644 --- a/gpu/gpu.gyp +++ b/gpu/gpu.gyp
@@ -312,6 +312,7 @@ '../testing/gmock.gyp:gmock', '../third_party/mesa/mesa.gyp:mesa_headers', '../ui/gfx/gfx.gyp:gfx_test_support', + '../ui/gl/gl.gyp:gl', '../ui/gl/gl.gyp:gl_unittest_utils', '../ui/gl/gl.gyp:gl_test_support', '../url/url.gyp:url_lib',
diff --git a/headless/BUILD.gn b/headless/BUILD.gn index 7b693f7..5133e623 100644 --- a/headless/BUILD.gn +++ b/headless/BUILD.gn
@@ -329,8 +329,6 @@ } executable("headless_shell") { - testonly = true - sources = [ "app/headless_shell.cc", "app/headless_shell_switches.cc",
diff --git a/headless/app/headless_shell.cc b/headless/app/headless_shell.cc index e1348e328e..cc79e1e 100644 --- a/headless/app/headless_shell.cc +++ b/headless/app/headless_shell.cc
@@ -14,6 +14,7 @@ #include "content/public/common/content_switches.h" #include "headless/app/headless_shell_switches.h" #include "headless/public/domains/page.h" +#include "headless/public/domains/runtime.h" #include "headless/public/headless_browser.h" #include "headless/public/headless_devtools_client.h" #include "headless/public/headless_devtools_target.h" @@ -25,6 +26,7 @@ using headless::HeadlessDevToolsClient; using headless::HeadlessWebContents; namespace page = headless::page; +namespace runtime = headless::runtime; namespace { // Address where to listen to incoming DevTools connections. @@ -32,18 +34,12 @@ } // A sample application which demonstrates the use of the headless API. -class HeadlessShell : public HeadlessWebContents::Observer { +class HeadlessShell : public HeadlessWebContents::Observer, page::Observer { public: HeadlessShell() : browser_(nullptr), devtools_client_(HeadlessDevToolsClient::Create()) {} ~HeadlessShell() override {} - void DevToolsTargetReady() override { - if (!RemoteDebuggingEnabled()) - web_contents_->GetDevToolsTarget()->AttachClient(devtools_client_.get()); - // TODO(skyostil): Implement more features to demonstrate the devtools API. - } - void OnStart(HeadlessBrowser* browser) { browser_ = browser; @@ -66,18 +62,43 @@ web_contents_->AddObserver(this); } - void ShutdownIfNeeded() { + void Shutdown() { + if (!web_contents_) + return; if (!RemoteDebuggingEnabled()) { + devtools_client_->GetPage()->RemoveObserver(this); web_contents_->GetDevToolsTarget()->DetachClient(devtools_client_.get()); - web_contents_->RemoveObserver(this); - web_contents_ = nullptr; - browser_->Shutdown(); } + web_contents_->RemoveObserver(this); + web_contents_ = nullptr; + browser_->Shutdown(); } // HeadlessWebContents::Observer implementation: - void DocumentOnLoadCompletedInMainFrame() override { - ShutdownIfNeeded(); + void DevToolsTargetReady() override { + if (RemoteDebuggingEnabled()) + return; + web_contents_->GetDevToolsTarget()->AttachClient(devtools_client_.get()); + devtools_client_->GetPage()->AddObserver(this); + devtools_client_->GetPage()->Enable(); + // Check if the document had already finished loading by the time we + // attached. + devtools_client_->GetRuntime()->Evaluate( + "document.readyState", + base::Bind(&HeadlessShell::OnReadyState, base::Unretained(this))); + // TODO(skyostil): Implement more features to demonstrate the devtools API. + } + + void OnReadyState(std::unique_ptr<runtime::EvaluateResult> result) { + std::string ready_state; + if (result->GetResult()->GetValue()->GetAsString(&ready_state) && + ready_state == "complete") + Shutdown(); + } + + // page::Observer implementation: + void OnLoadEventFired(const page::LoadEventFiredParams& params) override { + Shutdown(); } bool RemoteDebuggingEnabled() const {
diff --git a/headless/lib/browser/headless_devtools_client_impl.cc b/headless/lib/browser/headless_devtools_client_impl.cc index 78f4dade..2f662bb 100644 --- a/headless/lib/browser/headless_devtools_client_impl.cc +++ b/headless/lib/browser/headless_devtools_client_impl.cc
@@ -102,17 +102,18 @@ NOTREACHED() << "Unexpected reply"; return false; } - if (!it->second.callback_with_result.is_null()) { + Callback callback = std::move(it->second); + pending_messages_.erase(it); + if (!callback.callback_with_result.is_null()) { const base::DictionaryValue* result_dict; if (!message_dict.GetDictionary("result", &result_dict)) { NOTREACHED() << "Badly formed reply result"; return false; } - it->second.callback_with_result.Run(*result_dict); - } else if (!it->second.callback.is_null()) { - it->second.callback.Run(); + callback.callback_with_result.Run(*result_dict); + } else if (!callback.callback.is_null()) { + callback.callback.Run(); } - pending_messages_.erase(it); return true; }
diff --git a/headless/lib/browser/headless_web_contents_impl.cc b/headless/lib/browser/headless_web_contents_impl.cc index 723032a..13ed5e1 100644 --- a/headless/lib/browser/headless_web_contents_impl.cc +++ b/headless/lib/browser/headless_web_contents_impl.cc
@@ -39,16 +39,6 @@ observer_->DevToolsTargetReady(); } - void DocumentOnLoadCompletedInMainFrame() override { - observer_->DocumentOnLoadCompletedInMainFrame(); - } - - void DidFinishNavigation( - content::NavigationHandle* navigation_handle) override { - observer_->DidFinishNavigation(navigation_handle->HasCommitted() && - !navigation_handle->IsErrorPage()); - } - private: HeadlessWebContents::Observer* observer_; // Not owned.
diff --git a/headless/lib/headless_browser_browsertest.cc b/headless/lib/headless_browser_browsertest.cc index f2df50b..d6eb82b 100644 --- a/headless/lib/headless_browser_browsertest.cc +++ b/headless/lib/headless_browser_browsertest.cc
@@ -4,6 +4,7 @@ #include <memory> +#include "base/strings/stringprintf.h" #include "content/public/test/browser_test.h" #include "headless/public/headless_browser.h" #include "headless/public/headless_web_contents.h" @@ -81,7 +82,9 @@ IN_PROC_BROWSER_TEST_F(HeadlessBrowserTest, SetHostResolverRules) { EXPECT_TRUE(embedded_test_server()->Start()); HeadlessBrowser::Options::Builder builder; - builder.SetHostResolverRules("MAP not-an-actual-domain.tld 127.0.0.1"); + builder.SetHostResolverRules( + base::StringPrintf("MAP not-an-actual-domain.tld 127.0.0.1:%d", + embedded_test_server()->host_port_pair().port())); SetBrowserOptions(builder.Build()); // Load a page which doesn't actually exist, but which is turned into a valid
diff --git a/headless/lib/headless_web_contents_browsertest.cc b/headless/lib/headless_web_contents_browsertest.cc index 2298b8bc..30faee5 100644 --- a/headless/lib/headless_web_contents_browsertest.cc +++ b/headless/lib/headless_web_contents_browsertest.cc
@@ -16,38 +16,11 @@ class HeadlessWebContentsTest : public HeadlessBrowserTest {}; -class NavigationObserver : public HeadlessWebContents::Observer { - public: - NavigationObserver(HeadlessWebContentsTest* browser_test) - : browser_test_(browser_test), navigation_succeeded_(false) {} - ~NavigationObserver() override {} - - void DocumentOnLoadCompletedInMainFrame() override { - browser_test_->FinishAsynchronousTest(); - } - - void DidFinishNavigation(bool success) override { - navigation_succeeded_ = success; - } - - bool navigation_succeeded() const { return navigation_succeeded_; } - - private: - HeadlessWebContentsTest* browser_test_; // Not owned. - bool navigation_succeeded_; -}; - IN_PROC_BROWSER_TEST_F(HeadlessWebContentsTest, Navigation) { EXPECT_TRUE(embedded_test_server()->Start()); HeadlessWebContents* web_contents = browser()->CreateWebContents( embedded_test_server()->GetURL("/hello.html"), gfx::Size(800, 600)); - NavigationObserver observer(this); - web_contents->AddObserver(&observer); - - RunAsynchronousTest(); - - EXPECT_TRUE(observer.navigation_succeeded()); - web_contents->RemoveObserver(&observer); + EXPECT_TRUE(WaitForLoad(web_contents)); std::vector<HeadlessWebContents*> all_web_contents = browser()->GetAllWebContents(); @@ -61,13 +34,7 @@ HeadlessWebContents* web_contents = browser()->CreateWebContents( embedded_test_server()->GetURL("/window_open.html"), gfx::Size(800, 600)); - NavigationObserver observer(this); - web_contents->AddObserver(&observer); - - RunAsynchronousTest(); - - EXPECT_TRUE(observer.navigation_succeeded()); - web_contents->RemoveObserver(&observer); + EXPECT_TRUE(WaitForLoad(web_contents)); std::vector<HeadlessWebContents*> all_web_contents = browser()->GetAllWebContents();
diff --git a/headless/public/headless_web_contents.h b/headless/public/headless_web_contents.h index 0cdb58bb..02a9c49 100644 --- a/headless/public/headless_web_contents.h +++ b/headless/public/headless_web_contents.h
@@ -20,12 +20,9 @@ public: virtual ~HeadlessWebContents() {} - // TODO(skyostil): Replace this with an equivalent client API. class Observer { public: // All the following notifications will be called on browser main thread. - virtual void DocumentOnLoadCompletedInMainFrame() {} - virtual void DidFinishNavigation(bool success) {} // Indicates that this HeadlessWebContents instance is now ready to be // inspected using a HeadlessDevToolsClient.
diff --git a/headless/test/headless_browser_test.cc b/headless/test/headless_browser_test.cc index 2424231..d81279ce 100644 --- a/headless/test/headless_browser_test.cc +++ b/headless/test/headless_browser_test.cc
@@ -10,30 +10,49 @@ #include "base/run_loop.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" +#include "content/public/common/url_constants.h" #include "headless/lib/browser/headless_browser_impl.h" #include "headless/lib/headless_content_main_delegate.h" +#include "headless/public/domains/network.h" +#include "headless/public/domains/page.h" +#include "headless/public/headless_devtools_client.h" +#include "headless/public/headless_devtools_target.h" #include "headless/public/headless_web_contents.h" namespace headless { namespace { -class WaitForNavigationObserver : public HeadlessWebContents::Observer { +class WaitForLoadObserver : public page::Observer, public network::Observer { public: - WaitForNavigationObserver(HeadlessBrowserTest* browser_test, - HeadlessWebContents* web_contents) + WaitForLoadObserver(HeadlessBrowserTest* browser_test, + HeadlessWebContents* web_contents) : browser_test_(browser_test), web_contents_(web_contents), - navigation_succeeded_(false) { - web_contents_->AddObserver(this); + devtools_client_(HeadlessDevToolsClient::Create()), + navigation_succeeded_(true) { + web_contents_->GetDevToolsTarget()->AttachClient(devtools_client_.get()); + devtools_client_->GetNetwork()->AddObserver(this); + devtools_client_->GetNetwork()->Enable(); + devtools_client_->GetPage()->AddObserver(this); + devtools_client_->GetPage()->Enable(); } - ~WaitForNavigationObserver() override { web_contents_->RemoveObserver(this); } + ~WaitForLoadObserver() override { + devtools_client_->GetNetwork()->RemoveObserver(this); + devtools_client_->GetPage()->RemoveObserver(this); + web_contents_->GetDevToolsTarget()->DetachClient(devtools_client_.get()); + } - void DocumentOnLoadCompletedInMainFrame() override { + void OnLoadEventFired(const page::LoadEventFiredParams& params) override { browser_test_->FinishAsynchronousTest(); } - void DidFinishNavigation(bool success) override { - navigation_succeeded_ = success; + + void OnResponseReceived( + const network::ResponseReceivedParams& params) override { + if (params.GetResponse()->GetStatus() != 200 || + params.GetResponse()->GetUrl() == content::kUnreachableWebDataURL) { + navigation_succeeded_ = false; + } } bool navigation_succeeded() const { return navigation_succeeded_; } @@ -41,10 +60,11 @@ private: HeadlessBrowserTest* browser_test_; // Not owned. HeadlessWebContents* web_contents_; // Not owned. + std::unique_ptr<HeadlessDevToolsClient> devtools_client_; bool navigation_succeeded_; - DISALLOW_COPY_AND_ASSIGN(WaitForNavigationObserver); + DISALLOW_COPY_AND_ASSIGN(WaitForLoadObserver); }; } // namespace @@ -90,7 +110,7 @@ } bool HeadlessBrowserTest::WaitForLoad(HeadlessWebContents* web_contents) { - WaitForNavigationObserver observer(this, web_contents); + WaitForLoadObserver observer(this, web_contents); RunAsynchronousTest(); return observer.navigation_succeeded(); }
diff --git a/ios/web/public/web_state/ui/crw_web_delegate.h b/ios/web/public/web_state/ui/crw_web_delegate.h index 51a1dd3..65c7fbd 100644 --- a/ios/web/public/web_state/ui/crw_web_delegate.h +++ b/ios/web/public/web_state/ui/crw_web_delegate.h
@@ -65,9 +65,6 @@ // |URL| is launched in an external app. - (BOOL)openExternalURL:(const GURL&)URL linkClicked:(BOOL)linkClicked; -// Asked the delegate to present an error to the user because the -// CRWWebController cannot verify the URL of the current page. -- (void)presentSpoofingError; // This method is invoked whenever the system believes the URL is about to // change, or immediately after any unexpected change of the URL, prior to // updating the navigation manager's pending entry.
diff --git a/ios/web/web_state/ui/crw_web_controller.h b/ios/web/web_state/ui/crw_web_controller.h index 1dea724..5c0b7ac 100644 --- a/ios/web/web_state/ui/crw_web_controller.h +++ b/ios/web/web_state/ui/crw_web_controller.h
@@ -312,6 +312,7 @@ - (void)resetInjectedWebViewContentView; // Returns the number of observers registered for this CRWWebController. - (NSUInteger)observerCount; +// Returns the current window id. - (NSString*)windowId; - (void)setWindowId:(NSString*)windowId; - (void)setURLOnStartLoading:(const GURL&)url;
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 571821c7..6bd0fe6a 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -300,7 +300,10 @@ // The CRWWebViewProxy is the wrapper to give components access to the // web view in a controlled and limited way. base::scoped_nsobject<CRWWebViewProxyImpl> _webViewProxy; - // The view used to display content. Must outlive |_webViewProxy|. + // The view used to display content. Must outlive |_webViewProxy|. The + // container view should be accessed through this property rather than + // |self.view| from within this class, as |self.view| triggers creation while + // |self.containerView| will return nil if the view hasn't been instantiated. base::scoped_nsobject<CRWWebControllerContainerView> _containerView; // If |_contentView| contains a native view rather than a web view, this // is its controller. If it's a web view, this is nil. @@ -429,7 +432,7 @@ // Handles downloading PassKit data for WKWebView. Lazy initialized. base::scoped_nsobject<CRWPassKitDownloader> _passKitDownloader; - // Referrer for the current page. + // Referrer for the current page; does not include the fragment. base::scoped_nsobject<NSString> _currentReferrerString; // Pending information for an in-progress page navigation. The lifetime of @@ -467,12 +470,6 @@ std::unique_ptr<CertVerificationErrorsCacheType> _certVerificationErrors; } -// The container view. The container view should be accessed through this -// property rather than |self.view| from within this class, as |self.view| -// triggers creation while |self.containerView| will return nil if the view -// hasn't been instantiated. -@property(nonatomic, retain, readonly) - CRWWebControllerContainerView* containerView; // If |contentView_| contains a web view, this is the web view it contains. // If not, it's nil. @property(nonatomic, readonly) WKWebView* webView; @@ -485,12 +482,8 @@ @property(nonatomic, readwrite) id<CRWNativeContent> nativeController; // Returns NavigationManager's session controller. @property(nonatomic, readonly) CRWSessionController* sessionController; -// The title of the page. -@property(nonatomic, readonly) NSString* title; // Activity indicator group ID for this web controller. @property(nonatomic, readonly) NSString* activityIndicatorGroupID; -// Referrer for the current page; does not include the fragment. -@property(nonatomic, readonly) NSString* currentReferrerString; // Identifier used for storing and retrieving certificates. @property(nonatomic, readonly) int certGroupID; // Dictionary where keys are the names of WKWebView properties and values are @@ -501,10 +494,6 @@ @property(nonatomic, readonly) NSDictionary* WKWebViewObservers; // Downloader for PassKit files. Lazy initialized. @property(nonatomic, readonly) CRWPassKitDownloader* passKitDownloader; -// Returns the current window id. -@property(nonatomic, readonly) NSString* windowId; -// Returns windowID that is saved when a page changes. Used to detect refreshes. -@property(nonatomic, readonly) NSString* lastSeenWindowID; // The web view's view of the current URL. During page transitions // this may not be the same as the session history's view of the current URL. @@ -515,36 +504,17 @@ @property(nonatomic, readonly) GURL currentURL; // Returns the referrer for the current page. @property(nonatomic, readonly) web::Referrer currentReferrer; -// The default URL for a newly created web view. -@property(nonatomic, readonly) const GURL& defaultURL; -// Last URL change reported to webDidStartLoadingURL. Used to detect page -// location changes in practice. -@property(nonatomic, readonly) GURL URLOnStartLoading; -// Last URL change registered for load request. -@property(nonatomic, readonly) GURL lastRegisteredRequestURL; -// Returns YES if the object is being deallocated. -@property(nonatomic, readonly) BOOL isBeingDestroyed; -// Return YES if network activity is being halted. Halting happens prior to -// destruction. -@property(nonatomic, readonly) BOOL isHalted; // Returns YES if the user interacted with the page recently. @property(nonatomic, readonly) BOOL userClickedRecently; // YES if the web process backing _wkWebView is believed to currently be dead. @property(nonatomic, assign) BOOL webProcessIsDead; -// Whether the web page is currently performing window.history.pushState or -// window.history.replaceState -@property(nonatomic, readonly) BOOL changingHistoryState; // Returns whether the desktop user agent should be used when setting the user // agent. @property(nonatomic, readonly) BOOL useDesktopUserAgent; // Removes the container view from the hierarchy and resets the ivar. - (void)resetContainerView; -// Resets pending external request information. -- (void)resetExternalRequest; -// Resets pending navigation info. -- (void)resetPendingNavigationInfo; // Called when the web page has changed document and/or URL, and so the page // navigation should be reported to the delegate, and internal state updated to // reflect the fact that the navigation has occurred. @@ -559,10 +529,6 @@ // been registered for a non-document-changing URL change. Updates internal // state not specific to web pages, and informs the delegate. - (void)didStartLoadingURL:(const GURL&)URL updateHistory:(BOOL)updateHistory; -// Checks if the URL has changed unexpectedly, and handles such changes. -// Returns true if the URL has changed. -// TODO(stuartmorgan): Remove once the hook points are driven from the subclass. -- (BOOL)checkForUnexpectedURLChange; // Returns YES if the URL looks like it is one CRWWebController can show. + (BOOL)webControllerCanShow:(const GURL&)url; // Clears the currently-displayed transient content view. @@ -789,9 +755,6 @@ // Returns the referrer policy for the given referrer policy string (as reported // from JS). - (web::ReferrerPolicy)referrerPolicyFromString:(const std::string&)policy; -// Presents an error to the user because the CRWWebController cannot verify the -// URL of the current page. -- (void)presentSpoofingError; // Adds a new CRWSessionEntry with the given URL and state object to the history // stack. A state object is a serialized generic JavaScript object that contains // details of the UI's state for a given CRWSessionEntry/URL. @@ -1135,11 +1098,11 @@ - (void)clearTransientContentView { // Early return if there is no transient content view. - if (!self.containerView.transientContentView) + if (![_containerView transientContentView]) return; // Remove the transient content view from the hierarchy. - [self.containerView clearTransientContentView]; + [_containerView clearTransientContentView]; // Notify the WebState so it can perform any required state cleanup. if (_webStateImpl) @@ -1152,7 +1115,7 @@ // TODO(crbug.com/556848) Reenable DCHECK when |CRWWebControllerContainerView| // is restructured so that subviews are not added during |layoutSubviews|. // DCHECK([contentView.scrollView isDescendantOfView:contentView]); - [self.containerView displayTransientContent:contentView]; + [_containerView displayTransientContent:contentView]; } - (id<CRWWebDelegate>)delegate { @@ -1208,7 +1171,7 @@ } - (id<CRWNativeContent>)nativeController { - return self.containerView.nativeController; + return [_containerView nativeController]; } - (void)setNativeController:(id<CRWNativeContent>)nativeController { @@ -1220,24 +1183,16 @@ if ([self.nativeController respondsToSelector:@selector(setDelegate:)]) [self.nativeController setDelegate:nil]; - [self.containerView displayNativeContent:nativeController]; + [_containerView displayNativeContent:nativeController]; [self setNativeControllerWebUsageEnabled:_webUsageEnabled]; } -- (NSString*)title { - return [_webView title]; -} - - (NSString*)activityIndicatorGroupID { return [NSString stringWithFormat:@"WebController.NetworkActivityIndicatorKey.%@", self.webStateImpl->GetRequestGroupID()]; } -- (NSString*)currentReferrerString { - return _currentReferrerString; -} - - (int)certGroupID { return self.webState->GetCertGroupId(); } @@ -1297,18 +1252,10 @@ } - (void)resetContainerView { - [self.containerView removeFromSuperview]; + [_containerView removeFromSuperview]; _containerView.reset(); } -- (void)resetExternalRequest { - _externalRequest.reset(); -} - -- (void)resetPendingNavigationInfo { - _pendingNavigationInfo.reset(); -} - - (void)handleLowMemory { [self removeWebViewAllowingCachedReconstruction:YES]; _touchTrackingRecognizer.get().touchTrackingDelegate = nil; @@ -1333,7 +1280,7 @@ } - (BOOL)isViewAlive { - return !_webProcessIsDead && [self.containerView isViewAlive]; + return !_webProcessIsDead && [_containerView isViewAlive]; } - (BOOL)contentIsHTML { @@ -1514,16 +1461,6 @@ } } -- (void)presentSpoofingError { - UMA_HISTOGRAM_ENUMERATION("Web.URLVerificationFailure", - [self webViewDocumentType], - web::WEB_VIEW_DOCUMENT_TYPE_COUNT); - if (self.webView) { - [self removeWebViewAllowingCachedReconstruction:NO]; - [_delegate presentSpoofingError]; - } -} - - (GURL)currentURLWithTrustLevel:(web::URLVerificationTrustLevel*)trustLevel { DCHECK(trustLevel) << "Verification of the trustLevel state is mandatory"; if (self.webView) { @@ -1554,26 +1491,14 @@ - (GURL)currentURL { web::URLVerificationTrustLevel trustLevel = web::URLVerificationTrustLevel::kNone; - const GURL url([self currentURLWithTrustLevel:&trustLevel]); - - // Check whether the spoofing warning needs to be displayed. - if (trustLevel == web::URLVerificationTrustLevel::kNone) { - dispatch_async(dispatch_get_main_queue(), ^{ - if (!_isHalted) { - DCHECK_EQ(url, [self currentNavigationURL]); - [self presentSpoofingError]; - } - }); - } - - return url; + return [self currentURLWithTrustLevel:&trustLevel]; } - (web::Referrer)currentReferrer { // Referrer string doesn't include the fragment, so in cases where the // previous URL is equal to the current referrer plus the fragment the // previous URL is returned as current referrer. - NSString* referrerString = self.currentReferrerString; + NSString* referrerString = _currentReferrerString; // In case of an error evaluating the JavaScript simply return empty string. if ([referrerString length] == 0) @@ -1808,12 +1733,12 @@ _URLOnStartLoading = _defaultURL; // Add the web toolbars. - [self.containerView addToolbars:_webViewToolbars]; + [_containerView addToolbars:_webViewToolbars]; base::scoped_nsobject<CRWWebViewContentView> webViewContentView( [[CRWWebViewContentView alloc] initWithWebView:self.webView scrollView:self.webScrollView]); - [self.containerView displayWebViewContentView:webViewContentView]; + [_containerView displayWebViewContentView:webViewContentView]; } - (CRWWebController*)createChildWebController { @@ -1823,19 +1748,15 @@ } - (BOOL)canUseViewForGeneratingOverlayPlaceholderView { - return self.containerView != nil; + return _containerView != nil; } - (UIView*)view { // Kick off the process of lazily creating the view and starting the load if // necessary; this creates _containerView if it doesn't exist. [self triggerPendingLoad]; - DCHECK(self.containerView); - return self.containerView; -} - -- (CRWWebControllerContainerView*)containerView { - return _containerView.get(); + DCHECK(_containerView); + return _containerView; } - (id<CRWWebViewProxy>)webViewProxy { @@ -2208,17 +2129,12 @@ - (void)loadCurrentURL { // If the content view doesn't exist, the tab has either been evicted, or // never displayed. Bail, and let the URL be loaded when the tab is shown. - if (!self.containerView) + if (!_containerView) return; // Reset current WebUI if one exists. [self clearWebUI]; - // Precaution, so that the outgoing URL is registered, to reduce the risk of - // it being seen as a fresh URL later by the same method (and new page change - // erroneously reported). - [self checkForUnexpectedURLChange]; - // Abort any outstanding page load. This ensures the delegate gets informed // about the outgoing page, and further messages from the page are suppressed. if (_loadPhase != web::PAGE_LOADED) @@ -2262,7 +2178,7 @@ } - (void)triggerPendingLoad { - if (!self.containerView) { + if (!_containerView) { DCHECK(!_isBeingDestroyed); // Create the top-level parent view, which will contain the content (whether // native or web). Note, this needs to be created with a non-zero size @@ -2278,11 +2194,11 @@ [UIApplication sharedApplication].keyWindow.bounds; containerViewFrame.origin.y += statusBarHeight; containerViewFrame.size.height -= statusBarHeight; - self.containerView.frame = containerViewFrame; - DCHECK(!CGRectIsEmpty(self.containerView.frame)); + _containerView.get().frame = containerViewFrame; + DCHECK(!CGRectIsEmpty(_containerView.get().frame)); - [self.containerView addGestureRecognizer:[self touchTrackingRecognizer]]; - [self.containerView setAccessibilityIdentifier:web::kContainerViewID]; + [_containerView addGestureRecognizer:[self touchTrackingRecognizer]]; + [_containerView setAccessibilityIdentifier:web::kContainerViewID]; // Is |currentUrl| a web scheme or native chrome scheme. BOOL isChromeScheme = web::GetWebClient()->IsAppSpecificURL([self currentNavigationURL]); @@ -2409,7 +2325,6 @@ // CRWWebController is 100% up to date before the stack navigation starts. if (self.webView) { [self injectWindowID]; - [self checkForUnexpectedURLChange]; } bool wasShowingInterstitial = _webStateImpl->IsShowingWebInterstitial(); @@ -2596,7 +2511,7 @@ return; [_webViewToolbars addObject:toolbarView]; if (self.webView) - [self.containerView addToolbar:toolbarView]; + [_containerView addToolbar:toolbarView]; } - (void)removeToolbarViewFromWebView:(UIView*)toolbarView { @@ -2604,7 +2519,7 @@ return; [_webViewToolbars removeObject:toolbarView]; if (self.webView) - [self.containerView removeToolbar:toolbarView]; + [_containerView removeToolbar:toolbarView]; } - (CRWJSInjectionReceiver*)jsInjectionReceiver { @@ -2623,18 +2538,6 @@ return rendererInitiatedWithoutInteraction || noNavigationItems; } -- (BOOL)isBeingDestroyed { - return _isBeingDestroyed; -} - -- (BOOL)isHalted { - return _isHalted; -} - -- (BOOL)changingHistoryState { - return _changingHistoryState; -} - - (BOOL)useDesktopUserAgent { web::NavigationItem* item = [self currentNavItem]; return item && item->IsOverridingUserAgent(); @@ -3162,8 +3065,6 @@ - (BOOL)handleWindowHashChangeMessage:(base::DictionaryValue*)message context:(NSDictionary*)context { - [self checkForUnexpectedURLChange]; - // Because hash changes don't trigger |-didFinishNavigation|, fetch favicons // for the new page manually. [self evaluateJavaScript:@"__gCrWeb.sendFaviconsToHost();" @@ -3232,14 +3133,6 @@ // navigation entry does not contain a valid URL. if (!navItem || !navItem->GetURL().is_valid()) return YES; - if (!web::history_state_util::IsHistoryStateChangeValid(navItem->GetURL(), - pushURL)) { - // A redirect may have occurred just prior to the pushState. Check if - // the URL needs to be updated. - // TODO(bdibello): Investigate how the pushState() is handled before the - // redirect and after core.js injection. - [self checkForUnexpectedURLChange]; - } if (!web::history_state_util::IsHistoryStateChangeValid( [self currentNavItem]->GetURL(), pushURL)) { // If the current session entry URL origin still doesn't match pushURL's @@ -3311,12 +3204,6 @@ if (!navItem || (navigationManager.GetItemCount() <= 1 && navItem->GetURL().is_empty())) return YES; - if (!web::history_state_util::IsHistoryStateChangeValid(navItem->GetURL(), - replaceURL)) { - // A redirect may have occurred just prior to the replaceState. Check if - // the URL needs to be updated. - [self checkForUnexpectedURLChange]; - } if (!web::history_state_util::IsHistoryStateChangeValid( [self currentNavItem]->GetURL(), replaceURL)) { // If the current session entry URL origin still doesn't match @@ -3407,11 +3294,6 @@ [_delegate webDidStartLoadingURL:url shouldUpdateHistory:updateHistory]; } -- (BOOL)checkForUnexpectedURLChange { - // Subclasses may override this method to check for and handle URL changes. - return NO; -} - - (void)wasShown { if ([self.nativeController respondsToSelector:@selector(wasShown)]) { [self.nativeController wasShown]; @@ -4043,7 +3925,7 @@ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight]; [_placeholderOverlayView setContentMode:UIViewContentModeScaleAspectFill]; - [self.containerView addSubview:_placeholderOverlayView]; + [_containerView addSubview:_placeholderOverlayView]; id callback = ^(UIImage* image) { [_placeholderOverlayView setImage:image]; @@ -4505,7 +4387,7 @@ #pragma mark Fullscreen - (CGRect)visibleFrame { - CGRect frame = self.containerView.bounds; + CGRect frame = [_containerView bounds]; CGFloat headerHeight = [self headerHeight]; frame.origin.y = headerHeight; frame.size.height -= headerHeight; @@ -4658,7 +4540,7 @@ } - (void)updateSSLStatusForCurrentNavigationItem { - if ([self isBeingDestroyed]) { + if (_isBeingDestroyed) { return; } @@ -4833,7 +4715,7 @@ [_webView addObserver:self forKeyPath:keyPath options:0 context:nullptr]; } [self clearInjectedScriptManagers]; - [self setDocumentURL:[self defaultURL]]; + [self setDocumentURL:_defaultURL]; } - (void)resetWebView { @@ -4855,7 +4737,7 @@ [self abortLoad]; [self.webView removeFromSuperview]; - [self.containerView resetContent]; + [_containerView resetContent]; [self resetWebView]; } @@ -5074,7 +4956,7 @@ decisionHandler: (void (^)(WKNavigationActionPolicy))decisionHandler { _webProcessIsDead = NO; - if (self.isBeingDestroyed) { + if (_isBeingDestroyed) { decisionHandler(WKNavigationActionPolicyCancel); return; } @@ -5159,7 +5041,7 @@ // been registered, do so. loadPhase check is necessary because // lastRegisteredRequestURL may be the same as the webViewURL on a new tab // created by window.open (default is about::blank). - if (self.lastRegisteredRequestURL != webViewURL || + if (_lastRegisteredRequestURL != webViewURL || self.loadPhase != web::LOAD_REQUESTED) { // Reset current WebUI if one exists. [self clearWebUI]; @@ -5182,7 +5064,7 @@ } } // Ensure the URL is registered and loadPhase is as expected. - DCHECK(self.lastRegisteredRequestURL == webViewURL); + DCHECK(_lastRegisteredRequestURL == webViewURL); DCHECK(self.loadPhase == web::LOAD_REQUESTED); _latestWKNavigation.reset([navigation retain]); } @@ -5236,7 +5118,7 @@ // This must be reset at the end, since code above may need information about // the pending load. - [self resetPendingNavigationInfo]; + _pendingNavigationInfo.reset(); _certVerificationErrors->Clear(); } @@ -5252,7 +5134,7 @@ // This is the point where the document's URL has actually changed, and // pending navigation information should be applied to state information. [self setDocumentURL:net::GURLWithNSURL([self.webView URL])]; - DCHECK(_documentURL == self.lastRegisteredRequestURL); + DCHECK(_documentURL == _lastRegisteredRequestURL); self.webStateImpl->OnNavigationCommitted(_documentURL); [self commitPendingNavigationInfo]; if ([self currentBackForwardListItemHolder]->navigation_type() == @@ -5281,7 +5163,7 @@ - (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation { - DCHECK(!self.isHalted); + DCHECK(!_isHalted); // Trigger JavaScript driven post-document-load-completion tasks. // TODO(crbug.com/546350): Investigate using // WKUserScriptInjectionTimeAtDocumentEnd to inject this material at the @@ -5382,7 +5264,7 @@ } - (void)webViewEstimatedProgressDidChange { - if ([self isBeingDestroyed]) + if (_isBeingDestroyed) return; self.webStateImpl->SendChangeLoadProgress([_webView estimatedProgress]); @@ -5421,14 +5303,14 @@ // WKWebView's title becomes empty when the web process dies; ignore that // update. if (self.webProcessIsDead) { - DCHECK_EQ(self.title.length, 0U); + DCHECK_EQ([_webView title].length, 0U); return; } if ([self.delegate respondsToSelector:@selector(webController:titleDidChange:)]) { - DCHECK(self.title); - [self.delegate webController:self titleDidChange:self.title]; + DCHECK([_webView title]); + [self.delegate webController:self titleDidChange:[_webView title]]; } } @@ -5546,7 +5428,7 @@ // registering a load request logically comes before updating the document // URL, but also must come first since it uses state that is reset on URL // changes. - if (!self.changingHistoryState) { + if (!_changingHistoryState) { // If this wasn't a previously-expected load (e.g., certain back/forward // navigations), register the load request. if (![self isLoadRequestPendingForURL:newURL]) @@ -5555,7 +5437,7 @@ [self setDocumentURL:newURL]; - if (!self.changingHistoryState) { + if (!_changingHistoryState) { [self didStartLoadingURL:_documentURL updateHistory:YES]; [self updateSSLStatusForCurrentNavigationItem]; [self didFinishNavigation]; @@ -5661,7 +5543,7 @@ [self removeWebViewAllowingCachedReconstruction:NO]; _lastRegisteredRequestURL = _defaultURL; - [self.containerView displayWebViewContentView:webViewContentView]; + [_containerView displayWebViewContentView:webViewContentView]; [self setWebView:static_cast<WKWebView*>(webViewContentView.webView)]; } @@ -5716,26 +5598,10 @@ return [_windowIDJSManager setWindowId:windowId]; } -- (NSString*)lastSeenWindowID { - return _lastSeenWindowID; -} - - (void)setURLOnStartLoading:(const GURL&)url { _URLOnStartLoading = url; } -- (const GURL&)defaultURL { - return _defaultURL; -} - -- (GURL)URLOnStartLoading { - return _URLOnStartLoading; -} - -- (GURL)lastRegisteredRequestURL { - return _lastRegisteredRequestURL; -} - - (void)simulateLoadRequestWithURL:(const GURL&)URL { _lastRegisteredRequestURL = URL; _loadPhase = web::LOAD_REQUESTED;
diff --git a/ios/web/web_state/ui/crw_web_controller_unittest.mm b/ios/web/web_state/ui/crw_web_controller_unittest.mm index 5036c03..7b28bff 100644 --- a/ios/web/web_state/ui/crw_web_controller_unittest.mm +++ b/ios/web/web_state/ui/crw_web_controller_unittest.mm
@@ -461,8 +461,10 @@ web::kNSErrorPeerCertificateChainKey : chain, }]; - WKWebView* webView = static_cast<WKWebView*>( - [webController_ containerView].webViewContentView.webView); + CRWWebControllerContainerView* containerView = + static_cast<CRWWebControllerContainerView*>([webController_ view]); + WKWebView* webView = + static_cast<WKWebView*>(containerView.webViewContentView.webView); base::scoped_nsobject<NSObject> navigation([[NSObject alloc] init]); [static_cast<id<WKNavigationDelegate>>(webController_.get()) webView:webView @@ -507,8 +509,10 @@ web::kNSErrorPeerCertificateChainKey : chain, web::kNSErrorFailingURLKey : net::NSURLWithGURL(url), }]; - WKWebView* webView = static_cast<WKWebView*>( - [webController_ containerView].webViewContentView.webView); + CRWWebControllerContainerView* containerView = + static_cast<CRWWebControllerContainerView*>([webController_ view]); + WKWebView* webView = + static_cast<WKWebView*>(containerView.webViewContentView.webView); base::scoped_nsobject<NSObject> navigation([[NSObject alloc] init]); [static_cast<id<WKNavigationDelegate>>(webController_.get()) webView:webView
diff --git a/net/BUILD.gn b/net/BUILD.gn index b9f77f8..daa320d 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -102,7 +102,7 @@ ] if (use_glib && use_gconf && !is_chromeos) { - net_configs += [ "//build/config/linux:gconf" ] + net_configs += [ "//build/config/linux/gconf" ] } if (is_linux) { @@ -937,7 +937,7 @@ if (is_desktop_linux && use_gconf && use_glib) { configs += [ - "//build/config/linux:gconf", + "//build/config/linux/gconf", "//build/config/linux:glib", ] deps += [ "//build/linux:gio" ]
diff --git a/net/net.gypi b/net/net.gypi index 688d2b6..80a8878e 100644 --- a/net/net.gypi +++ b/net/net.gypi
@@ -248,23 +248,22 @@ 'quic/congestion_control/tcp_cubic_sender_base.h', 'quic/congestion_control/tcp_cubic_sender_packets.cc', 'quic/congestion_control/tcp_cubic_sender_packets.h', + 'quic/crypto/aead_base_decrypter.cc', 'quic/crypto/aead_base_decrypter.h', - 'quic/crypto/aead_base_decrypter_openssl.cc', + 'quic/crypto/aead_base_encrypter.cc', 'quic/crypto/aead_base_encrypter.h', - 'quic/crypto/aead_base_encrypter_openssl.cc', + 'quic/crypto/aes_128_gcm_12_decrypter.cc', 'quic/crypto/aes_128_gcm_12_decrypter.h', - 'quic/crypto/aes_128_gcm_12_decrypter_openssl.cc', + 'quic/crypto/aes_128_gcm_12_encrypter.cc', 'quic/crypto/aes_128_gcm_12_encrypter.h', - 'quic/crypto/aes_128_gcm_12_encrypter_openssl.cc', + 'quic/crypto/chacha20_poly1305_rfc7539_decrypter.cc', 'quic/crypto/chacha20_poly1305_rfc7539_decrypter.h', - 'quic/crypto/chacha20_poly1305_rfc7539_decrypter_openssl.cc', + 'quic/crypto/chacha20_poly1305_rfc7539_encrypter.cc', 'quic/crypto/chacha20_poly1305_rfc7539_encrypter.h', - 'quic/crypto/chacha20_poly1305_rfc7539_encrypter_openssl.cc', 'quic/crypto/channel_id.cc', 'quic/crypto/channel_id.h', 'quic/crypto/channel_id_chromium.cc', 'quic/crypto/channel_id_chromium.h', - 'quic/crypto/channel_id_openssl.cc', 'quic/crypto/common_cert_set.cc', 'quic/crypto/common_cert_set.h', 'quic/crypto/crypto_framer.cc', @@ -290,8 +289,8 @@ 'quic/crypto/null_decrypter.h', 'quic/crypto/null_encrypter.cc', 'quic/crypto/null_encrypter.h', + 'quic/crypto/p256_key_exchange.cc', 'quic/crypto/p256_key_exchange.h', - 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/proof_source.cc', 'quic/crypto/proof_source.h', 'quic/crypto/proof_verifier.h', @@ -983,8 +982,8 @@ 'quic/bidirectional_stream_quic_impl.h', 'quic/crypto/cert_compressor.cc', 'quic/crypto/cert_compressor.h', + 'quic/crypto/proof_source_chromium.cc', 'quic/crypto/proof_source_chromium.h', - 'quic/crypto/proof_source_chromium_openssl.cc', 'quic/crypto/quic_compressed_certs_cache.cc', 'quic/crypto/quic_compressed_certs_cache.h', 'quic/crypto/quic_crypto_client_config.cc', @@ -1626,7 +1625,6 @@ 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/crypto_test_utils_chromium.cc', - 'quic/test_tools/crypto_test_utils_openssl.cc', 'quic/test_tools/delayed_verify_strike_register_client.cc', 'quic/test_tools/delayed_verify_strike_register_client.h', 'quic/test_tools/mock_clock.cc',
diff --git a/net/quic/crypto/aead_base_decrypter_openssl.cc b/net/quic/crypto/aead_base_decrypter.cc similarity index 100% rename from net/quic/crypto/aead_base_decrypter_openssl.cc rename to net/quic/crypto/aead_base_decrypter.cc
diff --git a/net/quic/crypto/aead_base_encrypter_openssl.cc b/net/quic/crypto/aead_base_encrypter.cc similarity index 100% rename from net/quic/crypto/aead_base_encrypter_openssl.cc rename to net/quic/crypto/aead_base_encrypter.cc
diff --git a/net/quic/crypto/aes_128_gcm_12_decrypter_openssl.cc b/net/quic/crypto/aes_128_gcm_12_decrypter.cc similarity index 100% rename from net/quic/crypto/aes_128_gcm_12_decrypter_openssl.cc rename to net/quic/crypto/aes_128_gcm_12_decrypter.cc
diff --git a/net/quic/crypto/aes_128_gcm_12_encrypter_openssl.cc b/net/quic/crypto/aes_128_gcm_12_encrypter.cc similarity index 100% rename from net/quic/crypto/aes_128_gcm_12_encrypter_openssl.cc rename to net/quic/crypto/aes_128_gcm_12_encrypter.cc
diff --git a/net/quic/crypto/chacha20_poly1305_rfc7539_decrypter_openssl.cc b/net/quic/crypto/chacha20_poly1305_rfc7539_decrypter.cc similarity index 100% rename from net/quic/crypto/chacha20_poly1305_rfc7539_decrypter_openssl.cc rename to net/quic/crypto/chacha20_poly1305_rfc7539_decrypter.cc
diff --git a/net/quic/crypto/chacha20_poly1305_rfc7539_encrypter_openssl.cc b/net/quic/crypto/chacha20_poly1305_rfc7539_encrypter.cc similarity index 100% rename from net/quic/crypto/chacha20_poly1305_rfc7539_encrypter_openssl.cc rename to net/quic/crypto/chacha20_poly1305_rfc7539_encrypter.cc
diff --git a/net/quic/crypto/channel_id.cc b/net/quic/crypto/channel_id.cc index e707bf0..3d93be0 100644 --- a/net/quic/crypto/channel_id.cc +++ b/net/quic/crypto/channel_id.cc
@@ -4,6 +4,17 @@ #include "net/quic/crypto/channel_id.h" +#include <openssl/bn.h> +#include <openssl/ec.h> +#include <openssl/ecdsa.h> +#include <openssl/obj_mac.h> +#include <openssl/sha.h> + +#include "crypto/openssl_util.h" +#include "crypto/scoped_openssl_types.h" + +using base::StringPiece; + namespace net { // static @@ -11,4 +22,70 @@ // static const char ChannelIDVerifier::kClientToServerStr[] = "client -> server"; +// static +bool ChannelIDVerifier::Verify(StringPiece key, + StringPiece signed_data, + StringPiece signature) { + return VerifyRaw(key, signed_data, signature, true); +} + +// static +bool ChannelIDVerifier::VerifyRaw(StringPiece key, + StringPiece signed_data, + StringPiece signature, + bool is_channel_id_signature) { + if (key.size() != 32 * 2 || signature.size() != 32 * 2) { + return false; + } + + crypto::ScopedEC_GROUP p256(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1)); + if (!p256) { + return false; + } + + crypto::ScopedBIGNUM x(BN_new()), y(BN_new()), r(BN_new()), s(BN_new()); + + ECDSA_SIG sig; + sig.r = r.get(); + sig.s = s.get(); + + const uint8_t* key_bytes = reinterpret_cast<const uint8_t*>(key.data()); + const uint8_t* signature_bytes = + reinterpret_cast<const uint8_t*>(signature.data()); + + if (BN_bin2bn(key_bytes + 0, 32, x.get()) == nullptr || + BN_bin2bn(key_bytes + 32, 32, y.get()) == nullptr || + BN_bin2bn(signature_bytes + 0, 32, sig.r) == nullptr || + BN_bin2bn(signature_bytes + 32, 32, sig.s) == nullptr) { + return false; + } + + crypto::ScopedEC_POINT point(EC_POINT_new(p256.get())); + if (!point || + !EC_POINT_set_affine_coordinates_GFp(p256.get(), point.get(), x.get(), + y.get(), nullptr)) { + return false; + } + + crypto::ScopedEC_KEY ecdsa_key(EC_KEY_new()); + if (ecdsa_key.get() == nullptr || + !EC_KEY_set_group(ecdsa_key.get(), p256.get()) || + !EC_KEY_set_public_key(ecdsa_key.get(), point.get())) { + return false; + } + + SHA256_CTX sha256; + SHA256_Init(&sha256); + if (is_channel_id_signature) { + SHA256_Update(&sha256, kContextStr, strlen(kContextStr) + 1); + SHA256_Update(&sha256, kClientToServerStr, strlen(kClientToServerStr) + 1); + } + SHA256_Update(&sha256, signed_data.data(), signed_data.size()); + + unsigned char digest[SHA256_DIGEST_LENGTH]; + SHA256_Final(digest, &sha256); + + return ECDSA_do_verify(digest, sizeof(digest), &sig, ecdsa_key.get()) == 1; +} + } // namespace net
diff --git a/net/quic/crypto/channel_id_openssl.cc b/net/quic/crypto/channel_id_openssl.cc deleted file mode 100644 index 4e576ae..0000000 --- a/net/quic/crypto/channel_id_openssl.cc +++ /dev/null
@@ -1,86 +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 "net/quic/crypto/channel_id.h" - -#include <openssl/bn.h> -#include <openssl/ec.h> -#include <openssl/ecdsa.h> -#include <openssl/obj_mac.h> -#include <openssl/sha.h> - -#include "crypto/openssl_util.h" -#include "crypto/scoped_openssl_types.h" - -using base::StringPiece; - -namespace net { - -// static -bool ChannelIDVerifier::Verify(StringPiece key, - StringPiece signed_data, - StringPiece signature) { - return VerifyRaw(key, signed_data, signature, true); -} - -// static -bool ChannelIDVerifier::VerifyRaw(StringPiece key, - StringPiece signed_data, - StringPiece signature, - bool is_channel_id_signature) { - if (key.size() != 32 * 2 || signature.size() != 32 * 2) { - return false; - } - - crypto::ScopedEC_GROUP p256(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1)); - if (!p256) { - return false; - } - - crypto::ScopedBIGNUM x(BN_new()), y(BN_new()), r(BN_new()), s(BN_new()); - - ECDSA_SIG sig; - sig.r = r.get(); - sig.s = s.get(); - - const uint8_t* key_bytes = reinterpret_cast<const uint8_t*>(key.data()); - const uint8_t* signature_bytes = - reinterpret_cast<const uint8_t*>(signature.data()); - - if (BN_bin2bn(key_bytes + 0, 32, x.get()) == nullptr || - BN_bin2bn(key_bytes + 32, 32, y.get()) == nullptr || - BN_bin2bn(signature_bytes + 0, 32, sig.r) == nullptr || - BN_bin2bn(signature_bytes + 32, 32, sig.s) == nullptr) { - return false; - } - - crypto::ScopedEC_POINT point(EC_POINT_new(p256.get())); - if (!point || - !EC_POINT_set_affine_coordinates_GFp(p256.get(), point.get(), x.get(), - y.get(), nullptr)) { - return false; - } - - crypto::ScopedEC_KEY ecdsa_key(EC_KEY_new()); - if (ecdsa_key.get() == nullptr || - !EC_KEY_set_group(ecdsa_key.get(), p256.get()) || - !EC_KEY_set_public_key(ecdsa_key.get(), point.get())) { - return false; - } - - SHA256_CTX sha256; - SHA256_Init(&sha256); - if (is_channel_id_signature) { - SHA256_Update(&sha256, kContextStr, strlen(kContextStr) + 1); - SHA256_Update(&sha256, kClientToServerStr, strlen(kClientToServerStr) + 1); - } - SHA256_Update(&sha256, signed_data.data(), signed_data.size()); - - unsigned char digest[SHA256_DIGEST_LENGTH]; - SHA256_Final(digest, &sha256); - - return ECDSA_do_verify(digest, sizeof(digest), &sig, ecdsa_key.get()) == 1; -} - -} // namespace net
diff --git a/net/quic/crypto/p256_key_exchange_openssl.cc b/net/quic/crypto/p256_key_exchange.cc similarity index 100% rename from net/quic/crypto/p256_key_exchange_openssl.cc rename to net/quic/crypto/p256_key_exchange.cc
diff --git a/net/quic/crypto/proof_source_chromium_openssl.cc b/net/quic/crypto/proof_source_chromium.cc similarity index 100% rename from net/quic/crypto/proof_source_chromium_openssl.cc rename to net/quic/crypto/proof_source_chromium.cc
diff --git a/net/quic/test_tools/crypto_test_utils.cc b/net/quic/test_tools/crypto_test_utils.cc index 38d7b2c4..e0dceda 100644 --- a/net/quic/test_tools/crypto_test_utils.cc +++ b/net/quic/test_tools/crypto_test_utils.cc
@@ -4,9 +4,19 @@ #include "net/quic/test_tools/crypto_test_utils.h" +#include <openssl/bn.h> +#include <openssl/ec.h> +#include <openssl/ecdsa.h> +#include <openssl/evp.h> +#include <openssl/obj_mac.h> +#include <openssl/sha.h> + #include <memory> #include "base/strings/string_util.h" +#include "crypto/openssl_util.h" +#include "crypto/scoped_openssl_types.h" +#include "crypto/secure_hash.h" #include "net/quic/crypto/channel_id.h" #include "net/quic/crypto/common_cert_set.h" #include "net/quic/crypto/crypto_handshake.h" @@ -117,6 +127,138 @@ std::unique_ptr<ChannelIDKey> channel_id_key_; }; +class TestChannelIDKey : public ChannelIDKey { + public: + explicit TestChannelIDKey(EVP_PKEY* ecdsa_key) : ecdsa_key_(ecdsa_key) {} + ~TestChannelIDKey() override {} + + // ChannelIDKey implementation. + + bool Sign(StringPiece signed_data, string* out_signature) const override { + crypto::ScopedEVP_MD_CTX md_ctx(EVP_MD_CTX_create()); + if (!md_ctx || + EVP_DigestSignInit(md_ctx.get(), nullptr, EVP_sha256(), nullptr, + ecdsa_key_.get()) != 1) { + return false; + } + + EVP_DigestUpdate(md_ctx.get(), ChannelIDVerifier::kContextStr, + strlen(ChannelIDVerifier::kContextStr) + 1); + EVP_DigestUpdate(md_ctx.get(), ChannelIDVerifier::kClientToServerStr, + strlen(ChannelIDVerifier::kClientToServerStr) + 1); + EVP_DigestUpdate(md_ctx.get(), signed_data.data(), signed_data.size()); + + size_t sig_len; + if (!EVP_DigestSignFinal(md_ctx.get(), nullptr, &sig_len)) { + return false; + } + + std::unique_ptr<uint8_t[]> der_sig(new uint8_t[sig_len]); + if (!EVP_DigestSignFinal(md_ctx.get(), der_sig.get(), &sig_len)) { + return false; + } + + uint8_t* derp = der_sig.get(); + crypto::ScopedECDSA_SIG sig( + d2i_ECDSA_SIG(nullptr, const_cast<const uint8_t**>(&derp), sig_len)); + if (sig.get() == nullptr) { + return false; + } + + // The signature consists of a pair of 32-byte numbers. + static const size_t kSignatureLength = 32 * 2; + std::unique_ptr<uint8_t[]> signature(new uint8_t[kSignatureLength]); + if (!BN_bn2bin_padded(&signature[0], 32, sig->r) || + !BN_bn2bin_padded(&signature[32], 32, sig->s)) { + return false; + } + + *out_signature = + string(reinterpret_cast<char*>(signature.get()), kSignatureLength); + + return true; + } + + string SerializeKey() const override { + // i2d_PublicKey will produce an ANSI X9.62 public key which, for a P-256 + // key, is 0x04 (meaning uncompressed) followed by the x and y field + // elements as 32-byte, big-endian numbers. + static const int kExpectedKeyLength = 65; + + int len = i2d_PublicKey(ecdsa_key_.get(), nullptr); + if (len != kExpectedKeyLength) { + return ""; + } + + uint8_t buf[kExpectedKeyLength]; + uint8_t* derp = buf; + i2d_PublicKey(ecdsa_key_.get(), &derp); + + return string(reinterpret_cast<char*>(buf + 1), kExpectedKeyLength - 1); + } + + private: + crypto::ScopedEVP_PKEY ecdsa_key_; +}; + +class TestChannelIDSource : public ChannelIDSource { + public: + ~TestChannelIDSource() override {} + + // ChannelIDSource implementation. + + QuicAsyncStatus GetChannelIDKey( + const string& hostname, + std::unique_ptr<ChannelIDKey>* channel_id_key, + ChannelIDSourceCallback* /*callback*/) override { + channel_id_key->reset(new TestChannelIDKey(HostnameToKey(hostname))); + return QUIC_SUCCESS; + } + + private: + static EVP_PKEY* HostnameToKey(const string& hostname) { + // In order to generate a deterministic key for a given hostname the + // hostname is hashed with SHA-256 and the resulting digest is treated as a + // big-endian number. The most-significant bit is cleared to ensure that + // the resulting value is less than the order of the group and then it's + // taken as a private key. Given the private key, the public key is + // calculated with a group multiplication. + SHA256_CTX sha256; + SHA256_Init(&sha256); + SHA256_Update(&sha256, hostname.data(), hostname.size()); + + unsigned char digest[SHA256_DIGEST_LENGTH]; + SHA256_Final(digest, &sha256); + + // Ensure that the digest is less than the order of the P-256 group by + // clearing the most-significant bit. + digest[0] &= 0x7f; + + crypto::ScopedBIGNUM k(BN_new()); + CHECK(BN_bin2bn(digest, sizeof(digest), k.get()) != nullptr); + + crypto::ScopedEC_GROUP p256( + EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1)); + CHECK(p256); + + crypto::ScopedEC_KEY ecdsa_key(EC_KEY_new()); + CHECK(ecdsa_key && EC_KEY_set_group(ecdsa_key.get(), p256.get())); + + crypto::ScopedEC_POINT point(EC_POINT_new(p256.get())); + CHECK(EC_POINT_mul(p256.get(), point.get(), k.get(), nullptr, nullptr, + nullptr)); + + EC_KEY_set_private_key(ecdsa_key.get(), k.get()); + EC_KEY_set_public_key(ecdsa_key.get(), point.get()); + + crypto::ScopedEVP_PKEY pkey(EVP_PKEY_new()); + // EVP_PKEY_set1_EC_KEY takes a reference so no |release| here. + EVP_PKEY_set1_EC_KEY(pkey.get(), ecdsa_key.get()); + + return pkey.release(); + } +}; + } // anonymous namespace CryptoTestUtils::FakeServerOptions::FakeServerOptions() @@ -610,6 +752,11 @@ } // static +ChannelIDSource* CryptoTestUtils::ChannelIDSourceForTesting() { + return new TestChannelIDSource(); +} + +// static void CryptoTestUtils::MovePackets(PacketSavingConnection* source_conn, size_t* inout_packet_index, QuicCryptoStream* dest_stream,
diff --git a/net/quic/test_tools/crypto_test_utils_openssl.cc b/net/quic/test_tools/crypto_test_utils_openssl.cc deleted file mode 100644 index 1a995de..0000000 --- a/net/quic/test_tools/crypto_test_utils_openssl.cc +++ /dev/null
@@ -1,167 +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 "net/quic/test_tools/crypto_test_utils.h" - -#include <openssl/bn.h> -#include <openssl/ec.h> -#include <openssl/ecdsa.h> -#include <openssl/evp.h> -#include <openssl/obj_mac.h> -#include <openssl/sha.h> - -#include <memory> - -#include "crypto/openssl_util.h" -#include "crypto/scoped_openssl_types.h" -#include "crypto/secure_hash.h" -#include "net/quic/crypto/channel_id.h" - -using base::StringPiece; -using std::string; - -namespace net { - -namespace test { - -class TestChannelIDKey : public ChannelIDKey { - public: - explicit TestChannelIDKey(EVP_PKEY* ecdsa_key) : ecdsa_key_(ecdsa_key) {} - ~TestChannelIDKey() override {} - - // ChannelIDKey implementation. - - bool Sign(StringPiece signed_data, string* out_signature) const override { - crypto::ScopedEVP_MD_CTX md_ctx(EVP_MD_CTX_create()); - if (!md_ctx || - EVP_DigestSignInit(md_ctx.get(), nullptr, EVP_sha256(), nullptr, - ecdsa_key_.get()) != 1) { - return false; - } - - EVP_DigestUpdate(md_ctx.get(), ChannelIDVerifier::kContextStr, - strlen(ChannelIDVerifier::kContextStr) + 1); - EVP_DigestUpdate(md_ctx.get(), ChannelIDVerifier::kClientToServerStr, - strlen(ChannelIDVerifier::kClientToServerStr) + 1); - EVP_DigestUpdate(md_ctx.get(), signed_data.data(), signed_data.size()); - - size_t sig_len; - if (!EVP_DigestSignFinal(md_ctx.get(), nullptr, &sig_len)) { - return false; - } - - std::unique_ptr<uint8_t[]> der_sig(new uint8_t[sig_len]); - if (!EVP_DigestSignFinal(md_ctx.get(), der_sig.get(), &sig_len)) { - return false; - } - - uint8_t* derp = der_sig.get(); - crypto::ScopedECDSA_SIG sig( - d2i_ECDSA_SIG(nullptr, const_cast<const uint8_t**>(&derp), sig_len)); - if (sig.get() == nullptr) { - return false; - } - - // The signature consists of a pair of 32-byte numbers. - static const size_t kSignatureLength = 32 * 2; - std::unique_ptr<uint8_t[]> signature(new uint8_t[kSignatureLength]); - if (!BN_bn2bin_padded(&signature[0], 32, sig->r) || - !BN_bn2bin_padded(&signature[32], 32, sig->s)) { - return false; - } - - *out_signature = - string(reinterpret_cast<char*>(signature.get()), kSignatureLength); - - return true; - } - - string SerializeKey() const override { - // i2d_PublicKey will produce an ANSI X9.62 public key which, for a P-256 - // key, is 0x04 (meaning uncompressed) followed by the x and y field - // elements as 32-byte, big-endian numbers. - static const int kExpectedKeyLength = 65; - - int len = i2d_PublicKey(ecdsa_key_.get(), nullptr); - if (len != kExpectedKeyLength) { - return ""; - } - - uint8_t buf[kExpectedKeyLength]; - uint8_t* derp = buf; - i2d_PublicKey(ecdsa_key_.get(), &derp); - - return string(reinterpret_cast<char*>(buf + 1), kExpectedKeyLength - 1); - } - - private: - crypto::ScopedEVP_PKEY ecdsa_key_; -}; - -class TestChannelIDSource : public ChannelIDSource { - public: - ~TestChannelIDSource() override {} - - // ChannelIDSource implementation. - - QuicAsyncStatus GetChannelIDKey( - const string& hostname, - std::unique_ptr<ChannelIDKey>* channel_id_key, - ChannelIDSourceCallback* /*callback*/) override { - channel_id_key->reset(new TestChannelIDKey(HostnameToKey(hostname))); - return QUIC_SUCCESS; - } - - private: - static EVP_PKEY* HostnameToKey(const string& hostname) { - // In order to generate a deterministic key for a given hostname the - // hostname is hashed with SHA-256 and the resulting digest is treated as a - // big-endian number. The most-significant bit is cleared to ensure that - // the resulting value is less than the order of the group and then it's - // taken as a private key. Given the private key, the public key is - // calculated with a group multiplication. - SHA256_CTX sha256; - SHA256_Init(&sha256); - SHA256_Update(&sha256, hostname.data(), hostname.size()); - - unsigned char digest[SHA256_DIGEST_LENGTH]; - SHA256_Final(digest, &sha256); - - // Ensure that the digest is less than the order of the P-256 group by - // clearing the most-significant bit. - digest[0] &= 0x7f; - - crypto::ScopedBIGNUM k(BN_new()); - CHECK(BN_bin2bn(digest, sizeof(digest), k.get()) != nullptr); - - crypto::ScopedEC_GROUP p256( - EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1)); - CHECK(p256); - - crypto::ScopedEC_KEY ecdsa_key(EC_KEY_new()); - CHECK(ecdsa_key && EC_KEY_set_group(ecdsa_key.get(), p256.get())); - - crypto::ScopedEC_POINT point(EC_POINT_new(p256.get())); - CHECK(EC_POINT_mul(p256.get(), point.get(), k.get(), nullptr, nullptr, - nullptr)); - - EC_KEY_set_private_key(ecdsa_key.get(), k.get()); - EC_KEY_set_public_key(ecdsa_key.get(), point.get()); - - crypto::ScopedEVP_PKEY pkey(EVP_PKEY_new()); - // EVP_PKEY_set1_EC_KEY takes a reference so no |release| here. - EVP_PKEY_set1_EC_KEY(pkey.get(), ecdsa_key.get()); - - return pkey.release(); - } -}; - -// static -ChannelIDSource* CryptoTestUtils::ChannelIDSourceForTesting() { - return new TestChannelIDSource(); -} - -} // namespace test - -} // namespace net
diff --git a/skia/BUILD.gn b/skia/BUILD.gn index 3565eab..a5872a7 100644 --- a/skia/BUILD.gn +++ b/skia/BUILD.gn
@@ -19,8 +19,7 @@ gypi_chromium_skia_defines = exec_script("//build/gypi_to_gn.py", [ - rebase_path( - "//skia/chromium_skia_defines.gypi"), + rebase_path("//skia/chromium_skia_defines.gypi"), "--replace=<(skia_include_path)=//third_party/skia/include", "--replace=<(skia_src_path)=//third_party/skia/src", ], @@ -466,7 +465,7 @@ if (is_linux) { if (use_pango) { - configs += [ "//build/config/linux:pangocairo" ] + configs += [ "//build/config/linux/pangocairo" ] } deps += [ "//build/linux:fontconfig",
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index a21201e7..f0da75c 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -69,18 +69,6 @@ } ] }, - "test": "breakpad_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "KTU84P", - "device_type": "hammerhead" - } - ] - }, "test": "cc_unittests" }, { @@ -302,6 +290,10 @@ ], "instrumentation_tests": [ { + "apk_under_test": "Blimp.apk", + "override_compile_targets": [ + "blimp_test_apk" + ], "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ @@ -311,7 +303,8 @@ } ] }, - "test": "blimp_test_apk" + "test": "blimp_test_apk", + "test_apk": "BlimpTest.apk" }, { "swarming": {
diff --git a/testing/buildbot/filters/browser-side-navigation.linux.content_browsertests.filter b/testing/buildbot/filters/browser-side-navigation.linux.content_browsertests.filter index 21c1dd89..29ef9c8b3 100644 --- a/testing/buildbot/filters/browser-side-navigation.linux.content_browsertests.filter +++ b/testing/buildbot/filters/browser-side-navigation.linux.content_browsertests.filter
@@ -1,6 +1,4 @@ --NavigationControllerBrowserTest.FrameNavigationEntry_SubframeHistoryFallback -RenderFrameHostManagerTest.RestoreSubframeFileAccessForHistoryNavigation --RenderFrameHostManagerTest.SameOriginFramesInDifferentProcesses -RenderViewImplTest.GetCompositionCharacterBoundsTest -RenderViewImplTest.OnNavigationHttpPost -ServiceWorkerBrowserTest.FetchPageWithSaveData
diff --git a/testing/generate_isolate.py b/testing/generate_isolate.py new file mode 100755 index 0000000..1944e735 --- /dev/null +++ b/testing/generate_isolate.py
@@ -0,0 +1,114 @@ +#!/usr/bin/env python +# 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. + +"""Creates an .isolate given a list of files. + +""" + +import argparse +import os +import pprint +import re +import sys + + +_UNIVERSAL_BLACKLIST = ( + r'.*OWNERS', # Should never be included. +) + +_ANDROID_BLACKLIST = ( + r'.*\.so', # Libraries packed into .apk. + r'.*\.mojom.js', # Some test_support targets include python deps. + r'.*Mojo.*manifest\.json', # Some source_set()s pull these in. + r'.*jni_generator_tests', # Exists just to test the compile, not to be run. +) + +_DEVICE_BLACKLIST = ( + r'.*\.py', # Some test_support targets include python deps. +) + +_ASSERT_WHITELIST = ( + r'.*\.pak', + r'.*/', # Assume directories are always included on purpose. +) + + +def _IsExecutable(path): + return os.path.isfile(path) and os.access(path, os.X_OK) + + +def _MatchesAny(path, patterns): + return any(re.match(p, path) for p in patterns) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--command', + help='The command to put in the .isolate (optional)') + parser.add_argument('--runtime-deps-file', required=True, + help='Input .runtime_deps file.') + parser.add_argument('--output-directory', required=True, + help='Location of the ninja output directory') + parser.add_argument('--out-file', help='Write to file rather than stdout.') + parser.add_argument('--apply-android-filters', action='store_true', + help='Filter files not required for Android.') + parser.add_argument('--apply-device-filters', action='store_true', + help='Filter files not required in *.device.isolate.') + parser.add_argument('--assert-no-odd-data', action='store_true', + help='Fail if any data deps exist (after filtering) ' + 'that are not a part of the _ASSERT_WHITELIST. Use ' + 'this to prevent unexpected runtime_deps from ' + 'creeping in') + options = parser.parse_args() + + deps = [] + with open(options.runtime_deps_file) as deps_file: + for path in deps_file: + if path.startswith('./'): + path = path[2:] + deps.append(path.rstrip()) + + deps = (d for d in deps if not _MatchesAny(d, _UNIVERSAL_BLACKLIST)) + + if options.apply_android_filters: + deps = (d for d in deps if not _MatchesAny(d, _ANDROID_BLACKLIST)) + + if options.apply_device_filters: + deps = (d for d in deps if not _MatchesAny(d, _DEVICE_BLACKLIST)) + # Breakpad tests have a helper exe, which is packaged in the _dist. + deps = (d for d in deps if not _IsExecutable(d)) + + # Make them relative to out-file. + if options.out_file: + subdir = os.path.relpath(options.output_directory, + os.path.dirname(options.out_file)) + deps = (os.path.join(subdir, d) for d in deps) + + deps = sorted(deps) + + if options.assert_no_odd_data: + odd_files = [d for d in deps if not _MatchesAny(d, _ASSERT_WHITELIST)] + assert not odd_files, ('Found possibly undesired file in runtime_deps: %s' % + odd_files) + + isolate_dict = { + 'variables': { + 'files': deps, + } + } + if options.command: + isolate_dict['variables']['command'] = [options.command] + + isolate_data = pprint.pformat(isolate_dict) + if options.out_file: + with open(options.out_file, 'w') as f: + f.write(isolate_data + '\n') + else: + print isolate_data + + +if __name__ == '__main__': + sys.exit(main()) +
diff --git a/testing/test.gni b/testing/test.gni index 8434fc5..a575894 100644 --- a/testing/test.gni +++ b/testing/test.gni
@@ -6,6 +6,56 @@ # TEST SETUP # ============================================================================== +template("_gen_isolate") { + testonly = true + _runtime_deps_file = "$target_gen_dir/$target_name.runtime_deps" + group("${target_name}__write_deps") { + forward_variables_from(invoker, + [ + "data", + "data_deps", + "deps", + "public_deps", + ]) + write_runtime_deps = _runtime_deps_file + } + + action(target_name) { + script = "//testing/generate_isolate.py" + outputs = [ + invoker.output, + ] + args = [ + "--output-directory=.", + "--out-file", + rebase_path(invoker.output, root_build_dir), + "--runtime-deps-file", + rebase_path(_runtime_deps_file, root_build_dir), + ] + if (is_android) { + args += [ "--apply-android-filters" ] + } + if (defined(invoker.apply_device_filters) && invoker.apply_device_filters) { + args += [ "--apply-device-filters" ] + } + _assert_no_odd_data = + defined(invoker.assert_no_odd_data) && invoker.assert_no_odd_data + if (_assert_no_odd_data) { + args += [ "--assert-no-odd-data" ] + } + if (defined(invoker.command)) { + _isolate_dir = get_path_info(invoker.output, "dir") + args += [ + "--command", + rebase_path(invoker.command, _isolate_dir), + ] + } + deps = [ + ":${invoker.target_name}__write_deps", + ] + } +} + # Define a test as an executable (or apk on Android) with the "testonly" flag # set. # Variable: @@ -30,6 +80,40 @@ "isolate_file", "shard_timeout", ] + _gen_isolate_vars = [ + "allow_odd_runtime_deps", + "ignore_all_data_deps", + ] + + # TODO(agrieve): Delete all manually passed-in .isolate files now that they + # are unused. http://crbug.com/589318 + assert(!defined(invoker.isolate_file) || invoker.isolate_file != "") # Mark used. + _generate_device_isolate = + !defined(invoker.ignore_all_data_deps) || !invoker.ignore_all_data_deps + + if (_generate_device_isolate) { + _allow_odd_runtime_deps = defined(invoker.allow_odd_runtime_deps) && + invoker.allow_odd_runtime_deps + + # The device isolate is needed at runtime, so it cannot go in + # target_gen_dir, as builder/tester configurations do not include it. + _target_dir_name = get_label_info(":$target_name", "dir") + _device_isolate_path = "$root_out_dir/gen.runtime/$_target_dir_name/$target_name.device.isolate" + _gen_isolate_target_name = "${target_name}__isolate" + _gen_isolate(_gen_isolate_target_name) { + data_deps = [] + forward_variables_from(invoker, + [ + "data", + "data_deps", + "deps", + "public_deps", + ]) + assert_no_odd_data = !_allow_odd_runtime_deps + output = _device_isolate_path + apply_device_filters = true + } + } if (_use_raw_android_executable) { _exec_target = "${target_name}__exec" @@ -41,7 +125,10 @@ # Configs will always be defined since we set_defaults in BUILDCONFIG.gn. configs = [] data_deps = [] - forward_variables_from(invoker, "*", [ "extra_dist_files" ]) + forward_variables_from( + invoker, + "*", + _wrapper_script_vars + _gen_isolate_vars + [ "extra_dist_files" ]) testonly = true # Thanks to the set_defaults() for test(), configs are initialized with @@ -86,10 +173,10 @@ testonly = true deps = [] - forward_variables_from( - invoker, - "*", - _apk_specific_vars + _wrapper_script_vars + [ "visibility" ]) + forward_variables_from(invoker, + "*", + _apk_specific_vars + _wrapper_script_vars + + _gen_isolate_vars + [ "visibility" ]) if (!defined(invoker.use_default_launcher) || invoker.use_default_launcher) { @@ -123,6 +210,12 @@ "${_output_name}_incremental__test_runner_script" test_runner_script(_incremental_test_runner_target) { forward_variables_from(invoker, _wrapper_script_vars) + if (_generate_device_isolate) { + isolate_file = _device_isolate_path + deps = [ + ":$_gen_isolate_target_name", + ] + } apk_target = ":$_apk_target" test_name = "${_output_name}_incremental" test_type = "gtest" @@ -143,6 +236,13 @@ _test_runner_target = "${_output_name}__test_runner_script" test_runner_script(_test_runner_target) { forward_variables_from(invoker, _wrapper_script_vars) + if (_generate_device_isolate) { + isolate_file = _device_isolate_path + deps = [ + ":$_gen_isolate_target_name", + ] + } + if (_use_raw_android_executable) { executable_dist_dir = "$root_out_dir/$_dist_target" } else {
diff --git a/testing/variations/fieldtrial_testing_config_android.json b/testing/variations/fieldtrial_testing_config_android.json index e7042721..edac13f 100644 --- a/testing/variations/fieldtrial_testing_config_android.json +++ b/testing/variations/fieldtrial_testing_config_android.json
@@ -160,6 +160,11 @@ "group_name": "Enabled" } ], + "MojoChannel": [ + { + "group_name": "Enabled" + } + ], "NTPPopularSites": [ { "group_name": "Enabled5",
diff --git a/testing/variations/fieldtrial_testing_config_chromeos.json b/testing/variations/fieldtrial_testing_config_chromeos.json index d7e33bac..b61c796 100644 --- a/testing/variations/fieldtrial_testing_config_chromeos.json +++ b/testing/variations/fieldtrial_testing_config_chromeos.json
@@ -68,6 +68,11 @@ "group_name": "Enabled" } ], + "MojoChannel": [ + { + "group_name": "Enabled" + } + ], "OfferUploadCreditCards": [ { "group_name": "Enabled"
diff --git a/testing/variations/fieldtrial_testing_config_linux.json b/testing/variations/fieldtrial_testing_config_linux.json index 42c899a..cc6e93a 100644 --- a/testing/variations/fieldtrial_testing_config_linux.json +++ b/testing/variations/fieldtrial_testing_config_linux.json
@@ -91,6 +91,11 @@ "group_name": "Enabled" } ], + "MojoChannel": [ + { + "group_name": "Enabled" + } + ], "OfferUploadCreditCards": [ { "group_name": "Enabled"
diff --git a/testing/variations/fieldtrial_testing_config_mac.json b/testing/variations/fieldtrial_testing_config_mac.json index acc07ea..fbbe3fc7 100644 --- a/testing/variations/fieldtrial_testing_config_mac.json +++ b/testing/variations/fieldtrial_testing_config_mac.json
@@ -112,6 +112,11 @@ "group_name": "Enabled" } ], + "MojoChannel": [ + { + "group_name": "Enabled" + } + ], "OfferUploadCreditCards": [ { "group_name": "Enabled"
diff --git a/testing/variations/fieldtrial_testing_config_win.json b/testing/variations/fieldtrial_testing_config_win.json index 1f2ed924..d155a53 100644 --- a/testing/variations/fieldtrial_testing_config_win.json +++ b/testing/variations/fieldtrial_testing_config_win.json
@@ -137,6 +137,11 @@ "group_name": "Enabled" } ], + "MojoChannel": [ + { + "group_name": "Enabled" + } + ], "NetworkQualityEstimator": [ { "group_name": "Enabled",
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index fe1f9b14..d66e39c 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -569,9 +569,6 @@ crbug.com/380217 [ Linux Win ] fast/shapes/shape-outside-floats/shape-outside-floats-inset-rounded-large-radius.html [ Skip ] crbug.com/380217 [ Win ] fast/shapes/shape-outside-floats/shape-outside-floats-inset-rounded-bottom-left.html [ Skip ] -crbug.com/601011 css2.1/20110323/background-intrinsic-004.htm [ NeedsManualRebaseline ] -crbug.com/601011 svg/as-background-image/background-image-preserveaspectRatio-support.html [ NeedsManualRebaseline ] - crbug.com/405389 imported/csswg-test/css-shapes-1/shape-outside/supported-shapes/polygon/shape-outside-polygon-017.html [ Failure ] crbug.com/424365 imported/csswg-test/css-shapes-1/shape-outside/shape-image/shape-image-010.html [ Failure ] crbug.com/424365 imported/csswg-test/css-shapes-1/shape-outside/shape-image/shape-image-024.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-ImageBitmap-close-expected.txt b/third_party/WebKit/LayoutTests/fast/canvas/canvas-ImageBitmap-close-expected.txt index 45f865c..26836ff4 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-ImageBitmap-close-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-ImageBitmap-close-expected.txt
@@ -9,6 +9,7 @@ PASS bitmap.height is imgHeight PASS bitmap.width is 0 PASS bitmap.height is 0 +PASS ctx.drawImage(bitmap, 0, 0) threw exception InvalidStateError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The image source is neutered. PASS Apply structured clone to an already closed bitmap is rejected as expected: DataCloneError: Failed to execute 'postMessage' on 'Worker': An ImageBitmap is neutered and could not be cloned. PASS Apply transfering to an already closed bitmap is rejected as expected: DataCloneError: Failed to execute 'postMessage' on 'Worker': An ImageBitmap is neutered and could not be cloned. PASS createImageBitmap from a closed ImageBitmap was rejected. IndexSizeError: Failed to execute 'createImageBitmap' on 'Window': The source width provided is 0.
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-ImageBitmap-close.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-ImageBitmap-close.html index 7f6eacf..6e791297 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-ImageBitmap-close.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-ImageBitmap-close.html
@@ -10,6 +10,7 @@ var imgWidth = 10; var imageData = new ImageData(10, 10); var bitmap; +var ctx; createImageBitmap(imageData).then(imageBitmap => { bitmap = imageBitmap; shouldBe("bitmap.width", "imgWidth"); @@ -25,6 +26,12 @@ shouldBe("bitmap.width", "0"); shouldBe("bitmap.height", "0"); + var canvas = document.createElement("canvas"); + canvas.width = imgWidth; + canvas.height = imgHeight; + ctx = canvas.getContext("2d"); + shouldThrow("ctx.drawImage(bitmap, 0, 0)"); + // Try to apply structured clone to an already closed bitmap try { worker.postMessage({data: bitmap});
diff --git a/third_party/WebKit/LayoutTests/http/tests/credentialmanager/credentialscontainer-get-basics.html b/third_party/WebKit/LayoutTests/http/tests/credentialmanager/credentialscontainer-get-basics.html index 2aad940..1d5b51d 100644 --- a/third_party/WebKit/LayoutTests/http/tests/credentialmanager/credentialscontainer-get-basics.html +++ b/third_party/WebKit/LayoutTests/http/tests/credentialmanager/credentialscontainer-get-basics.html
@@ -10,15 +10,15 @@ } function stubRejectionChecker(reason) { - assert_unreached("get() should not reject, but did: " + reason.name); + assert_unreached("get(...) should not reject, but did: " + reason.name); } (function() { var t = async_test("Verify the basics of get()."); t.step(function () { navigator.credentials.get().then( - t.step_func(stubResolverUndefinedChecker.bind(t)), - t.step_func(stubRejectionChecker.bind(t))); + t.unreached_func(), + t.step_func_done()); }); }());
diff --git a/third_party/WebKit/LayoutTests/http/tests/credentialmanager/idl-expected.txt b/third_party/WebKit/LayoutTests/http/tests/credentialmanager/idl-expected.txt new file mode 100644 index 0000000..16219ba --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/credentialmanager/idl-expected.txt
@@ -0,0 +1,50 @@ +This is a testharness.js-based test. +PASS CredentialsContainer interface: existence and properties of interface object +PASS CredentialsContainer interface object length +PASS CredentialsContainer interface object name +FAIL CredentialsContainer interface: existence and properties of interface prototype object assert_equals: class string of CredentialsContainer.prototype expected "[object CredentialsContainerPrototype]" but got "[object CredentialsContainer]" +PASS CredentialsContainer interface: existence and properties of interface prototype object's "constructor" property +FAIL CredentialsContainer interface: operation get(CredentialRequestOptions) assert_unreached: Throws "TypeError: Illegal invocation" instead of rejecting promise Reached unreachable code +FAIL CredentialsContainer interface: operation store(Credential) assert_unreached: Throws "TypeError: Illegal invocation" instead of rejecting promise Reached unreachable code +FAIL CredentialsContainer interface: operation requireUserMediation() assert_unreached: Throws "TypeError: Illegal invocation" instead of rejecting promise Reached unreachable code +PASS CredentialsContainer must be primary interface of navigator.credentials +PASS Stringification of navigator.credentials +PASS CredentialsContainer interface: navigator.credentials must inherit property "get" with the proper type (0) +PASS CredentialsContainer interface: calling get(CredentialRequestOptions) on navigator.credentials with too few arguments must throw TypeError +PASS CredentialsContainer interface: navigator.credentials must inherit property "store" with the proper type (1) +PASS CredentialsContainer interface: calling store(Credential) on navigator.credentials with too few arguments must throw TypeError +PASS CredentialsContainer interface: navigator.credentials must inherit property "requireUserMediation" with the proper type (2) +PASS PasswordCredential interface: existence and properties of interface object +PASS PasswordCredential interface object length +PASS PasswordCredential interface object name +FAIL PasswordCredential interface: existence and properties of interface prototype object assert_equals: class string of PasswordCredential.prototype expected "[object PasswordCredentialPrototype]" but got "[object PasswordCredential]" +PASS PasswordCredential interface: existence and properties of interface prototype object's "constructor" property +PASS PasswordCredential interface: attribute idName +PASS PasswordCredential interface: attribute passwordName +PASS PasswordCredential interface: attribute additionalData +PASS PasswordCredential must be primary interface of new PasswordCredential({ id: "id", password: "pencil", iconURL: "https://example.com/", name: "name" }) +PASS Stringification of new PasswordCredential({ id: "id", password: "pencil", iconURL: "https://example.com/", name: "name" }) +PASS PasswordCredential interface: new PasswordCredential({ id: "id", password: "pencil", iconURL: "https://example.com/", name: "name" }) must inherit property "idName" with the proper type (0) +PASS PasswordCredential interface: new PasswordCredential({ id: "id", password: "pencil", iconURL: "https://example.com/", name: "name" }) must inherit property "passwordName" with the proper type (1) +PASS PasswordCredential interface: new PasswordCredential({ id: "id", password: "pencil", iconURL: "https://example.com/", name: "name" }) must inherit property "additionalData" with the proper type (2) +PASS SiteBoundCredential interface: new PasswordCredential({ id: "id", password: "pencil", iconURL: "https://example.com/", name: "name" }) must inherit property "name" with the proper type (0) +PASS SiteBoundCredential interface: new PasswordCredential({ id: "id", password: "pencil", iconURL: "https://example.com/", name: "name" }) must inherit property "iconURL" with the proper type (1) +PASS Credential interface: new PasswordCredential({ id: "id", password: "pencil", iconURL: "https://example.com/", name: "name" }) must inherit property "id" with the proper type (0) +PASS Credential interface: new PasswordCredential({ id: "id", password: "pencil", iconURL: "https://example.com/", name: "name" }) must inherit property "type" with the proper type (1) +PASS FederatedCredential interface: existence and properties of interface object +PASS FederatedCredential interface object length +PASS FederatedCredential interface object name +FAIL FederatedCredential interface: existence and properties of interface prototype object assert_equals: class string of FederatedCredential.prototype expected "[object FederatedCredentialPrototype]" but got "[object FederatedCredential]" +PASS FederatedCredential interface: existence and properties of interface prototype object's "constructor" property +PASS FederatedCredential interface: attribute provider +PASS FederatedCredential interface: attribute protocol +PASS FederatedCredential must be primary interface of new FederatedCredential({ id: "id", provider: "https://example.com", iconURL: "https://example.com/", name: "name" }) +PASS Stringification of new FederatedCredential({ id: "id", provider: "https://example.com", iconURL: "https://example.com/", name: "name" }) +PASS FederatedCredential interface: new FederatedCredential({ id: "id", provider: "https://example.com", iconURL: "https://example.com/", name: "name" }) must inherit property "provider" with the proper type (0) +PASS FederatedCredential interface: new FederatedCredential({ id: "id", provider: "https://example.com", iconURL: "https://example.com/", name: "name" }) must inherit property "protocol" with the proper type (1) +PASS SiteBoundCredential interface: new FederatedCredential({ id: "id", provider: "https://example.com", iconURL: "https://example.com/", name: "name" }) must inherit property "name" with the proper type (0) +PASS SiteBoundCredential interface: new FederatedCredential({ id: "id", provider: "https://example.com", iconURL: "https://example.com/", name: "name" }) must inherit property "iconURL" with the proper type (1) +PASS Credential interface: new FederatedCredential({ id: "id", provider: "https://example.com", iconURL: "https://example.com/", name: "name" }) must inherit property "id" with the proper type (0) +PASS Credential interface: new FederatedCredential({ id: "id", provider: "https://example.com", iconURL: "https://example.com/", name: "name" }) must inherit property "type" with the proper type (1) +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/http/tests/credentialmanager/idl.html b/third_party/WebKit/LayoutTests/http/tests/credentialmanager/idl.html new file mode 100644 index 0000000..1107384 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/credentialmanager/idl.html
@@ -0,0 +1,86 @@ +<!DOCTYPE html> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<script src=/w3c/resources/WebIDLParser.js></script> +<script src=/w3c/resources/idlharness.js></script> +<script type="text/plain" id="untested"> + dictionary CredentialData { + USVString id; + }; + + interface Credential { + readonly attribute USVString id; + readonly attribute DOMString type; + }; + + dictionary SiteBoundCredentialData : CredentialData { + USVString name; + USVString iconURL; + }; + + interface SiteBoundCredential : Credential { + readonly attribute USVString name; + readonly attribute USVString iconURL; + }; + + dictionary PasswordCredentialData : SiteBoundCredentialData { + USVString password; + }; + + typedef (FormData or URLSearchParams) CredentialBodyType; + + + dictionary FederatedCredentialData : SiteBoundCredentialData { + USVString provider; + DOMString protocol; + }; + + dictionary CredentialRequestOptions { + boolean password = false; + FederatedCredentialRequestOptions federated; + + boolean unmediated = false; + }; + + dictionary FederatedCredentialRequestOptions { + sequence<USVString> providers; + sequence<DOMString> protocols; + }; + +</script> +<script type="text/plain" id="tested"> + interface CredentialsContainer { + Promise<Credential?> get(CredentialRequestOptions options); + Promise<Credential> store(Credential credential); + Promise<void> requireUserMediation(); + }; + + [Constructor(PasswordCredentialData data), + Constructor(HTMLFormElement form), + Exposed=Window] + interface PasswordCredential : SiteBoundCredential { + attribute USVString idName; + attribute USVString passwordName; + + attribute CredentialBodyType? additionalData; + }; + + [Constructor(FederatedCredentialData data), Exposed=Window] + interface FederatedCredential : SiteBoundCredential { + readonly attribute USVString provider; + readonly attribute DOMString? protocol; + }; +</script> +<script> + "use strict"; + var idl_array = new IdlArray(); + idl_array.add_untested_idls(document.querySelector('#untested').textContent); + idl_array.add_idls(document.querySelector('#tested').textContent); + idl_array.add_objects({ + CredentialsContainer: ['navigator.credentials'], + PasswordCredential: ['new PasswordCredential({ id: "id", password: "pencil", iconURL: "https://example.com/", name: "name" })'], + FederatedCredential: ['new FederatedCredential({ id: "id", provider: "https://example.com", iconURL: "https://example.com/", name: "name" })'] + }); + idl_array.test(); +</script> +
diff --git a/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-async-third-party-script.html b/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-async-third-party-script.html index 681bbe08..47e27630 100644 --- a/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-async-third-party-script.html +++ b/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-async-third-party-script.html
@@ -3,7 +3,7 @@ <script src="../resources/testharnessreport.js"></script> <script> var t = async_test('Cross origin but asynchronous doc.written scripts are not blocked'); - var src = 'http://localhost:8000/loading/resources/js-loaded.js?2'; + var src = 'http://localhost:8000/loading/resources/js-loaded.js?async-third-party-script'; var jsLoaded = false; var loadSuccess = false; if (window.internals) {
diff --git a/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-block-all-conn-types.html b/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-block-all-conn-types.html index c2f0e4b..2c9d563c 100644 --- a/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-block-all-conn-types.html +++ b/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-block-all-conn-types.html
@@ -2,7 +2,7 @@ <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> <script> - var src = 'http://localhost:8000/loading/resources/js-loaded.js'; + var src = 'http://localhost:8000/loading/resources/js-loaded.js?all-conn-types'; var jsLoaded = false; var loadSuccess = false; var loadFailed = false;
diff --git a/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-block.html b/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-block.html index 355ba97..13b11a3 100644 --- a/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-block.html +++ b/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-block.html
@@ -4,7 +4,7 @@ <script> var sameOrigin = 'http://127.0.0.1:8000'; var crossOrigin = 'http://localhost:8000'; - var filePath = '/loading/resources/js-loaded.js'; + var filePath = '/loading/resources/js-loaded.js?cross-origin'; var jsLoaded = false; var loadSuccess = false; @@ -32,6 +32,7 @@ }, false); } + filePath = '/loading/resources/js-loaded.js?same-origin'; src = sameOrigin + filePath; jsLoaded = false; loadSuccess = false; @@ -49,6 +50,7 @@ var jsLoaded = false; var loadSuccess = false; + var filePath = '/loading/resources/js-loaded.js?cross-origin'; src = crossOrigin + filePath; document.write('<scr' + 'ipt src="' + src + '" onload="loadSuccess=true"></scr' + 'ipt>'); </script> @@ -64,7 +66,7 @@ loadSuccess = false; var loadFailed = false; - filePath = '/loading/resources/js-loaded.js?1'; + filePath = '/loading/resources/js-loaded.js?cross-origin2'; src = crossOrigin + filePath; document.write('<scr' + 'ipt src="' + src + '" onload="loadSuccess=true" onError="loadFailed=true"></scr' + 'ipt>'); </script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-conn-type.html b/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-conn-type.html index 2123f92..65d0ddd 100644 --- a/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-conn-type.html +++ b/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-conn-type.html
@@ -2,7 +2,7 @@ <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> <script> - var src = 'http://localhost:8000/loading/resources/js-loaded.js'; + var src = 'http://localhost:8000/loading/resources/js-loaded.js?conn-type'; var jsLoaded = false; var loadSuccess = false; if (window.internals) {
diff --git a/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-reload-expected.txt b/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-reload-expected.txt new file mode 100644 index 0000000..ce92881 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-reload-expected.txt
@@ -0,0 +1,15 @@ +main frame - didStartProvisionalLoadForFrame +main frame - didCommitLoadForFrame +main frame - didStartProvisionalLoadForFrame +main frame - didCommitLoadForFrame +main frame - didStartProvisionalLoadForFrame +main frame - didCommitLoadForFrame +main frame - didFinishDocumentLoadForFrame +main frame - didHandleOnloadEventsForFrame +main frame - didFinishLoadForFrame +This is a testharness.js-based test. +PASS window.internals is required for the test to run +PASS Load Success +PASS cross origin doc.written scripts are not blocked in a page reload +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-reload.html b/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-reload.html new file mode 100644 index 0000000..f4d03d2 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/loading/doc-write-sync-third-party-script-reload.html
@@ -0,0 +1,82 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script> + var reloadTestSuccess = false; +</script> + +<script> + test(function () { + assert_true(window.internals !== null); + }, "window.internals is required for the test to run"); + + internals.settings.setDisallowFetchForDocWrittenScriptsInMainFrameOnSlowConnections(true); + internals.setNetworkStateNotifierTestOnly(true); + internals.setNetworkConnectionInfo('cellular2g', 1.0); + internals.evictAllResources(); + + window.addEventListener('beforeunload', function() { + internals.settings.setDisallowFetchForDocWrittenScriptsInMainFrameOnSlowConnections(false); + internals.setNetworkStateNotifierTestOnly(false); + // Remove localStorage items, just in case they haven't been + // already removed, due to test failure. + if (window.localStorage.getItem("errorCount") !== null) { + window.localStorage.removeItem("errorCount"); + } + + if (window.localStorage.getItem("successCount") !== null) { + window.localStorage.removeItem("successCount"); + } + }, false); + + if (window.localStorage.getItem("errorCount") === null) { + window.localStorage.setItem("errorCount", 0); + } + + if (window.localStorage.getItem("successCount") === null) { + window.localStorage.setItem("successCount", 0); + } + + var crossOrigin = 'http://localhost:8000'; + var filePath = '/loading/resources/js-loaded.js?reload'; + + // First time the script will be blocked and onError will reload the page. + // On reload the script should not be blocked. + // This tests two types of reload, one with and one without cache bypass. + // The script should not be blocked in both cases. + src = crossOrigin + filePath; + document.write('<scr' + 'ipt src="' + src + '" onload="test(successTest,\'Load Success\')" onError="test(errorTest,\'Load Error\')"></scr' + 'ipt>'); + + var successTest = function() { + assert_equals(+window.localStorage.getItem("errorCount"), 1); + + var successCount = +window.localStorage.getItem("successCount"); + assert_greater_than_equal(successCount, 0); + + if (successCount == 0) + { + window.localStorage.setItem("successCount", 1); + internals.forceReload(true); + return; + } + + assert_equals(successCount, 1); + window.localStorage.removeItem("errorCount"); + window.localStorage.removeItem("successCount"); + reloadTestSuccess=true; + } + + var errorTest = function() { + assert_equals(+window.localStorage.getItem("errorCount"), 0); + assert_equals(+window.localStorage.getItem("successCount"), 0); + window.localStorage.setItem("errorCount", 1); + internals.forceReload(false); + } + +</script> + +<script> + test(function () { + assert_true(reloadTestSuccess); + }, "cross origin doc.written scripts are not blocked in a page reload"); +</script>
diff --git a/third_party/WebKit/LayoutTests/imported/web-platform-tests/dom/interfaces-expected.txt b/third_party/WebKit/LayoutTests/imported/web-platform-tests/dom/interfaces-expected.txt index 32a49ad..3c1f716d 100644 --- a/third_party/WebKit/LayoutTests/imported/web-platform-tests/dom/interfaces-expected.txt +++ b/third_party/WebKit/LayoutTests/imported/web-platform-tests/dom/interfaces-expected.txt
@@ -1512,7 +1512,7 @@ FAIL DOMTokenList interface: operation replace(DOMString,DOMString) assert_own_property: interface prototype object missing non-static operation expected property "replace" missing PASS DOMTokenList interface: operation supports(DOMString) PASS DOMTokenList interface: attribute value -FAIL DOMTokenList interface: stringifier assert_true: property is not enumerable expected true got false +PASS DOMTokenList interface: stringifier PASS DOMTokenList must be primary interface of document.body.classList PASS Stringification of document.body.classList PASS DOMTokenList interface: document.body.classList must inherit property "length" with the proper type (0)
diff --git a/third_party/WebKit/LayoutTests/platform/android/css2.1/20110323/background-intrinsic-004-expected.png b/third_party/WebKit/LayoutTests/platform/android/css2.1/20110323/background-intrinsic-004-expected.png deleted file mode 100644 index dea275b..0000000 --- a/third_party/WebKit/LayoutTests/platform/android/css2.1/20110323/background-intrinsic-004-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/css2.1/20110323/background-intrinsic-004-expected.png b/third_party/WebKit/LayoutTests/platform/linux/css2.1/20110323/background-intrinsic-004-expected.png index 9bc4f7e..dea275b 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/css2.1/20110323/background-intrinsic-004-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/css2.1/20110323/background-intrinsic-004-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/as-background-image/background-image-preserveaspectRatio-support-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/as-background-image/background-image-preserveaspectRatio-support-expected.png index fe7e490c..9b0ca31 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/as-background-image/background-image-preserveaspectRatio-support-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/as-background-image/background-image-preserveaspectRatio-support-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/css2.1/20110323/background-intrinsic-004-expected.png b/third_party/WebKit/LayoutTests/platform/mac/css2.1/20110323/background-intrinsic-004-expected.png index f3b1064..01b8d3c 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/css2.1/20110323/background-intrinsic-004-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/css2.1/20110323/background-intrinsic-004-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/as-background-image/background-image-preserveaspectRatio-support-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/as-background-image/background-image-preserveaspectRatio-support-expected.png index 079fc0c..bcf3e438 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/as-background-image/background-image-preserveaspectRatio-support-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/as-background-image/background-image-preserveaspectRatio-support-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/css2.1/20110323/background-intrinsic-004-expected.png b/third_party/WebKit/LayoutTests/platform/win/css2.1/20110323/background-intrinsic-004-expected.png index a901ef3..e568cb6ff 100644 --- a/third_party/WebKit/LayoutTests/platform/win/css2.1/20110323/background-intrinsic-004-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/css2.1/20110323/background-intrinsic-004-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/as-background-image/background-image-preserveaspectRatio-support-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/as-background-image/background-image-preserveaspectRatio-support-expected.png index ce47ab5a..ad1cce7 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/as-background-image/background-image-preserveaspectRatio-support-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/as-background-image/background-image-preserveaspectRatio-support-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dom/href-semantics.html b/third_party/WebKit/LayoutTests/svg/dom/href-semantics.html index 4d429823..0656242 100644 --- a/third_party/WebKit/LayoutTests/svg/dom/href-semantics.html +++ b/third_party/WebKit/LayoutTests/svg/dom/href-semantics.html
@@ -134,4 +134,22 @@ assert_false(element.hasAttributeNS(xlinkNs, 'href'), '"xlink:href" no longer exist'); assert_equals(element.href.baseVal, ''); }, document.title+', IDL href reflects "xlink:href"; removeAttribute(xlink:href) w/o NS-prefix resets to default.'); + +test(function() { + var element = document.createElementNS(svgNs, 'a'); + element.setAttributeNS(xlinkNs, 'xlink:href', 'bar'); + assert_false(element.hasAttributeNS(null, 'href'), '"href" does not exist'); + assert_true(element.hasAttributeNS(xlinkNs, 'href'), '"xlink:href" exists'); + assert_equals(element.href.baseVal, 'bar', 'baseVal reflects "xlink:href"'); + assert_equals(element.href.animVal, 'bar', 'animVal reflects "xlink:href"'); +}, document.title+', href.animVal reflects "xlink:href" when it is set.'); + +test(function() { + var element = document.createElementNS(svgNs, 'a'); + element.setAttributeNS(null, 'href', 'bar'); + assert_true(element.hasAttributeNS(null, 'href'), '"href" exists'); + assert_false(element.hasAttributeNS(xlinkNs, 'href'), '"xlink:href" does not exist'); + assert_equals(element.href.baseVal, 'bar', 'baseVal reflects "href"'); + assert_equals(element.href.animVal, 'bar', 'animVal reflects "href"'); +}, document.title+', href.animVal reflects "href" when it is set.'); </script>
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt index 37314012..9b50d99 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -554,9 +554,7 @@ setter normalize interface Credential attribute @@toStringTag - getter iconURL getter id - getter name getter type method constructor interface CredentialsContainer @@ -1192,7 +1190,7 @@ method constructor method dispatchEvent method removeEventListener -interface FederatedCredential : Credential +interface FederatedCredential : SiteBoundCredential attribute @@toStringTag getter protocol getter provider @@ -3522,7 +3520,7 @@ attribute @@toStringTag getter persisted method constructor -interface PasswordCredential : Credential +interface PasswordCredential : SiteBoundCredential attribute @@toStringTag getter additionalData getter idName @@ -5074,6 +5072,11 @@ getter workerStart method constructor setter onerror +interface SiteBoundCredential : Credential + attribute @@toStringTag + getter iconURL + getter name + method constructor interface SourceBuffer : EventTarget attribute @@toStringTag getter appendWindowEnd
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt index 5b2d3f72..1fd50583 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
@@ -753,9 +753,7 @@ method size interface Credential attribute @@toStringTag - getter iconURL getter id - getter name getter type method constructor interface CredentialsContainer @@ -1557,7 +1555,7 @@ method constructor method dispatchEvent method removeEventListener -interface FederatedCredential : Credential +interface FederatedCredential : SiteBoundCredential attribute @@toStringTag getter protocol getter provider @@ -4093,7 +4091,7 @@ attribute @@toStringTag getter persisted method constructor -interface PasswordCredential : Credential +interface PasswordCredential : SiteBoundCredential attribute @@toStringTag getter additionalData getter idName @@ -5780,6 +5778,11 @@ getter value method constructor setter value +interface SiteBoundCredential : Credential + attribute @@toStringTag + getter iconURL + getter name + method constructor interface Skew : TransformComponent attribute @@toStringTag getter ax
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp b/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp index 4ee53c1..a4eaf56 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp
@@ -43,7 +43,6 @@ #include "bindings/core/v8/V8Window.h" #include "bindings/core/v8/WorkerOrWorkletScriptController.h" #include "core/dom/Document.h" -#include "core/dom/ExceptionCode.h" #include "core/fetch/AccessControlStatus.h" #include "core/frame/LocalDOMWindow.h" #include "core/frame/LocalFrame.h"
diff --git a/third_party/WebKit/Source/core/animation/AnimationTest.cpp b/third_party/WebKit/Source/core/animation/AnimationTest.cpp index 8fa8467..15b7bae8 100644 --- a/third_party/WebKit/Source/core/animation/AnimationTest.cpp +++ b/third_party/WebKit/Source/core/animation/AnimationTest.cpp
@@ -36,7 +36,6 @@ #include "core/animation/ElementAnimations.h" #include "core/animation/KeyframeEffect.h" #include "core/dom/Document.h" -#include "core/dom/ExceptionCode.h" #include "core/dom/QualifiedName.h" #include "core/testing/DummyPageHolder.h" #include "platform/weborigin/KURL.h"
diff --git a/third_party/WebKit/Source/core/animation/KeyframeEffectTest.cpp b/third_party/WebKit/Source/core/animation/KeyframeEffectTest.cpp index e5ecb34..cb4c2bf6 100644 --- a/third_party/WebKit/Source/core/animation/KeyframeEffectTest.cpp +++ b/third_party/WebKit/Source/core/animation/KeyframeEffectTest.cpp
@@ -15,7 +15,6 @@ #include "core/animation/KeyframeEffectModel.h" #include "core/animation/Timing.h" #include "core/dom/Document.h" -#include "core/dom/ExceptionCode.h" #include "core/testing/DummyPageHolder.h" #include "testing/gtest/include/gtest/gtest.h" #include <v8.h>
diff --git a/third_party/WebKit/Source/core/animation/PairwiseInterpolationValue.h b/third_party/WebKit/Source/core/animation/PairwiseInterpolationValue.h index 40f5f5be..0d16dd8 100644 --- a/third_party/WebKit/Source/core/animation/PairwiseInterpolationValue.h +++ b/third_party/WebKit/Source/core/animation/PairwiseInterpolationValue.h
@@ -16,9 +16,9 @@ DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); PairwiseInterpolationValue(PassOwnPtr<InterpolableValue> startInterpolableValue, PassOwnPtr<InterpolableValue> endInterpolableValue, PassRefPtr<NonInterpolableValue> nonInterpolableValue = nullptr) - : startInterpolableValue(startInterpolableValue) - , endInterpolableValue(endInterpolableValue) - , nonInterpolableValue(nonInterpolableValue) + : startInterpolableValue(std::move(startInterpolableValue)) + , endInterpolableValue(std::move(endInterpolableValue)) + , nonInterpolableValue(std::move(nonInterpolableValue)) { } PairwiseInterpolationValue(std::nullptr_t) { }
diff --git a/third_party/WebKit/Source/core/animation/TypedInterpolationValue.h b/third_party/WebKit/Source/core/animation/TypedInterpolationValue.h index cf4391d2..dc92019a 100644 --- a/third_party/WebKit/Source/core/animation/TypedInterpolationValue.h +++ b/third_party/WebKit/Source/core/animation/TypedInterpolationValue.h
@@ -16,7 +16,7 @@ public: static PassOwnPtr<TypedInterpolationValue> create(const InterpolationType& type, PassOwnPtr<InterpolableValue> interpolableValue, PassRefPtr<NonInterpolableValue> nonInterpolableValue = nullptr) { - return adoptPtr(new TypedInterpolationValue(type, interpolableValue, nonInterpolableValue)); + return adoptPtr(new TypedInterpolationValue(type, std::move(interpolableValue), nonInterpolableValue)); } PassOwnPtr<TypedInterpolationValue> clone() const @@ -35,7 +35,7 @@ private: TypedInterpolationValue(const InterpolationType& type, PassOwnPtr<InterpolableValue> interpolableValue, PassRefPtr<NonInterpolableValue> nonInterpolableValue) : m_type(type) - , m_value(interpolableValue, nonInterpolableValue) + , m_value(std::move(interpolableValue), nonInterpolableValue) { ASSERT(m_value.interpolableValue); }
diff --git a/third_party/WebKit/Source/core/core.gypi b/third_party/WebKit/Source/core/core.gypi index fd396f23..1eeaa41 100644 --- a/third_party/WebKit/Source/core/core.gypi +++ b/third_party/WebKit/Source/core/core.gypi
@@ -408,6 +408,7 @@ 'html/track/AudioTrack.idl', 'html/track/VideoTrack.idl', 'inspector/DevToolsHost.idl', + 'offscreencanvas/OffscreenCanvas.idl', 'workers/DedicatedWorkerGlobalScope.idl', 'workers/SharedWorkerGlobalScope.idl', 'workers/WorkerGlobalScope.idl', @@ -1945,6 +1946,8 @@ 'loader/appcache/ApplicationCache.h', 'loader/appcache/ApplicationCacheHost.cpp', 'loader/appcache/ApplicationCacheHost.h', + 'offscreencanvas/OffscreenCanvas.cpp', + 'offscreencanvas/OffscreenCanvas.h', 'origin_trials/OriginTrialContext.cpp', 'origin_trials/OriginTrialContext.h', 'page/AutoscrollController.cpp',
diff --git a/third_party/WebKit/Source/core/css/CSSPathValue.cpp b/third_party/WebKit/Source/core/css/CSSPathValue.cpp index 78770a3c..d25c1f81 100644 --- a/third_party/WebKit/Source/core/css/CSSPathValue.cpp +++ b/third_party/WebKit/Source/core/css/CSSPathValue.cpp
@@ -16,7 +16,7 @@ CSSPathValue* CSSPathValue::create(PassOwnPtr<SVGPathByteStream> pathByteStream) { - return CSSPathValue::create(StylePath::create(pathByteStream)); + return CSSPathValue::create(StylePath::create(std::move(pathByteStream))); } CSSPathValue::CSSPathValue(PassRefPtr<StylePath> stylePath)
diff --git a/third_party/WebKit/Source/core/css/CSSSelector.cpp b/third_party/WebKit/Source/core/css/CSSSelector.cpp index 25be5d3..4355b9d 100644 --- a/third_party/WebKit/Source/core/css/CSSSelector.cpp +++ b/third_party/WebKit/Source/core/css/CSSSelector.cpp
@@ -756,7 +756,7 @@ void CSSSelector::setSelectorList(PassOwnPtr<CSSSelectorList> selectorList) { createRareData(); - m_data.m_rareData->m_selectorList = selectorList; + m_data.m_rareData->m_selectorList = std::move(selectorList); } static bool validateSubSelector(const CSSSelector* selector)
diff --git a/third_party/WebKit/Source/core/css/CSSValuePool.cpp b/third_party/WebKit/Source/core/css/CSSValuePool.cpp index 9769754..35dae10 100644 --- a/third_party/WebKit/Source/core/css/CSSValuePool.cpp +++ b/third_party/WebKit/Source/core/css/CSSValuePool.cpp
@@ -38,8 +38,8 @@ DEFINE_THREAD_SAFE_STATIC_LOCAL(ThreadSpecific<Persistent<CSSValuePool>>, threadSpecificPool, new ThreadSpecific<Persistent<CSSValuePool>>()); Persistent<CSSValuePool>& poolHandle = *threadSpecificPool; if (!poolHandle) { - poolHandle = new CSSValuePool(); - poolHandle.clearOnThreadShutdown(); + poolHandle = new CSSValuePool; + poolHandle.registerAsStaticReference(); } return *poolHandle; }
diff --git a/third_party/WebKit/Source/core/css/StyleRuleKeyframe.h b/third_party/WebKit/Source/core/css/StyleRuleKeyframe.h index 0a68c88..8d5c3cb 100644 --- a/third_party/WebKit/Source/core/css/StyleRuleKeyframe.h +++ b/third_party/WebKit/Source/core/css/StyleRuleKeyframe.h
@@ -16,7 +16,7 @@ public: static StyleRuleKeyframe* create(PassOwnPtr<Vector<double>> keys, StylePropertySet* properties) { - return new StyleRuleKeyframe(keys, properties); + return new StyleRuleKeyframe(std::move(keys), properties); } // Exposed to JavaScript.
diff --git a/third_party/WebKit/Source/core/css/cssom/MatrixTransformComponent.h b/third_party/WebKit/Source/core/css/cssom/MatrixTransformComponent.h index 6062194..4b87cf0 100644 --- a/third_party/WebKit/Source/core/css/cssom/MatrixTransformComponent.h +++ b/third_party/WebKit/Source/core/css/cssom/MatrixTransformComponent.h
@@ -91,7 +91,7 @@ MatrixTransformComponent(PassOwnPtr<const TransformationMatrix> matrix, TransformComponentType fromType) : TransformComponent() - , m_matrix(matrix) + , m_matrix(std::move(matrix)) , m_is2D(is2DComponentType(fromType)) { }
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserSelector.cpp b/third_party/WebKit/Source/core/css/parser/CSSParserSelector.cpp index e93c566..1fb2579 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserSelector.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSParserSelector.cpp
@@ -57,7 +57,7 @@ void CSSParserSelector::setSelectorList(PassOwnPtr<CSSSelectorList> selectorList) { - m_selector->setSelectorList(selectorList); + m_selector->setSelectorList(std::move(selectorList)); } bool CSSParserSelector::isSimple() const @@ -86,7 +86,7 @@ while (end->tagHistory()) end = end->tagHistory(); end->setRelation(relation); - end->setTagHistory(selector); + end->setTagHistory(std::move(selector)); } PassOwnPtr<CSSParserSelector> CSSParserSelector::releaseTagHistory()
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserSelector.h b/third_party/WebKit/Source/core/css/parser/CSSParserSelector.h index fcd2f6d..1722df6 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserSelector.h +++ b/third_party/WebKit/Source/core/css/parser/CSSParserSelector.h
@@ -66,7 +66,7 @@ bool isSimple() const; CSSParserSelector* tagHistory() const { return m_tagHistory.get(); } - void setTagHistory(PassOwnPtr<CSSParserSelector> selector) { m_tagHistory = selector; } + void setTagHistory(PassOwnPtr<CSSParserSelector> selector) { m_tagHistory = std::move(selector); } void clearTagHistory() { m_tagHistory.clear(); } void appendTagHistory(CSSSelector::RelationType, PassOwnPtr<CSSParserSelector>); PassOwnPtr<CSSParserSelector> releaseTagHistory();
diff --git a/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp index 4778772..02c00b69 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp
@@ -753,7 +753,7 @@ PassOwnPtr<CSSParserSelector> CSSSelectorParser::addSimpleSelectorToCompound(PassOwnPtr<CSSParserSelector> compoundSelector, PassOwnPtr<CSSParserSelector> simpleSelector) { - compoundSelector->appendTagHistory(CSSSelector::SubSelector, simpleSelector); + compoundSelector->appendTagHistory(CSSSelector::SubSelector, std::move(simpleSelector)); return compoundSelector; } @@ -785,7 +785,7 @@ return compoundSelector; OwnPtr<CSSParserSelector> secondCompound = splitAfter->releaseTagHistory(); - secondCompound->appendTagHistory(secondCompound->pseudoType() == CSSSelector::PseudoSlotted ? CSSSelector::ShadowSlot : CSSSelector::ShadowPseudo, compoundSelector); + secondCompound->appendTagHistory(secondCompound->pseudoType() == CSSSelector::PseudoSlotted ? CSSSelector::ShadowSlot : CSSSelector::ShadowPseudo, std::move(compoundSelector)); return secondCompound.release(); }
diff --git a/third_party/WebKit/Source/core/dom/ContextFeatures.cpp b/third_party/WebKit/Source/core/dom/ContextFeatures.cpp index 186c00d2..ee2f3e42 100644 --- a/third_party/WebKit/Source/core/dom/ContextFeatures.cpp +++ b/third_party/WebKit/Source/core/dom/ContextFeatures.cpp
@@ -66,7 +66,7 @@ void provideContextFeaturesTo(Page& page, PassOwnPtr<ContextFeaturesClient> client) { - Supplement<Page>::provideTo(page, ContextFeatures::supplementName(), ContextFeatures::create(client)); + Supplement<Page>::provideTo(page, ContextFeatures::supplementName(), ContextFeatures::create(std::move(client))); } void provideContextFeaturesToDocumentFrom(Document& document, Page& page)
diff --git a/third_party/WebKit/Source/core/dom/DOMError.h b/third_party/WebKit/Source/core/dom/DOMError.h index 3a7512d..c5f5d52 100644 --- a/third_party/WebKit/Source/core/dom/DOMError.h +++ b/third_party/WebKit/Source/core/dom/DOMError.h
@@ -29,7 +29,6 @@ #include "bindings/core/v8/ScriptWrappable.h" #include "core/CoreExport.h" #include "core/dom/DOMException.h" -#include "core/dom/ExceptionCode.h" #include "platform/heap/Handle.h" #include "wtf/text/WTFString.h"
diff --git a/third_party/WebKit/Source/core/dom/DOMImplementation.cpp b/third_party/WebKit/Source/core/dom/DOMImplementation.cpp index 3336723..0d11478 100644 --- a/third_party/WebKit/Source/core/dom/DOMImplementation.cpp +++ b/third_party/WebKit/Source/core/dom/DOMImplementation.cpp
@@ -34,7 +34,6 @@ #include "core/dom/DocumentInit.h" #include "core/dom/DocumentType.h" #include "core/dom/Element.h" -#include "core/dom/ExceptionCode.h" #include "core/dom/Text.h" #include "core/dom/XMLDocument.h" #include "core/dom/custom/CustomElementRegistrationContext.h"
diff --git a/third_party/WebKit/Source/core/dom/DOMTokenList.idl b/third_party/WebKit/Source/core/dom/DOMTokenList.idl index 1b0ce77..6a4c9f7 100644 --- a/third_party/WebKit/Source/core/dom/DOMTokenList.idl +++ b/third_party/WebKit/Source/core/dom/DOMTokenList.idl
@@ -35,8 +35,7 @@ [RaisesException, CustomElementCallbacks] boolean toggle(DOMString token, optional boolean force); [RaisesException, CustomElementCallbacks] boolean supports(DOMString token); attribute DOMString value; - // FIXME: stringifier should be enumerable. - [NotEnumerable] stringifier; + stringifier; iterable<DOMString>;
diff --git a/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp b/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp index 21dd5c70..0c90a77 100644 --- a/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp +++ b/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp
@@ -47,7 +47,7 @@ // transferred away by takeDecoder(), we need to make sure it's recreated // next time data is appended. m_needsDecoder = !decoder; - m_decoder = decoder; + m_decoder = std::move(decoder); } TextResourceDecoder* DecodedDataDocumentParser::decoder()
diff --git a/third_party/WebKit/Source/core/dom/Document.cpp b/third_party/WebKit/Source/core/dom/Document.cpp index a14c543d..65a27abf 100644 --- a/third_party/WebKit/Source/core/dom/Document.cpp +++ b/third_party/WebKit/Source/core/dom/Document.cpp
@@ -3939,7 +3939,7 @@ void Document::registerEventFactory(PassOwnPtr<EventFactoryBase> eventFactory) { DCHECK(!eventFactories().contains(eventFactory.get())); - eventFactories().add(eventFactory); + eventFactories().add(std::move(eventFactory)); } Event* Document::createEvent(ExecutionContext* executionContext, const String& eventType, ExceptionState& exceptionState) @@ -4554,7 +4554,7 @@ void Document::setTransformSource(PassOwnPtr<TransformSource> source) { - m_transformSource = source; + m_transformSource = std::move(source); } String Document::designMode() const @@ -5143,12 +5143,12 @@ // FIXME(crbug.com/305497): This should be removed after ExecutionContext-LocalDOMWindow migration. void Document::postTask(const WebTraceLocation& location, PassOwnPtr<ExecutionContextTask> task) { - m_taskRunner->postTask(location, task); + m_taskRunner->postTask(location, std::move(task)); } void Document::postInspectorTask(const WebTraceLocation& location, PassOwnPtr<ExecutionContextTask> task) { - m_taskRunner->postInspectorTask(location, task); + m_taskRunner->postInspectorTask(location, std::move(task)); } void Document::tasksWereSuspended()
diff --git a/third_party/WebKit/Source/core/dom/ExecutionContext.cpp b/third_party/WebKit/Source/core/dom/ExecutionContext.cpp index cf518f5..4619388 100644 --- a/third_party/WebKit/Source/core/dom/ExecutionContext.cpp +++ b/third_party/WebKit/Source/core/dom/ExecutionContext.cpp
@@ -98,7 +98,7 @@ void ExecutionContext::postSuspendableTask(PassOwnPtr<SuspendableTask> task) { - m_suspendedTasks.append(task); + m_suspendedTasks.append(std::move(task)); if (!m_activeDOMObjectsAreSuspended) postTask(BLINK_FROM_HERE, createSameThreadTask(&ExecutionContext::runSuspendableTasks, this)); }
diff --git a/third_party/WebKit/Source/core/dom/ExecutionContextTask.h b/third_party/WebKit/Source/core/dom/ExecutionContextTask.h index 67b50b34..6782908 100644 --- a/third_party/WebKit/Source/core/dom/ExecutionContextTask.h +++ b/third_party/WebKit/Source/core/dom/ExecutionContextTask.h
@@ -116,9 +116,9 @@ // When posting tasks across threads, use |createCrossThreadTask|. template<typename FunctionType, typename... P> PassOwnPtr<ExecutionContextTask> createSameThreadTask( - FunctionType function, const P&... parameters) + FunctionType function, P&&... parameters) { - return internal::CallClosureTask<WTF::SameThreadAffinity>::create(bind(function, parameters...)); + return internal::CallClosureTask<WTF::SameThreadAffinity>::create(bind(function, std::forward<P>(parameters)...)); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp b/third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp index 5036c65..4baf2bb 100644 --- a/third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp +++ b/third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp
@@ -56,7 +56,7 @@ Platform::current()->mainThread()->getWebTaskRunner()->postTask(location, threadSafeBind( &MainThreadTaskRunner::perform, CrossThreadWeakPersistentThisPointer<MainThreadTaskRunner>(this), - task, + passed(std::move(task)), isInspectorTask)); } @@ -64,18 +64,18 @@ { if (!task->taskNameForInstrumentation().isEmpty()) InspectorInstrumentation::asyncTaskScheduled(m_context, task->taskNameForInstrumentation(), task.get()); - postTaskInternal(location, task, false); + postTaskInternal(location, std::move(task), false); } void MainThreadTaskRunner::postInspectorTask(const WebTraceLocation& location, PassOwnPtr<ExecutionContextTask> task) { - postTaskInternal(location, task, true); + postTaskInternal(location, std::move(task), true); } void MainThreadTaskRunner::perform(PassOwnPtr<ExecutionContextTask> task, bool isInspectorTask) { if (!isInspectorTask && (m_context->tasksNeedSuspension() || !m_pendingTasks.isEmpty())) { - m_pendingTasks.append(task); + m_pendingTasks.append(std::move(task)); return; }
diff --git a/third_party/WebKit/Source/core/dom/MessagePort.cpp b/third_party/WebKit/Source/core/dom/MessagePort.cpp index 92769be..155592f3 100644 --- a/third_party/WebKit/Source/core/dom/MessagePort.cpp +++ b/third_party/WebKit/Source/core/dom/MessagePort.cpp
@@ -156,7 +156,7 @@ DCHECK(!m_entangledChannel); DCHECK(getExecutionContext()); - m_entangledChannel = remote; + m_entangledChannel = std::move(remote); m_entangledChannel->setClient(this); }
diff --git a/third_party/WebKit/Source/core/dom/MutationObserver.cpp b/third_party/WebKit/Source/core/dom/MutationObserver.cpp index 3c2625ab..7148235 100644 --- a/third_party/WebKit/Source/core/dom/MutationObserver.cpp +++ b/third_party/WebKit/Source/core/dom/MutationObserver.cpp
@@ -32,7 +32,6 @@ #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/Microtask.h" -#include "core/dom/ExceptionCode.h" #include "core/dom/MutationCallback.h" #include "core/dom/MutationObserverInit.h" #include "core/dom/MutationObserverRegistration.h"
diff --git a/third_party/WebKit/Source/core/dom/NodeIterator.cpp b/third_party/WebKit/Source/core/dom/NodeIterator.cpp index 3110394..7b50e89 100644 --- a/third_party/WebKit/Source/core/dom/NodeIterator.cpp +++ b/third_party/WebKit/Source/core/dom/NodeIterator.cpp
@@ -27,7 +27,6 @@ #include "bindings/core/v8/ExceptionState.h" #include "core/dom/Attr.h" #include "core/dom/Document.h" -#include "core/dom/ExceptionCode.h" #include "core/dom/NodeTraversal.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/dom/TreeWalker.cpp b/third_party/WebKit/Source/core/dom/TreeWalker.cpp index 822d13da..d099f8f1 100644 --- a/third_party/WebKit/Source/core/dom/TreeWalker.cpp +++ b/third_party/WebKit/Source/core/dom/TreeWalker.cpp
@@ -27,7 +27,6 @@ #include "bindings/core/v8/ExceptionMessages.h" #include "bindings/core/v8/ExceptionState.h" #include "core/dom/ContainerNode.h" -#include "core/dom/ExceptionCode.h" #include "core/dom/NodeTraversal.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/events/MessageEvent.cpp b/third_party/WebKit/Source/core/events/MessageEvent.cpp index ee0dbbc..6c676b67 100644 --- a/third_party/WebKit/Source/core/events/MessageEvent.cpp +++ b/third_party/WebKit/Source/core/events/MessageEvent.cpp
@@ -93,7 +93,7 @@ , m_origin(origin) , m_lastEventId(lastEventId) , m_source(source) - , m_channels(channels) + , m_channels(std::move(channels)) , m_suborigin(suborigin) { if (m_dataAsSerializedScriptValue)
diff --git a/third_party/WebKit/Source/core/fetch/ImageResource.cpp b/third_party/WebKit/Source/core/fetch/ImageResource.cpp index d76dadb..67abfc4a4 100644 --- a/third_party/WebKit/Source/core/fetch/ImageResource.cpp +++ b/third_party/WebKit/Source/core/fetch/ImageResource.cpp
@@ -410,7 +410,7 @@ // If there's no boundary, just handle the request normally. if (response.isMultipart() && !response.multipartBoundary().isEmpty()) m_multipartParser = new MultipartImageResourceParser(response, response.multipartBoundary(), this); - Resource::responseReceived(response, handle); + Resource::responseReceived(response, std::move(handle)); if (RuntimeEnabledFeatures::clientHintsEnabled()) { m_devicePixelRatioHeaderValue = m_response.httpHeaderField(HTTPNames::Content_DPR).toFloat(&m_hasDevicePixelRatioHeaderValue); if (!m_hasDevicePixelRatioHeaderValue || m_devicePixelRatioHeaderValue <= 0.0) {
diff --git a/third_party/WebKit/Source/core/fetch/RawResource.cpp b/third_party/WebKit/Source/core/fetch/RawResource.cpp index 26470a2..27e67ac 100644 --- a/third_party/WebKit/Source/core/fetch/RawResource.cpp +++ b/third_party/WebKit/Source/core/fetch/RawResource.cpp
@@ -150,7 +150,7 @@ while (RawResourceClient* c = w.next()) { // |handle| is cleared when passed, but it's not a problem because // |handle| is null when there are two or more clients, as asserted. - c->responseReceived(this, m_response, handle); + c->responseReceived(this, m_response, std::move(handle)); } // If we successfully revalidated, we won't get appendData() calls.
diff --git a/third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp b/third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp index cddaf32..09aaa19 100644 --- a/third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp +++ b/third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp
@@ -32,7 +32,6 @@ #include "bindings/core/v8/ExceptionState.h" #include "core/dom/DOMArrayBuffer.h" -#include "core/dom/ExceptionCode.h" #include "core/fileapi/Blob.h" #include "core/fileapi/FileError.h" #include "core/fileapi/FileReaderLoader.h"
diff --git a/third_party/WebKit/Source/core/frame/DOMTimerCoordinator.cpp b/third_party/WebKit/Source/core/frame/DOMTimerCoordinator.cpp index e7238f90..064b701 100644 --- a/third_party/WebKit/Source/core/frame/DOMTimerCoordinator.cpp +++ b/third_party/WebKit/Source/core/frame/DOMTimerCoordinator.cpp
@@ -13,7 +13,7 @@ DOMTimerCoordinator::DOMTimerCoordinator(PassOwnPtr<WebTaskRunner> timerTaskRunner) : m_circularSequentialID(0) , m_timerNestingLevel(0) - , m_timerTaskRunner(timerTaskRunner) + , m_timerTaskRunner(std::move(timerTaskRunner)) { } @@ -62,7 +62,7 @@ void DOMTimerCoordinator::setTimerTaskRunner(PassOwnPtr<WebTaskRunner> timerTaskRunner) { - m_timerTaskRunner = timerTaskRunner; + m_timerTaskRunner = std::move(timerTaskRunner); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/frame/FrameHost.cpp b/third_party/WebKit/Source/core/frame/FrameHost.cpp index cf736ea3..90c54b89 100644 --- a/third_party/WebKit/Source/core/frame/FrameHost.cpp +++ b/third_party/WebKit/Source/core/frame/FrameHost.cpp
@@ -32,6 +32,8 @@ #include "core/frame/EventHandlerRegistry.h" #include "core/frame/FrameView.h" +#include "core/frame/PageScaleConstraints.h" +#include "core/frame/PageScaleConstraintsSet.h" #include "core/frame/TopControls.h" #include "core/inspector/ConsoleMessageStorage.h" #include "core/page/Page.h" @@ -165,7 +167,7 @@ rootView->setNeedsLayout(); } -void FrameHost::setUserAgentPageScaleConstraints(PageScaleConstraints newConstraints) +void FrameHost::setUserAgentPageScaleConstraints(const PageScaleConstraints& newConstraints) { if (newConstraints == pageScaleConstraintsSet().userAgentConstraints()) return;
diff --git a/third_party/WebKit/Source/core/frame/FrameHost.h b/third_party/WebKit/Source/core/frame/FrameHost.h index 40b4169..ebfac921 100644 --- a/third_party/WebKit/Source/core/frame/FrameHost.h +++ b/third_party/WebKit/Source/core/frame/FrameHost.h
@@ -32,14 +32,12 @@ #define FrameHost_h #include "core/CoreExport.h" -#include "core/frame/PageScaleConstraintsSet.h" -#include "core/frame/TopControls.h" -#include "core/frame/VisualViewport.h" #include "platform/heap/Handle.h" #include "wtf/Allocator.h" #include "wtf/Noncopyable.h" #include "wtf/OwnPtr.h" #include "wtf/PassOwnPtr.h" +#include "wtf/text/AtomicString.h" namespace blink { @@ -48,10 +46,13 @@ class Deprecation; class EventHandlerRegistry; class Page; +struct PageScaleConstraints; class PageScaleConstraintsSet; class Settings; +class TopControls; class UseCounter; class Visitor; +class VisualViewport; // FrameHost is the set of global data shared between multiple frames // and is provided by the embedder to each frame when created. @@ -102,7 +103,7 @@ int subframeCount() const; void setDefaultPageScaleLimits(float minScale, float maxScale); - void setUserAgentPageScaleConstraints(PageScaleConstraints newConstraints); + void setUserAgentPageScaleConstraints(const PageScaleConstraints& newConstraints); private: explicit FrameHost(Page&);
diff --git a/third_party/WebKit/Source/core/frame/History.cpp b/third_party/WebKit/Source/core/frame/History.cpp index 7db4f36..469da34 100644 --- a/third_party/WebKit/Source/core/frame/History.cpp +++ b/third_party/WebKit/Source/core/frame/History.cpp
@@ -27,7 +27,6 @@ #include "bindings/core/v8/ExceptionState.h" #include "core/dom/Document.h" -#include "core/dom/ExceptionCode.h" #include "core/frame/LocalFrame.h" #include "core/loader/DocumentLoader.h" #include "core/loader/FrameLoader.h"
diff --git a/third_party/WebKit/Source/core/frame/ImageBitmap.h b/third_party/WebKit/Source/core/frame/ImageBitmap.h index 399bb97..d9174eb 100644 --- a/third_party/WebKit/Source/core/frame/ImageBitmap.h +++ b/third_party/WebKit/Source/core/frame/ImageBitmap.h
@@ -61,6 +61,7 @@ bool wouldTaintOrigin(SecurityOrigin*) const override { return !m_image->originClean(); } void adjustDrawRects(FloatRect* srcRect, FloatRect* dstRect) const override; FloatSize elementSize(const FloatSize&) const override; + bool isImageBitmap() const override { return true; } // ImageBitmapSource implementation IntSize bitmapSourceSize() const override { return size(); }
diff --git a/third_party/WebKit/Source/core/frame/SettingsDelegate.cpp b/third_party/WebKit/Source/core/frame/SettingsDelegate.cpp index 626da21..71236be 100644 --- a/third_party/WebKit/Source/core/frame/SettingsDelegate.cpp +++ b/third_party/WebKit/Source/core/frame/SettingsDelegate.cpp
@@ -35,7 +35,7 @@ namespace blink { SettingsDelegate::SettingsDelegate(PassOwnPtr<Settings> settings) - : m_settings(settings) + : m_settings(std::move(settings)) { if (m_settings) m_settings->setDelegate(this);
diff --git a/third_party/WebKit/Source/core/frame/TopControls.cpp b/third_party/WebKit/Source/core/frame/TopControls.cpp index bfe1f85..387caf2 100644 --- a/third_party/WebKit/Source/core/frame/TopControls.cpp +++ b/third_party/WebKit/Source/core/frame/TopControls.cpp
@@ -22,10 +22,6 @@ { } -TopControls::~TopControls() -{ -} - DEFINE_TRACE(TopControls) { visitor->trace(m_frameHost);
diff --git a/third_party/WebKit/Source/core/frame/TopControls.h b/third_party/WebKit/Source/core/frame/TopControls.h index 2a27d49e..49dd9ee 100644 --- a/third_party/WebKit/Source/core/frame/TopControls.h +++ b/third_party/WebKit/Source/core/frame/TopControls.h
@@ -19,14 +19,13 @@ // duplicating cc::TopControlsManager behaviour. Top controls' self-animation // to completion is still handled by compositor and kicks in when scrolling is // complete (i.e, upon ScrollEnd or FlingEnd). -class CORE_EXPORT TopControls final : public GarbageCollectedFinalized<TopControls> { +class CORE_EXPORT TopControls final : public GarbageCollected<TopControls> { public: static TopControls* create(const FrameHost& host) { return new TopControls(host); } - ~TopControls(); DECLARE_TRACE(); // The amount that the viewport was shrunk by to accommodate the top
diff --git a/third_party/WebKit/Source/core/frame/VisualViewport.cpp b/third_party/WebKit/Source/core/frame/VisualViewport.cpp index fdef2f0e..7329a0a 100644 --- a/third_party/WebKit/Source/core/frame/VisualViewport.cpp +++ b/third_party/WebKit/Source/core/frame/VisualViewport.cpp
@@ -33,6 +33,8 @@ #include "core/frame/FrameHost.h" #include "core/frame/FrameView.h" #include "core/frame/LocalFrame.h" +#include "core/frame/PageScaleConstraints.h" +#include "core/frame/PageScaleConstraintsSet.h" #include "core/frame/Settings.h" #include "core/inspector/InspectorInstrumentation.h" #include "core/layout/LayoutView.h"
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp index 36cb3c4..f3d35c4 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
@@ -312,7 +312,7 @@ m_selfSource = new CSPSource(this, m_selfProtocol, origin->host(), origin->port(), String(), CSPSource::NoWildcard, CSPSource::NoWildcard); } -const PassOwnPtr<Vector<CSPHeaderAndType>> ContentSecurityPolicy::headers() const +PassOwnPtr<Vector<CSPHeaderAndType>> ContentSecurityPolicy::headers() const { OwnPtr<Vector<CSPHeaderAndType>> headers = adoptPtr(new Vector<CSPHeaderAndType>); for (const auto& policy : m_policies) {
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.h b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.h index 6baf2b5..2e410f6 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.h +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.h
@@ -143,7 +143,7 @@ void didReceiveHeaders(const ContentSecurityPolicyResponseHeaders&); void didReceiveHeader(const String&, ContentSecurityPolicyHeaderType, ContentSecurityPolicyHeaderSource); - const PassOwnPtr<Vector<CSPHeaderAndType>> headers() const; + PassOwnPtr<Vector<CSPHeaderAndType>> headers() const; bool allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const; bool allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const;
diff --git a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp index 17f41a03..49faf885 100644 --- a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp
@@ -202,7 +202,7 @@ CanvasRenderingContext::ContextType type = renderingContextFactory->getContextType(); ASSERT(type < CanvasRenderingContext::ContextTypeCount); ASSERT(!renderingContextFactories()[type]); - renderingContextFactories()[type] = renderingContextFactory; + renderingContextFactories()[type] = std::move(renderingContextFactory); } CanvasRenderingContext* HTMLCanvasElement::getCanvasRenderingContext(const String& type, const CanvasContextCreationAttributes& attributes) @@ -799,7 +799,7 @@ int msaaSampleCount = 0; OwnPtr<ImageBufferSurface> surface; if (externalSurface) { - surface = externalSurface; + surface = std::move(externalSurface); } else { surface = createImageBufferSurface(size(), &msaaSampleCount); } @@ -904,7 +904,7 @@ discardImageBuffer(); setWidth(surface->size().width()); setHeight(surface->size().height()); - createImageBufferInternal(surface); + createImageBufferInternal(std::move(surface)); } void HTMLCanvasElement::ensureUnacceleratedImageBuffer()
diff --git a/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp b/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp index 3a0fabf6..d84e2ea9 100644 --- a/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp
@@ -24,7 +24,6 @@ #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ExceptionStatePlaceholder.h" #include "core/HTMLNames.h" -#include "core/dom/ExceptionCode.h" #include "core/dom/shadow/ShadowRoot.h" #include "core/frame/UseCounter.h" #include "core/html/HTMLDivElement.h"
diff --git a/third_party/WebKit/Source/core/html/HTMLOptionsCollection.cpp b/third_party/WebKit/Source/core/html/HTMLOptionsCollection.cpp index aaa2bba5..0fe1979 100644 --- a/third_party/WebKit/Source/core/html/HTMLOptionsCollection.cpp +++ b/third_party/WebKit/Source/core/html/HTMLOptionsCollection.cpp
@@ -24,7 +24,6 @@ #include "bindings/core/v8/ExceptionMessages.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/UnionTypesCore.h" -#include "core/dom/ExceptionCode.h" #include "core/dom/StaticNodeList.h" #include "core/html/HTMLOptionElement.h" #include "core/html/HTMLSelectElement.h"
diff --git a/third_party/WebKit/Source/core/html/canvas/CanvasDrawListener.cpp b/third_party/WebKit/Source/core/html/canvas/CanvasDrawListener.cpp index 58d807e0..4717d51 100644 --- a/third_party/WebKit/Source/core/html/canvas/CanvasDrawListener.cpp +++ b/third_party/WebKit/Source/core/html/canvas/CanvasDrawListener.cpp
@@ -23,9 +23,9 @@ m_frameCaptureRequested = true; } -CanvasDrawListener::CanvasDrawListener(const PassOwnPtr<WebCanvasCaptureHandler> handler) +CanvasDrawListener::CanvasDrawListener(PassOwnPtr<WebCanvasCaptureHandler> handler) : m_frameCaptureRequested(true) - , m_handler(handler) + , m_handler(std::move(handler)) { }
diff --git a/third_party/WebKit/Source/core/html/canvas/CanvasDrawListener.h b/third_party/WebKit/Source/core/html/canvas/CanvasDrawListener.h index 8e20bdfb..1fd851f 100644 --- a/third_party/WebKit/Source/core/html/canvas/CanvasDrawListener.h +++ b/third_party/WebKit/Source/core/html/canvas/CanvasDrawListener.h
@@ -21,7 +21,7 @@ void requestFrame(); protected: - explicit CanvasDrawListener(const PassOwnPtr<WebCanvasCaptureHandler>); + explicit CanvasDrawListener(PassOwnPtr<WebCanvasCaptureHandler>); bool m_frameCaptureRequested; OwnPtr<WebCanvasCaptureHandler> m_handler;
diff --git a/third_party/WebKit/Source/core/html/canvas/CanvasImageSource.h b/third_party/WebKit/Source/core/html/canvas/CanvasImageSource.h index 7e897c43..2c00cb1d 100644 --- a/third_party/WebKit/Source/core/html/canvas/CanvasImageSource.h +++ b/third_party/WebKit/Source/core/html/canvas/CanvasImageSource.h
@@ -57,6 +57,7 @@ virtual bool isVideoElement() const { return false; } virtual bool isCanvasElement() const { return false; } virtual bool isSVGSource() const { return false; } + virtual bool isImageBitmap() const { return false; } // Adjusts the source and destination rectangles for cases where the actual // source image is a subregion of the image returned by getSourceImageForCanvas.
diff --git a/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.cpp b/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.cpp index d9557ca..9d89f0c9 100644 --- a/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.cpp +++ b/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.cpp
@@ -36,6 +36,11 @@ { } +CanvasRenderingContext::CanvasRenderingContext(OffscreenCanvas* canvas) + : m_offscreenCanvas(canvas) +{ +} + CanvasRenderingContext::ContextType CanvasRenderingContext::contextTypeFromId(const String& id) { if (id == "2d") @@ -85,6 +90,7 @@ DEFINE_TRACE(CanvasRenderingContext) { visitor->trace(m_canvas); + visitor->trace(m_offscreenCanvas); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h b/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h index de45e8b..88d3e53 100644 --- a/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h +++ b/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h
@@ -28,6 +28,7 @@ #include "core/CoreExport.h" #include "core/html/HTMLCanvasElement.h" +#include "core/offscreencanvas/OffscreenCanvas.h" #include "wtf/HashSet.h" #include "wtf/Noncopyable.h" #include "wtf/text/StringHash.h" @@ -41,6 +42,7 @@ class CanvasImageSource; class HTMLCanvasElement; class ImageData; +class ImageBitmap; class CORE_EXPORT CanvasRenderingContext : public GarbageCollectedFinalized<CanvasRenderingContext>, public ScriptWrappable { WTF_MAKE_NONCOPYABLE(CanvasRenderingContext); @@ -119,13 +121,19 @@ bool wouldTaintOrigin(CanvasImageSource*); void didMoveToNewDocument(Document*); + // OffscreenCanvas-specific methods + OffscreenCanvas* getOffscreenCanvas() const { return m_offscreenCanvas; } + virtual ImageBitmap* transferToImageBitmap(ExceptionState&) { return nullptr; } + protected: CanvasRenderingContext(HTMLCanvasElement*); + CanvasRenderingContext(OffscreenCanvas*); DECLARE_VIRTUAL_TRACE(); virtual void stop() = 0; private: Member<HTMLCanvasElement> m_canvas; + Member<OffscreenCanvas> m_offscreenCanvas; HashSet<String> m_cleanURLs; HashSet<String> m_dirtyURLs; };
diff --git a/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContextFactory.h b/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContextFactory.h index 97b10d1..a1d94d3b 100644 --- a/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContextFactory.h +++ b/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContextFactory.h
@@ -15,6 +15,7 @@ namespace blink { class HTMLCanvasElement; +class OffscreenCanvas; class CORE_EXPORT CanvasRenderingContextFactory { USING_FAST_MALLOC(CanvasRenderingContextFactory); @@ -23,9 +24,11 @@ CanvasRenderingContextFactory() = default; virtual ~CanvasRenderingContextFactory() { } - virtual CanvasRenderingContext* create(HTMLCanvasElement*, const CanvasContextCreationAttributes&, Document&) = 0; + virtual CanvasRenderingContext* create(HTMLCanvasElement*, const CanvasContextCreationAttributes&, Document&) { return nullptr; } + virtual CanvasRenderingContext* create(OffscreenCanvas*, const CanvasContextCreationAttributes&) { return nullptr; } virtual CanvasRenderingContext::ContextType getContextType() const = 0; - virtual void onError(HTMLCanvasElement*, const String& error) = 0; + virtual void onError(HTMLCanvasElement*, const String& error) {}; + virtual void onError(OffscreenCanvas*, const String& error) {}; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp b/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp index d3052b3..8376110 100644 --- a/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp
@@ -34,7 +34,6 @@ #include "bindings/core/v8/ExceptionState.h" #include "core/HTMLNames.h" #include "core/InputTypeNames.h" -#include "core/dom/ExceptionCode.h" #include "core/events/BeforeTextInsertedEvent.h" #include "core/events/KeyboardEvent.h" #include "core/events/ScopedEventQueue.h"
diff --git a/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp b/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp index 8f71cc260..7b0a0342 100644 --- a/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp +++ b/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp
@@ -82,7 +82,7 @@ void BackgroundHTMLParser::start(PassRefPtr<WeakReference<BackgroundHTMLParser>> reference, PassOwnPtr<Configuration> config, const KURL& documentURL, PassOwnPtr<CachedDocumentParameters> cachedDocumentParameters, const MediaValuesCached::MediaValuesCachedData& mediaValuesCachedData, PassOwnPtr<WebTaskRunner> loadingTaskRunner) { - new BackgroundHTMLParser(reference, config, documentURL, cachedDocumentParameters, mediaValuesCachedData, loadingTaskRunner); + new BackgroundHTMLParser(reference, std::move(config), documentURL, std::move(cachedDocumentParameters), mediaValuesCachedData, std::move(loadingTaskRunner)); // Caller must free by calling stop(). } @@ -103,9 +103,9 @@ , m_pendingTokens(adoptPtr(new CompactHTMLTokenStream)) , m_pendingTokenLimit(config->pendingTokenLimit) , m_xssAuditor(config->xssAuditor.release()) - , m_preloadScanner(adoptPtr(new TokenPreloadScanner(documentURL, cachedDocumentParameters, mediaValuesCachedData))) + , m_preloadScanner(adoptPtr(new TokenPreloadScanner(documentURL, std::move(cachedDocumentParameters), mediaValuesCachedData))) , m_decoder(config->decoder.release()) - , m_loadingTaskRunner(loadingTaskRunner) + , m_loadingTaskRunner(std::move(loadingTaskRunner)) , m_parsedChunkQueue(config->parsedChunkQueue.release()) , m_startingScript(false) { @@ -140,7 +140,7 @@ void BackgroundHTMLParser::setDecoder(PassOwnPtr<TextResourceDecoder> decoder) { ASSERT(decoder); - m_decoder = decoder; + m_decoder = std::move(decoder); } void BackgroundHTMLParser::flush()
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp b/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp index a46da89e..4800977 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp
@@ -374,7 +374,7 @@ // This call should have been made immediately after runScriptsForPausedTreeBuilder // which may have started a network load and left us waiting. ASSERT(!m_lastChunkBeforeScript); - m_lastChunkBeforeScript = chunk; + m_lastChunkBeforeScript = std::move(chunk); return; } @@ -401,7 +401,7 @@ return; } - discardSpeculationsAndResumeFrom(chunk, token.release(), tokenizer.release()); + discardSpeculationsAndResumeFrom(std::move(chunk), token.release(), tokenizer.release()); } void HTMLDocumentParser::discardSpeculationsAndResumeFrom(PassOwnPtr<ParsedChunk> lastChunkBeforeScript, PassOwnPtr<HTMLToken> token, PassOwnPtr<HTMLTokenizer> tokenizer) @@ -411,8 +411,8 @@ OwnPtr<BackgroundHTMLParser::Checkpoint> checkpoint = adoptPtr(new BackgroundHTMLParser::Checkpoint); checkpoint->parser = m_weakFactory.createWeakPtr(); - checkpoint->token = token; - checkpoint->tokenizer = tokenizer; + checkpoint->token = std::move(token); + checkpoint->tokenizer = std::move(tokenizer); checkpoint->treeBuilderState = HTMLTreeBuilderSimulator::stateFor(m_treeBuilder.get()); checkpoint->inputCheckpoint = lastChunkBeforeScript->inputCheckpoint; checkpoint->preloadScannerCheckpoint = lastChunkBeforeScript->preloadScannerCheckpoint; @@ -420,7 +420,7 @@ m_input.current().clear(); // FIXME: This should be passed in instead of cleared. ASSERT(checkpoint->unparsedInput.isSafeToSendToAnotherThread()); - HTMLParserThread::shared()->postTask(threadSafeBind(&BackgroundHTMLParser::resumeFrom, AllowCrossThreadAccess(m_backgroundParser), checkpoint.release())); + HTMLParserThread::shared()->postTask(threadSafeBind(&BackgroundHTMLParser::resumeFrom, AllowCrossThreadAccess(m_backgroundParser), passed(checkpoint.release()))); } size_t HTMLDocumentParser::processParsedChunkFromBackgroundParser(PassOwnPtr<ParsedChunk> popChunk) @@ -438,7 +438,7 @@ ASSERT(!m_token); ASSERT(!m_lastChunkBeforeScript); - OwnPtr<ParsedChunk> chunk(popChunk); + OwnPtr<ParsedChunk> chunk(std::move(popChunk)); OwnPtr<CompactHTMLTokenStream> tokens = chunk->tokens.release(); size_t elementTokenCount = 0; @@ -754,11 +754,11 @@ HTMLParserThread::shared()->postTask(threadSafeBind( &BackgroundHTMLParser::start, reference.release(), - config.release(), + passed(config.release()), document()->url(), - CachedDocumentParameters::create(document()), + passed(CachedDocumentParameters::create(document())), MediaValuesCached::MediaValuesCachedData(*document()), - adoptPtr(m_loadingTaskRunner->clone()))); + passed(adoptPtr(m_loadingTaskRunner->clone())))); } void HTMLDocumentParser::stopBackgroundParser() @@ -1040,7 +1040,7 @@ memcpy(buffer->data(), data, length); TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("blink.debug"), "HTMLDocumentParser::appendBytes", "size", (unsigned)length); - HTMLParserThread::shared()->postTask(threadSafeBind(&BackgroundHTMLParser::appendRawBytesFromMainThread, AllowCrossThreadAccess(m_backgroundParser), buffer.release())); + HTMLParserThread::shared()->postTask(threadSafeBind(&BackgroundHTMLParser::appendRawBytesFromMainThread, AllowCrossThreadAccess(m_backgroundParser), passed(buffer.release()))); return; } @@ -1073,10 +1073,10 @@ void HTMLDocumentParser::setDecoder(PassOwnPtr<TextResourceDecoder> decoder) { ASSERT(decoder); - DecodedDataDocumentParser::setDecoder(decoder); + DecodedDataDocumentParser::setDecoder(std::move(decoder)); if (m_haveBackgroundParser) - HTMLParserThread::shared()->postTask(threadSafeBind(&BackgroundHTMLParser::setDecoder, AllowCrossThreadAccess(m_backgroundParser), takeDecoder())); + HTMLParserThread::shared()->postTask(threadSafeBind(&BackgroundHTMLParser::setDecoder, AllowCrossThreadAccess(m_backgroundParser), passed(takeDecoder()))); } void HTMLDocumentParser::pumpPreloadQueue()
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLParserThread.cpp b/third_party/WebKit/Source/core/html/parser/HTMLParserThread.cpp index 439bf9f..1e4dde7 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLParserThread.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLParserThread.cpp
@@ -95,7 +95,7 @@ postTask(threadSafeBind(&HTMLParserThread::setupHTMLParserThread, AllowCrossThreadAccess(this))); } - m_thread->postTask(BLINK_FROM_HERE, closure); + m_thread->postTask(BLINK_FROM_HERE, std::move(closure)); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp index 86c7f4a7..d4734de6 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp
@@ -478,7 +478,7 @@ , m_isAppCacheEnabled(false) , m_isCSPEnabled(false) , m_templateCount(0) - , m_documentParameters(documentParameters) + , m_documentParameters(std::move(documentParameters)) , m_mediaValues(MediaValuesCached::create(mediaValuesCachedData)) , m_didRewind(false) { @@ -754,7 +754,7 @@ } HTMLPreloadScanner::HTMLPreloadScanner(const HTMLParserOptions& options, const KURL& documentURL, PassOwnPtr<CachedDocumentParameters> documentParameters, const MediaValuesCached::MediaValuesCachedData& mediaValuesCachedData) - : m_scanner(documentURL, documentParameters, mediaValuesCachedData) + : m_scanner(documentURL, std::move(documentParameters), mediaValuesCachedData) , m_tokenizer(HTMLTokenizer::create(options)) { }
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.h b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.h index 955390a..fbbe93b 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.h +++ b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.h
@@ -156,7 +156,7 @@ public: static PassOwnPtr<HTMLPreloadScanner> create(const HTMLParserOptions& options, const KURL& documentURL, PassOwnPtr<CachedDocumentParameters> documentParameters, const MediaValuesCached::MediaValuesCachedData& mediaValuesCachedData) { - return adoptPtr(new HTMLPreloadScanner(options, documentURL, documentParameters, mediaValuesCachedData)); + return adoptPtr(new HTMLPreloadScanner(options, documentURL, std::move(documentParameters), mediaValuesCachedData)); }
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScannerTest.cpp b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScannerTest.cpp index a87f84e..dda2b79a 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScannerTest.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScannerTest.cpp
@@ -80,7 +80,7 @@ protected: void preload(PassOwnPtr<PreloadRequest> preloadRequest, const NetworkHintsInterface&) override { - m_preloadRequest = preloadRequest; + m_preloadRequest = std::move(preloadRequest); } private:
diff --git a/third_party/WebKit/Source/core/html/parser/ParsedChunkQueue.cpp b/third_party/WebKit/Source/core/html/parser/ParsedChunkQueue.cpp index 8ae2a7b..263c9a9 100644 --- a/third_party/WebKit/Source/core/html/parser/ParsedChunkQueue.cpp +++ b/third_party/WebKit/Source/core/html/parser/ParsedChunkQueue.cpp
@@ -19,7 +19,7 @@ MutexLocker locker(m_mutex); bool wasEmpty = m_pendingChunks.isEmpty(); - m_pendingChunks.append(chunk); + m_pendingChunks.append(std::move(chunk)); return wasEmpty; }
diff --git a/third_party/WebKit/Source/core/input/EventHandler.cpp b/third_party/WebKit/Source/core/input/EventHandler.cpp index 9f54c24..c2c1a97 100644 --- a/third_party/WebKit/Source/core/input/EventHandler.cpp +++ b/third_party/WebKit/Source/core/input/EventHandler.cpp
@@ -56,6 +56,7 @@ #include "core/frame/FrameView.h" #include "core/frame/LocalFrame.h" #include "core/frame/Settings.h" +#include "core/frame/TopControls.h" #include "core/frame/UseCounter.h" #include "core/frame/VisualViewport.h" #include "core/html/HTMLCanvasElement.h"
diff --git a/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp index 42f79f1f..b41cbcf 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp
@@ -667,7 +667,7 @@ return; } m_state->setBoolean(CSSAgentState::cssAgentEnabled, true); - m_resourceContentLoader->ensureResourcesContentLoaded(m_resourceContentLoaderClientId, bind(&InspectorCSSAgent::resourceContentLoaded, this, prpCallback)); + m_resourceContentLoader->ensureResourcesContentLoaded(m_resourceContentLoaderClientId, bind(&InspectorCSSAgent::resourceContentLoaded, this, passed(std::move(prpCallback)))); } void InspectorCSSAgent::resourceContentLoaded(PassOwnPtr<EnableCallback> callback) @@ -1217,7 +1217,7 @@ { FrontendOperationScope scope; HeapVector<Member<StyleSheetAction>> actions; - if (!multipleStyleTextsActions(errorString, edits, &actions)) + if (!multipleStyleTextsActions(errorString, std::move(edits), &actions)) return; TrackExceptionState exceptionState; @@ -1349,7 +1349,7 @@ if (!element) return; - unsigned forcedPseudoState = computePseudoClassMask(forcedPseudoClasses); + unsigned forcedPseudoState = computePseudoClassMask(std::move(forcedPseudoClasses)); NodeIdToForcedPseudoState::iterator it = m_nodeIdToForcedPseudoState.find(nodeId); unsigned currentForcedPseudoState = it == m_nodeIdToForcedPseudoState.end() ? 0 : it->value; bool needStyleRecalc = forcedPseudoState != currentForcedPseudoState;
diff --git a/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp index 71caabd..8812e24d 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp
@@ -1148,7 +1148,7 @@ void InspectorDOMAgent::highlightQuad(ErrorString* errorString, PassOwnPtr<protocol::Array<double>> quadArray, const Maybe<protocol::DOM::RGBA>& color, const Maybe<protocol::DOM::RGBA>& outlineColor) { OwnPtr<FloatQuad> quad = adoptPtr(new FloatQuad()); - if (!parseQuad(quadArray, quad.get())) { + if (!parseQuad(std::move(quadArray), quad.get())) { *errorString = "Invalid Quad format"; return; } @@ -1161,7 +1161,7 @@ highlightConfig->content = parseColor(color.fromMaybe(nullptr)); highlightConfig->contentOutline = parseColor(outlineColor.fromMaybe(nullptr)); if (m_client) - m_client->highlightQuad(quad, *highlightConfig); + m_client->highlightQuad(std::move(quad), *highlightConfig); } Node* InspectorDOMAgent::nodeForRemoteId(ErrorString* errorString, const String& objectId) @@ -1197,7 +1197,7 @@ if (!node) return; - OwnPtr<InspectorHighlightConfig> highlightConfig = highlightConfigFromInspectorObject(errorString, highlightInspectorObject); + OwnPtr<InspectorHighlightConfig> highlightConfig = highlightConfigFromInspectorObject(errorString, std::move(highlightInspectorObject)); if (!highlightConfig) return;
diff --git a/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp index de0f34c7..cc598311 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
@@ -505,9 +505,9 @@ if (!eventData) return; if (synchronous) - m_debuggerAgent->breakProgram(protocol::Debugger::Paused::ReasonEnum::EventListener, eventData); + m_debuggerAgent->breakProgram(protocol::Debugger::Paused::ReasonEnum::EventListener, std::move(eventData)); else - m_debuggerAgent->schedulePauseOnNextStatement(protocol::Debugger::Paused::ReasonEnum::EventListener, eventData); + m_debuggerAgent->schedulePauseOnNextStatement(protocol::Debugger::Paused::ReasonEnum::EventListener, std::move(eventData)); } PassOwnPtr<protocol::DictionaryValue> InspectorDOMDebuggerAgent::preparePauseOnNativeEventData(const String& eventName, const String* targetName)
diff --git a/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp index c5ade9d..0087ef7 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp
@@ -98,7 +98,7 @@ protocol::Debugger::BreakpointId* outBreakpointId, OwnPtr<protocol::Debugger::Location>* outActualLocation) { - m_v8DebuggerAgent->setBreakpoint(errorString, inLocation, inCondition, outBreakpointId, outActualLocation); + m_v8DebuggerAgent->setBreakpoint(errorString, std::move(inLocation), inCondition, outBreakpointId, std::move(outActualLocation)); } void InspectorDebuggerAgent::removeBreakpoint(ErrorString* errorString, @@ -111,7 +111,7 @@ PassOwnPtr<protocol::Debugger::Location> inLocation, const Maybe<bool>& inInterstatementLocation) { - m_v8DebuggerAgent->continueToLocation(errorString, inLocation, inInterstatementLocation); + m_v8DebuggerAgent->continueToLocation(errorString, std::move(inLocation), inInterstatementLocation); } void InspectorDebuggerAgent::stepOver(ErrorString* errorString) @@ -228,7 +228,7 @@ PassOwnPtr<protocol::Runtime::CallArgument> inNewValue, const String16& inCallFrameId) { - m_v8DebuggerAgent->setVariableValue(errorString, inScopeNumber, inVariableName, inNewValue, inCallFrameId); + m_v8DebuggerAgent->setVariableValue(errorString, inScopeNumber, inVariableName, std::move(inNewValue), inCallFrameId); } void InspectorDebuggerAgent::getBacktrace(ErrorString* errorString, @@ -254,7 +254,7 @@ const String16& inScriptId, PassOwnPtr<protocol::Array<protocol::Debugger::ScriptPosition>> inPositions) { - m_v8DebuggerAgent->setBlackboxedRanges(errorString, inScriptId, inPositions); + m_v8DebuggerAgent->setBlackboxedRanges(errorString, inScriptId, std::move(inPositions)); } void InspectorDebuggerAgent::scriptExecutionBlockedByCSP(const String& directiveText)
diff --git a/third_party/WebKit/Source/core/inspector/InspectorHighlight.cpp b/third_party/WebKit/Source/core/inspector/InspectorHighlight.cpp index 4620a83d..69873df 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorHighlight.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorHighlight.cpp
@@ -256,7 +256,7 @@ void InspectorHighlight::appendPath(PassOwnPtr<protocol::ListValue> path, const Color& fillColor, const Color& outlineColor, const String& name) { OwnPtr<protocol::DictionaryValue> object = protocol::DictionaryValue::create(); - object->setValue("path", path); + object->setValue("path", std::move(path)); object->setString("fillColor", fillColor.serialized()); if (outlineColor != Color::transparent) object->setString("outlineColor", outlineColor.serialized());
diff --git a/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp index 95c422e..7c583318 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp
@@ -518,7 +518,7 @@ callback->sendFailure("Agent is not enabled."); return; } - m_inspectorResourceContentLoader->ensureResourcesContentLoaded(m_resourceContentLoaderClientId, bind(&InspectorPageAgent::getResourceContentAfterResourcesContentLoaded, this, frameId, url, callback)); + m_inspectorResourceContentLoader->ensureResourcesContentLoaded(m_resourceContentLoaderClientId, bind(&InspectorPageAgent::getResourceContentAfterResourcesContentLoaded, this, frameId, url, passed(std::move(callback)))); } void InspectorPageAgent::searchContentAfterResourcesContentLoaded(const String& frameId, const String& url, const String& query, bool caseSensitive, bool isRegex, PassOwnPtr<SearchInResourceCallback> callback) @@ -548,7 +548,7 @@ callback->sendFailure("Agent is not enabled."); return; } - m_inspectorResourceContentLoader->ensureResourcesContentLoaded(m_resourceContentLoaderClientId, bind(&InspectorPageAgent::searchContentAfterResourcesContentLoaded, this, frameId, url, query, optionalCaseSensitive.fromMaybe(false), optionalIsRegex.fromMaybe(false), callback)); + m_inspectorResourceContentLoader->ensureResourcesContentLoaded(m_resourceContentLoaderClientId, bind(&InspectorPageAgent::searchContentAfterResourcesContentLoaded, this, frameId, url, query, optionalCaseSensitive.fromMaybe(false), optionalIsRegex.fromMaybe(false), passed(std::move(callback)))); } void InspectorPageAgent::setDocumentContent(ErrorString* errorString, const String& frameId, const String& html)
diff --git a/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp index 304f1c95..8eea7fa 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp
@@ -132,8 +132,8 @@ public: InspectorFileReaderLoaderClient(PassRefPtr<BlobDataHandle> blob, PassOwnPtr<TextResourceDecoder> decoder, PassOwnPtr<GetResponseBodyCallback> callback) : m_blob(blob) - , m_decoder(decoder) - , m_callback(callback) + , m_decoder(std::move(decoder)) + , m_callback(std::move(callback)) { m_loader = FileReaderLoader::create(FileReaderLoader::ReadByClient, this); } @@ -939,13 +939,13 @@ BlobDataHandle* blob = resourceData->downloadedFileBlob(); LocalFrame* frame = IdentifiersFactory::frameById(m_inspectedFrames, resourceData->frameId()); Document* document = frame->document(); - InspectorFileReaderLoaderClient* client = new InspectorFileReaderLoaderClient(blob, InspectorPageAgent::createResourceTextDecoder(resourceData->mimeType(), resourceData->textEncodingName()), callback); + InspectorFileReaderLoaderClient* client = new InspectorFileReaderLoaderClient(blob, InspectorPageAgent::createResourceTextDecoder(resourceData->mimeType(), resourceData->textEncodingName()), std::move(callback)); client->start(document); } void InspectorResourceAgent::getResponseBody(ErrorString* errorString, const String& requestId, PassOwnPtr<GetResponseBodyCallback> passCallback) { - OwnPtr<GetResponseBodyCallback> callback = passCallback; + OwnPtr<GetResponseBodyCallback> callback = std::move(passCallback); NetworkResourcesData::ResourceData const* resourceData = m_resourcesData->data(requestId); if (!resourceData) { callback->sendFailure("No resource with given identifier found");
diff --git a/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp b/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp index bac53d0c..3da5343 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp
@@ -155,7 +155,7 @@ { if (!m_started) start(); - m_callbacks.add(clientId, Callbacks()).storedValue->value.append(callback); + m_callbacks.add(clientId, Callbacks()).storedValue->value.append(std::move(callback)); checkDone(); }
diff --git a/third_party/WebKit/Source/core/inspector/InspectorSession.cpp b/third_party/WebKit/Source/core/inspector/InspectorSession.cpp index 4dc20ee..83d04455 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorSession.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorSession.cpp
@@ -101,7 +101,7 @@ if (m_autoFlush) m_client->sendProtocolMessage(m_sessionId, 0, message->toJSONString(), String()); else - m_notificationQueue.append(message); + m_notificationQueue.append(std::move(message)); } void InspectorSession::flush()
diff --git a/third_party/WebKit/Source/core/inspector/InspectorTaskRunner.cpp b/third_party/WebKit/Source/core/inspector/InspectorTaskRunner.cpp index 3d31d0a..55f47bbb 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorTaskRunner.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorTaskRunner.cpp
@@ -32,7 +32,7 @@ void InspectorTaskRunner::appendTask(PassOwnPtr<Task> task) { MutexLocker lock(m_mutex); - m_queue.append(task); + m_queue.append(std::move(task)); m_condition.signal(); }
diff --git a/third_party/WebKit/Source/core/inspector/LayoutEditor.cpp b/third_party/WebKit/Source/core/inspector/LayoutEditor.cpp index 56bed8a..3b1a748b 100644 --- a/third_party/WebKit/Source/core/inspector/LayoutEditor.cpp +++ b/third_party/WebKit/Source/core/inspector/LayoutEditor.cpp
@@ -32,7 +32,7 @@ OwnPtr<protocol::DictionaryValue> object = protocol::DictionaryValue::create(); object->setString("type", type); object->setString("propertyName", propertyName); - object->setObject("propertyValue", valueDescription); + object->setObject("propertyValue", std::move(valueDescription)); return object.release(); } @@ -418,7 +418,7 @@ ScriptForbiddenScope::AllowUserAgentScript allowScript; OwnPtr<protocol::ListValue> command = protocol::ListValue::create(); command->pushValue(protocol::StringValue::create(method)); - command->pushValue(argument); + command->pushValue(std::move(argument)); m_scriptController->executeScriptInMainWorld("dispatch(" + command->toJSONString() + ")", ScriptController::ExecuteScriptWhenScriptsDisabled); }
diff --git a/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp b/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp index e13a5c0..30d2e9b 100644 --- a/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp +++ b/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp
@@ -94,7 +94,7 @@ { ASSERT(!m_clientMessageLoop); ASSERT(clientMessageLoop); - m_clientMessageLoop = clientMessageLoop; + m_clientMessageLoop = std::move(clientMessageLoop); } void MainThreadDebugger::contextCreated(ScriptState* scriptState, LocalFrame* frame, SecurityOrigin* origin) @@ -131,7 +131,7 @@ { MutexLocker locker(creationMutex()); if (s_instance) { - s_instance->m_taskRunner->appendTask(task); + s_instance->m_taskRunner->appendTask(std::move(task)); s_instance->m_taskRunner->interruptAndRunAllTasksDontWait(s_instance->m_isolate); } }
diff --git a/third_party/WebKit/Source/core/inspector/NetworkResourcesData.h b/third_party/WebKit/Source/core/inspector/NetworkResourcesData.h index d7f0193..daa12192 100644 --- a/third_party/WebKit/Source/core/inspector/NetworkResourcesData.h +++ b/third_party/WebKit/Source/core/inspector/NetworkResourcesData.h
@@ -115,7 +115,7 @@ void setTextEncodingName(const String& textEncodingName) { m_textEncodingName = textEncodingName; } TextResourceDecoder* decoder() const { return m_decoder.get(); } - void setDecoder(PassOwnPtr<TextResourceDecoder> decoder) { m_decoder = decoder; } + void setDecoder(PassOwnPtr<TextResourceDecoder> decoder) { m_decoder = std::move(decoder); } PassRefPtr<SharedBuffer> buffer() const { return m_buffer; } void setBuffer(PassRefPtr<SharedBuffer> buffer) { m_buffer = buffer; }
diff --git a/third_party/WebKit/Source/core/layout/LayoutGrid.cpp b/third_party/WebKit/Source/core/layout/LayoutGrid.cpp index 89030b6..2a0cfb4c 100644 --- a/third_party/WebKit/Source/core/layout/LayoutGrid.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutGrid.cpp
@@ -619,7 +619,7 @@ double hypotheticalFactorUnitSize = leftOverSpace / std::max<double>(1, flexFactorSum); // product of the hypothetical "flex factor unit" and any flexible track's "flex factor" must be grater than such track's "base size". - OwnPtr<TrackIndexSet> additionalTracksToTreatAsInflexible = tracksToTreatAsInflexible; + OwnPtr<TrackIndexSet> additionalTracksToTreatAsInflexible = std::move(tracksToTreatAsInflexible); bool validFlexFactorUnit = true; for (auto index : flexibleTracksIndexes) { if (additionalTracksToTreatAsInflexible && additionalTracksToTreatAsInflexible->contains(index))
diff --git a/third_party/WebKit/Source/core/layout/shapes/PolygonShape.h b/third_party/WebKit/Source/core/layout/shapes/PolygonShape.h index 31c90904..62dd4a6 100644 --- a/third_party/WebKit/Source/core/layout/shapes/PolygonShape.h +++ b/third_party/WebKit/Source/core/layout/shapes/PolygonShape.h
@@ -63,7 +63,7 @@ public: PolygonShape(PassOwnPtr<Vector<FloatPoint>> vertices, WindRule fillRule) : Shape() - , m_polygon(vertices, fillRule) + , m_polygon(std::move(vertices), fillRule) { }
diff --git a/third_party/WebKit/Source/core/layout/shapes/RasterShape.h b/third_party/WebKit/Source/core/layout/shapes/RasterShape.h index 8db830e2..e9d262e3 100644 --- a/third_party/WebKit/Source/core/layout/shapes/RasterShape.h +++ b/third_party/WebKit/Source/core/layout/shapes/RasterShape.h
@@ -82,7 +82,7 @@ WTF_MAKE_NONCOPYABLE(RasterShape); public: RasterShape(PassOwnPtr<RasterShapeIntervals> intervals, const IntSize& marginRectSize) - : m_intervals(intervals) + : m_intervals(std::move(intervals)) , m_marginRectSize(marginRectSize) { m_intervals->initializeBounds();
diff --git a/third_party/WebKit/Source/core/layout/shapes/Shape.cpp b/third_party/WebKit/Source/core/layout/shapes/Shape.cpp index e1d9745..176bd3e 100644 --- a/third_party/WebKit/Source/core/layout/shapes/Shape.cpp +++ b/third_party/WebKit/Source/core/layout/shapes/Shape.cpp
@@ -70,7 +70,7 @@ static PassOwnPtr<Shape> createPolygonShape(PassOwnPtr<Vector<FloatPoint>> vertices, WindRule fillRule) { - return adoptPtr(new PolygonShape(vertices, fillRule)); + return adoptPtr(new PolygonShape(std::move(vertices), fillRule)); } static inline FloatRect physicalRectToLogical(const FloatRect& rect, float logicalBoxHeight, WritingMode writingMode)
diff --git a/third_party/WebKit/Source/core/layout/svg/ReferenceFilterBuilder.cpp b/third_party/WebKit/Source/core/layout/svg/ReferenceFilterBuilder.cpp index 13a56bc1..1bb451f 100644 --- a/third_party/WebKit/Source/core/layout/svg/ReferenceFilterBuilder.cpp +++ b/third_party/WebKit/Source/core/layout/svg/ReferenceFilterBuilder.cpp
@@ -59,7 +59,7 @@ void ReferenceFilterBuilder::setDocumentResourceReference(const FilterOperation* filterOperation, PassOwnPtr<DocumentResourceReference> documentResourceReference) { ASSERT(!documentResourceReferences().contains(filterOperation)); - documentResourceReferences().add(filterOperation, documentResourceReference); + documentResourceReferences().add(filterOperation, std::move(documentResourceReference)); } Filter* ReferenceFilterBuilder::build(float zoom, Element* element, FilterEffect* previousEffect, const ReferenceFilterOperation& filterOperation, const FloatSize* referenceBoxSize, const SkPaint* fillPaint, const SkPaint* strokePaint)
diff --git a/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp b/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp index 87c579b6..0b8713a 100644 --- a/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp +++ b/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp
@@ -154,7 +154,7 @@ void CrossOriginPreflightResultCache::appendEntry(const String& origin, const KURL& url, PassOwnPtr<CrossOriginPreflightResultCacheItem> preflightResult) { ASSERT(isMainThread()); - m_preflightHashMap.set(std::make_pair(origin, url), preflightResult); + m_preflightHashMap.set(std::make_pair(origin, url), std::move(preflightResult)); } bool CrossOriginPreflightResultCache::canSkipPreflight(const String& origin, const KURL& url, StoredCredentials includeCredentials, const String& method, const HTTPHeaderMap& requestHeaders)
diff --git a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp index 2e82f63..8951304 100644 --- a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp
@@ -576,7 +576,7 @@ if (handle) m_isUsingDataConsumerHandle = true; - handleResponse(resource->identifier(), response, handle); + handleResponse(resource->identifier(), response, std::move(handle)); // |this| may be dead here. } @@ -646,7 +646,7 @@ return; } m_fallbackRequestForServiceWorker = ResourceRequest(); - m_client->didReceiveResponse(identifier, response, handle); + m_client->didReceiveResponse(identifier, response, std::move(handle)); return; } @@ -675,7 +675,7 @@ } } - m_client->didReceiveResponse(identifier, response, handle); + m_client->didReceiveResponse(identifier, response, std::move(handle)); } void DocumentThreadableLoader::setSerializedCachedMetadata(Resource*, const char* data, size_t size)
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp index cd2acbd..f2cbded4f2 100644 --- a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp +++ b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
@@ -86,6 +86,17 @@ if (!document.settings()) return false; + if (!document.frame()) + return false; + + // Do not block scripts if it is a page reload. This is to enable pages to + // recover if blocking of a script is leading to a page break and the user + // reloads the page. + const FrameLoadType loadType = document.frame()->loader().loadType(); + const bool isReload = (loadType == FrameLoadTypeReload || loadType == FrameLoadTypeReloadBypassingCache || loadType == FrameLoadTypeSame); + if (isReload) + return false; + const bool isSlowConnection = networkStateNotifier().connectionType() == WebConnectionTypeCellular2G; const bool disallowFetch = document.settings()->disallowFetchForDocWrittenScriptsInMainFrame() || (document.settings()->disallowFetchForDocWrittenScriptsInMainFrameOnSlowConnections() && isSlowConnection); if (!disallowFetch)
diff --git a/third_party/WebKit/Source/core/loader/ThreadableLoaderClientWrapper.h b/third_party/WebKit/Source/core/loader/ThreadableLoaderClientWrapper.h index 1350195a..4de6111 100644 --- a/third_party/WebKit/Source/core/loader/ThreadableLoaderClientWrapper.h +++ b/third_party/WebKit/Source/core/loader/ThreadableLoaderClientWrapper.h
@@ -88,7 +88,7 @@ ResourceResponse response(responseData.get()); if (m_client) - m_client->didReceiveResponse(identifier, response, handle); + m_client->didReceiveResponse(identifier, response, std::move(handle)); } void didReceiveData(PassOwnPtr<Vector<char>> data) @@ -141,7 +141,7 @@ void didReceiveResourceTiming(PassOwnPtr<CrossThreadResourceTimingInfoData> timingData) { - OwnPtr<ResourceTimingInfo> info(ResourceTimingInfo::adopt(timingData)); + OwnPtr<ResourceTimingInfo> info(ResourceTimingInfo::adopt(std::move(timingData))); if (m_resourceTimingClient) m_resourceTimingClient->didReceiveResourceTiming(*info);
diff --git a/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp b/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp index 810bf14..b4a60c9 100644 --- a/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp +++ b/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp
@@ -52,7 +52,11 @@ return adoptPtr(new ::testing::StrictMock<MockThreadableLoaderClient>); } MOCK_METHOD2(didSendData, void(unsigned long long, unsigned long long)); - MOCK_METHOD3(didReceiveResponse, void(unsigned long, const ResourceResponse&, PassOwnPtr<WebDataConsumerHandle>)); + MOCK_METHOD3(didReceiveResponseMock, void(unsigned long, const ResourceResponse&, WebDataConsumerHandle*)); + void didReceiveResponse(unsigned long identifier, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle) + { + didReceiveResponseMock(identifier, response, handle.get()); + } MOCK_METHOD2(didReceiveData, void(const char*, unsigned)); MOCK_METHOD2(didReceiveCachedMetadata, void(const char*, int)); MOCK_METHOD2(didFinishLoading, void(unsigned long, double)); @@ -295,13 +299,13 @@ { ASSERT(m_workerThread); ASSERT(m_workerThread->isCurrentThread()); - document().postTask(BLINK_FROM_HERE, task); + document().postTask(BLINK_FROM_HERE, std::move(task)); } bool postTaskToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask> task) override { ASSERT(m_workerThread); - m_workerThread->postTask(BLINK_FROM_HERE, task); + m_workerThread->postTask(BLINK_FROM_HERE, std::move(task)); return true; } @@ -477,7 +481,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)).WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)).WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader)); EXPECT_CALL(*client(), didFail(Truly(isCancellation))); startLoader(successURL()); @@ -493,7 +497,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)).WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::clearLoader)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)).WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::clearLoader)); startLoader(successURL()); callCheckpoint(2); @@ -508,7 +512,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)); EXPECT_CALL(*client(), didReceiveData(_, _)).WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader)); EXPECT_CALL(*client(), didFail(Truly(isCancellation))); @@ -525,7 +529,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)); EXPECT_CALL(*client(), didReceiveData(_, _)).WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::clearLoader)); startLoader(successURL()); @@ -541,7 +545,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)); EXPECT_CALL(*client(), didReceiveData(StrEq("fox"), 4)); // We expect didReceiveResourceTiming() calls in DocumentThreadableLoader; // it's used to connect DocumentThreadableLoader to WorkerThreadableLoader, @@ -563,7 +567,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)); EXPECT_CALL(*client(), didReceiveData(_, _)); if (GetParam() == DocumentThreadableLoaderTest) EXPECT_CALL(*client(), didReceiveResourceTiming(_)); @@ -582,7 +586,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)); EXPECT_CALL(*client(), didReceiveData(_, _)); if (GetParam() == DocumentThreadableLoaderTest) EXPECT_CALL(*client(), didReceiveResourceTiming(_)); @@ -601,7 +605,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)); EXPECT_CALL(*client(), didFail(Truly(isNotCancellation))); startLoader(errorURL()); @@ -617,7 +621,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)); EXPECT_CALL(*client(), didFail(_)).WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader)); startLoader(errorURL()); @@ -633,7 +637,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)); EXPECT_CALL(*client(), didFail(_)).WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::clearLoader)); startLoader(errorURL()); @@ -739,7 +743,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)); EXPECT_CALL(*client(), didReceiveData(StrEq("fox"), 4)); if (GetParam() == DocumentThreadableLoaderTest) EXPECT_CALL(*client(), didReceiveResourceTiming(_)); @@ -758,7 +762,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)); EXPECT_CALL(*client(), didReceiveData(StrEq("fox"), 4)); if (GetParam() == DocumentThreadableLoaderTest) EXPECT_CALL(*client(), didReceiveResourceTiming(_)); @@ -777,7 +781,7 @@ callCheckpoint(1); EXPECT_CALL(checkpoint(), Call(2)); - EXPECT_CALL(*client(), didReceiveResponse(_, _, _)); + EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _)); EXPECT_CALL(*client(), didReceiveData(StrEq("fox"), 4)); if (GetParam() == DocumentThreadableLoaderTest) EXPECT_CALL(*client(), didReceiveResourceTiming(_));
diff --git a/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp b/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp index 9edde37..a0dd0fec 100644 --- a/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp +++ b/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp
@@ -218,12 +218,12 @@ void WorkerThreadableLoader::MainThreadBridgeBase::didReceiveResponse(unsigned long identifier, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle) { - forwardTaskToWorker(createCrossThreadTask(&ThreadableLoaderClientWrapper::didReceiveResponse, m_workerClientWrapper, identifier, response, handle)); + forwardTaskToWorker(createCrossThreadTask(&ThreadableLoaderClientWrapper::didReceiveResponse, m_workerClientWrapper, identifier, response, passed(std::move(handle)))); } void WorkerThreadableLoader::MainThreadBridgeBase::didReceiveData(const char* data, unsigned dataLength) { - forwardTaskToWorker(createCrossThreadTask(&ThreadableLoaderClientWrapper::didReceiveData, m_workerClientWrapper, createVectorFromMemoryRegion(data, dataLength))); + forwardTaskToWorker(createCrossThreadTask(&ThreadableLoaderClientWrapper::didReceiveData, m_workerClientWrapper, passed(createVectorFromMemoryRegion(data, dataLength)))); } void WorkerThreadableLoader::MainThreadBridgeBase::didDownloadData(int dataLength) @@ -233,7 +233,7 @@ void WorkerThreadableLoader::MainThreadBridgeBase::didReceiveCachedMetadata(const char* data, int dataLength) { - forwardTaskToWorker(createCrossThreadTask(&ThreadableLoaderClientWrapper::didReceiveCachedMetadata, m_workerClientWrapper, createVectorFromMemoryRegion(data, dataLength))); + forwardTaskToWorker(createCrossThreadTask(&ThreadableLoaderClientWrapper::didReceiveCachedMetadata, m_workerClientWrapper, passed(createVectorFromMemoryRegion(data, dataLength)))); } void WorkerThreadableLoader::MainThreadBridgeBase::didFinishLoading(unsigned long identifier, double finishTime) @@ -282,12 +282,12 @@ void WorkerThreadableLoader::MainThreadAsyncBridge::forwardTaskToWorker(PassOwnPtr<ExecutionContextTask> task) { - loaderProxy()->postTaskToWorkerGlobalScope(task); + loaderProxy()->postTaskToWorkerGlobalScope(std::move(task)); } void WorkerThreadableLoader::MainThreadAsyncBridge::forwardTaskToWorkerOnLoaderDone(PassOwnPtr<ExecutionContextTask> task) { - loaderProxy()->postTaskToWorkerGlobalScope(task); + loaderProxy()->postTaskToWorkerGlobalScope(std::move(task)); } WorkerThreadableLoader::MainThreadSyncBridge::MainThreadSyncBridge( @@ -352,7 +352,7 @@ MutexLocker lock(m_lock); RELEASE_ASSERT(!m_done); - m_clientTasks.append(task); + m_clientTasks.append(std::move(task)); } void WorkerThreadableLoader::MainThreadSyncBridge::forwardTaskToWorkerOnLoaderDone(PassOwnPtr<ExecutionContextTask> task) @@ -362,7 +362,7 @@ MutexLocker lock(m_lock); RELEASE_ASSERT(!m_done); - m_clientTasks.append(task); + m_clientTasks.append(std::move(task)); m_done = true; m_loaderDoneEvent->signal(); }
diff --git a/third_party/WebKit/Source/core/offscreencanvas/OWNERS b/third_party/WebKit/Source/core/offscreencanvas/OWNERS new file mode 100644 index 0000000..f8e160a --- /dev/null +++ b/third_party/WebKit/Source/core/offscreencanvas/OWNERS
@@ -0,0 +1,3 @@ +junov@chromium.org +xlai@chromium.org +xidachen@chromium.org
diff --git a/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.cpp b/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.cpp new file mode 100644 index 0000000..a210fa7 --- /dev/null +++ b/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.cpp
@@ -0,0 +1,101 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/offscreencanvas/OffscreenCanvas.h" + +#include "core/dom/ExceptionCode.h" +#include "core/html/canvas/CanvasContextCreationAttributes.h" +#include "core/html/canvas/CanvasRenderingContext.h" +#include "core/html/canvas/CanvasRenderingContextFactory.h" +#include "wtf/MathExtras.h" + +namespace blink { + +OffscreenCanvas::OffscreenCanvas(const IntSize& size) + : m_size(size) +{ } + +OffscreenCanvas::~OffscreenCanvas() +{ } + +OffscreenCanvas* OffscreenCanvas::create(unsigned width, unsigned height) +{ + return new OffscreenCanvas(IntSize(clampTo<int>(width), clampTo<int>(height))); +} + +void OffscreenCanvas::setWidth(unsigned width) +{ + m_size.setWidth(clampTo<int>(width)); +} + +void OffscreenCanvas::setHeight(unsigned height) +{ + m_size.setHeight(clampTo<int>(height)); +} + +ImageBitmap* OffscreenCanvas::transferToImageBitmap(ExceptionState& exceptionState) +{ + if (!m_context) { + exceptionState.throwDOMException(InvalidStateError, "Cannot transfer an ImageBitmap from an OffscreenCanvas with no context"); + return nullptr; + } + ImageBitmap* image = m_context->transferToImageBitmap(exceptionState); + if (!image) { + // Undocumented exception (not in spec) + exceptionState.throwDOMException(V8GeneralError, "Out of memory"); + } + return image; +} + +CanvasRenderingContext* OffscreenCanvas::getCanvasRenderingContext(const String& id, const CanvasContextCreationAttributes& attributes) +{ + CanvasRenderingContext::ContextType contextType = CanvasRenderingContext::contextTypeFromId(id); + + // Unknown type. + if (contextType == CanvasRenderingContext::ContextTypeCount) + return nullptr; + + CanvasRenderingContextFactory* factory = getRenderingContextFactory(contextType); + if (!factory) + return nullptr; + + if (m_context) { + if (m_context->getContextType() != contextType) { + factory->onError(this, "OffscreenCanvas has an existing context of a different type"); + return nullptr; + } + } else { + m_context = factory->create(this, attributes); + } + + return m_context.get(); +} + +OffscreenCanvas::ContextFactoryVector& OffscreenCanvas::renderingContextFactories() +{ + DEFINE_STATIC_LOCAL(ContextFactoryVector, s_contextFactories, (CanvasRenderingContext::ContextTypeCount)); + return s_contextFactories; +} + +CanvasRenderingContextFactory* OffscreenCanvas::getRenderingContextFactory(int type) +{ + ASSERT(type < CanvasRenderingContext::ContextTypeCount); + return renderingContextFactories()[type].get(); +} + +void OffscreenCanvas::registerRenderingContextFactory(PassOwnPtr<CanvasRenderingContextFactory> renderingContextFactory) +{ + CanvasRenderingContext::ContextType type = renderingContextFactory->getContextType(); + ASSERT(type < CanvasRenderingContext::ContextTypeCount); + ASSERT(!renderingContextFactories()[type]); + renderingContextFactories()[type] = renderingContextFactory; +} + +DEFINE_TRACE(OffscreenCanvas) +{ + visitor->trace(m_context); + visitor->trace(m_canvas); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvas.h b/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.h similarity index 64% rename from third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvas.h rename to third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.h index 3b285c6d..e367fa2 100644 --- a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvas.h +++ b/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.h
@@ -9,7 +9,6 @@ #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/ScriptWrappable.h" #include "core/html/HTMLCanvasElement.h" -#include "modules/ModulesExport.h" #include "platform/geometry/IntSize.h" #include "platform/heap/Handle.h" @@ -17,11 +16,8 @@ class CanvasContextCreationAttributes; class ImageBitmap; -class OffscreenCanvasRenderingContext; -class OffscreenCanvasRenderingContext2D; -class OffscreenCanvasRenderingContextFactory; -class MODULES_EXPORT OffscreenCanvas final : public GarbageCollectedFinalized<OffscreenCanvas>, public ScriptWrappable { +class CORE_EXPORT OffscreenCanvas final : public GarbageCollectedFinalized<OffscreenCanvas>, public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: static OffscreenCanvas* create(unsigned width, unsigned height); @@ -34,26 +30,25 @@ void setHeight(unsigned); // API Methods - OffscreenCanvasRenderingContext2D* getContext(const String&, const CanvasContextCreationAttributes&); ImageBitmap* transferToImageBitmap(ExceptionState&); IntSize size() const { return m_size; } - OffscreenCanvasRenderingContext2D* renderingContext() const; void setAssociatedCanvas(HTMLCanvasElement* canvas) { m_canvas = canvas; } HTMLCanvasElement* getAssociatedCanvas() const { return m_canvas; } + CanvasRenderingContext* getCanvasRenderingContext(const String&, const CanvasContextCreationAttributes&); - static void registerRenderingContextFactory(PassOwnPtr<OffscreenCanvasRenderingContextFactory>); + static void registerRenderingContextFactory(PassOwnPtr<CanvasRenderingContextFactory>); DECLARE_VIRTUAL_TRACE(); private: OffscreenCanvas(const IntSize&); - using ContextFactoryVector = Vector<OwnPtr<OffscreenCanvasRenderingContextFactory>>; + using ContextFactoryVector = Vector<OwnPtr<CanvasRenderingContextFactory>>; static ContextFactoryVector& renderingContextFactories(); - static OffscreenCanvasRenderingContextFactory* getRenderingContextFactory(int); + static CanvasRenderingContextFactory* getRenderingContextFactory(int); - Member<OffscreenCanvasRenderingContext> m_context; + Member<CanvasRenderingContext> m_context; WeakMember<HTMLCanvasElement> m_canvas; IntSize m_size; };
diff --git a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvas.idl b/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.idl similarity index 61% rename from third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvas.idl rename to third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.idl index 1896a52..f68357e5 100644 --- a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvas.idl +++ b/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.idl
@@ -2,10 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// Note: If there're more context types implemented, they should be added here -// to form a union type of OffscreenCanvasRenderingContext -typedef OffscreenCanvasRenderingContext2D OffscreenRenderingContext; - [ Constructor([EnforceRange] unsigned long width, [EnforceRange] unsigned long height), Exposed=(Window,Worker), @@ -14,6 +10,5 @@ [EnforceRange] attribute unsigned long width; [EnforceRange] attribute unsigned long height; - OffscreenRenderingContext? getContext(DOMString contextId, optional CanvasContextCreationAttributes attributes); [RaisesException] ImageBitmap transferToImageBitmap(); };
diff --git a/third_party/WebKit/Source/core/page/NetworkStateNotifierTest.cpp b/third_party/WebKit/Source/core/page/NetworkStateNotifierTest.cpp index 7fd924e..2a6f271 100644 --- a/third_party/WebKit/Source/core/page/NetworkStateNotifierTest.cpp +++ b/third_party/WebKit/Source/core/page/NetworkStateNotifierTest.cpp
@@ -82,7 +82,7 @@ void setNotificationCallback(PassOwnPtr<SameThreadClosure> closure) { - m_closure = closure; + m_closure = std::move(closure); } private:
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp index d8ac4746..1d2f4e4 100644 --- a/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp +++ b/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp
@@ -46,12 +46,12 @@ ScrollState* ScrollState::create(PassOwnPtr<ScrollStateData> data) { - ScrollState* scrollState = new ScrollState(data); + ScrollState* scrollState = new ScrollState(std::move(data)); return scrollState; } ScrollState::ScrollState(PassOwnPtr<ScrollStateData> data) - : m_data(data) + : m_data(std::move(data)) { }
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp index ae3ef656..e83aa28 100644 --- a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp +++ b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -322,7 +322,7 @@ WebScrollbarLayer* ScrollingCoordinator::addWebScrollbarLayer(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, PassOwnPtr<WebScrollbarLayer> scrollbarLayer) { ScrollbarMap& scrollbars = orientation == HorizontalScrollbar ? m_horizontalScrollbars : m_verticalScrollbars; - return scrollbars.add(scrollableArea, scrollbarLayer).storedValue->value.get(); + return scrollbars.add(scrollableArea, std::move(scrollbarLayer)).storedValue->value.get(); } WebScrollbarLayer* ScrollingCoordinator::getWebScrollbarLayer(ScrollableArea* scrollableArea, ScrollbarOrientation orientation)
diff --git a/third_party/WebKit/Source/core/paint/ObjectPaintProperties.h b/third_party/WebKit/Source/core/paint/ObjectPaintProperties.h index 2977ae8..5d2afa4 100644 --- a/third_party/WebKit/Source/core/paint/ObjectPaintProperties.h +++ b/third_party/WebKit/Source/core/paint/ObjectPaintProperties.h
@@ -96,7 +96,7 @@ m_scrollTranslation = translation; } void setScrollbarPaintOffset(PassRefPtr<TransformPaintPropertyNode> paintOffset) { m_scrollbarPaintOffset = paintOffset; } - void setLocalBorderBoxProperties(PassOwnPtr<LocalBorderBoxProperties> properties) { m_localBorderBoxProperties = properties; } + void setLocalBorderBoxProperties(PassOwnPtr<LocalBorderBoxProperties> properties) { m_localBorderBoxProperties = std::move(properties); } RefPtr<TransformPaintPropertyNode> m_paintOffsetTranslation; RefPtr<TransformPaintPropertyNode> m_transform;
diff --git a/third_party/WebKit/Source/core/streams/ReadableStream.cpp b/third_party/WebKit/Source/core/streams/ReadableStream.cpp index 3bb77be..9f907f1 100644 --- a/third_party/WebKit/Source/core/streams/ReadableStream.cpp +++ b/third_party/WebKit/Source/core/streams/ReadableStream.cpp
@@ -9,7 +9,6 @@ #include "bindings/core/v8/ScriptPromiseResolver.h" #include "bindings/core/v8/V8Binding.h" #include "core/dom/DOMException.h" -#include "core/dom/ExceptionCode.h" #include "core/streams/ReadableStreamReader.h" #include "core/streams/UnderlyingSource.h"
diff --git a/third_party/WebKit/Source/core/style/ContentData.cpp b/third_party/WebKit/Source/core/style/ContentData.cpp index 75ae859..7689ff27 100644 --- a/third_party/WebKit/Source/core/style/ContentData.cpp +++ b/third_party/WebKit/Source/core/style/ContentData.cpp
@@ -43,7 +43,7 @@ ContentData* ContentData::create(PassOwnPtr<CounterContent> counter) { - return new CounterContentData(counter); + return new CounterContentData(std::move(counter)); } ContentData* ContentData::create(QuoteType quote)
diff --git a/third_party/WebKit/Source/core/style/ContentData.h b/third_party/WebKit/Source/core/style/ContentData.h index 4bd1781..2d8d007 100644 --- a/third_party/WebKit/Source/core/style/ContentData.h +++ b/third_party/WebKit/Source/core/style/ContentData.h
@@ -140,14 +140,14 @@ friend class ContentData; public: const CounterContent* counter() const { return m_counter.get(); } - void setCounter(PassOwnPtr<CounterContent> counter) { m_counter = counter; } + void setCounter(PassOwnPtr<CounterContent> counter) { m_counter = std::move(counter); } bool isCounter() const override { return true; } LayoutObject* createLayoutObject(Document&, ComputedStyle&) const override; private: CounterContentData(PassOwnPtr<CounterContent> counter) - : m_counter(counter) + : m_counter(std::move(counter)) { }
diff --git a/third_party/WebKit/Source/core/style/StylePath.cpp b/third_party/WebKit/Source/core/style/StylePath.cpp index 6ef3008c2..397bc12 100644 --- a/third_party/WebKit/Source/core/style/StylePath.cpp +++ b/third_party/WebKit/Source/core/style/StylePath.cpp
@@ -12,7 +12,7 @@ namespace blink { StylePath::StylePath(PassOwnPtr<SVGPathByteStream> pathByteStream) - : m_byteStream(pathByteStream) + : m_byteStream(std::move(pathByteStream)) , m_pathLength(std::numeric_limits<float>::quiet_NaN()) { ASSERT(m_byteStream); @@ -24,7 +24,7 @@ PassRefPtr<StylePath> StylePath::create(PassOwnPtr<SVGPathByteStream> pathByteStream) { - return adoptRef(new StylePath(pathByteStream)); + return adoptRef(new StylePath(std::move(pathByteStream))); } StylePath* StylePath::emptyPath()
diff --git a/third_party/WebKit/Source/core/svg/SVGAnimatedHref.cpp b/third_party/WebKit/Source/core/svg/SVGAnimatedHref.cpp index 9952ea5..09adda5 100644 --- a/third_party/WebKit/Source/core/svg/SVGAnimatedHref.cpp +++ b/third_party/WebKit/Source/core/svg/SVGAnimatedHref.cpp
@@ -64,8 +64,7 @@ String SVGAnimatedHref::animVal() { UseCounter::count(contextElement()->document(), UseCounter::SVGHrefAnimVal); - // We should only animate (non-XLink) 'href'. - return SVGAnimatedString::animVal(); + return backingString()->SVGAnimatedString::animVal(); } SVGAnimatedString* SVGAnimatedHref::backingString()
diff --git a/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp b/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp index ac20bc7..c1ac416 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp
@@ -5,7 +5,6 @@ #include "core/timing/PerformanceObserver.h" #include "bindings/core/v8/ExceptionState.h" -#include "core/dom/ExceptionCode.h" #include "core/dom/ExecutionContext.h" #include "core/timing/PerformanceBase.h" #include "core/timing/PerformanceEntry.h"
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp b/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp index 4d4da4f..ca72ac3 100644 --- a/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp
@@ -54,7 +54,7 @@ } DedicatedWorkerGlobalScope::DedicatedWorkerGlobalScope(const KURL& url, const String& userAgent, DedicatedWorkerThread* thread, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilegeData, WorkerClients* workerClients) - : WorkerGlobalScope(url, userAgent, thread, timeOrigin, starterOriginPrivilegeData, workerClients) + : WorkerGlobalScope(url, userAgent, thread, timeOrigin, std::move(starterOriginPrivilegeData), workerClients) { }
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp b/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp index 9a9ff85..896d18da 100644 --- a/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp +++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp
@@ -56,7 +56,7 @@ WorkerGlobalScope* DedicatedWorkerThread::createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData) { - return DedicatedWorkerGlobalScope::create(this, startupData, m_timeOrigin); + return DedicatedWorkerGlobalScope::create(this, std::move(startupData), m_timeOrigin); } void DedicatedWorkerThread::postInitialize()
diff --git a/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp b/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp index 4847223..64a3f0a 100644 --- a/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp +++ b/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp
@@ -59,7 +59,7 @@ void processMessageOnWorkerGlobalScope(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels, InProcessWorkerObjectProxy* workerObjectProxy, ExecutionContext* scriptContext) { WorkerGlobalScope* globalScope = toWorkerGlobalScope(scriptContext); - MessagePortArray* ports = MessagePort::entanglePorts(*scriptContext, channels); + MessagePortArray* ports = MessagePort::entanglePorts(*scriptContext, std::move(channels)); globalScope->dispatchEvent(MessageEvent::create(ports, message)); workerObjectProxy->confirmMessageFromWorkerObject(V8GCController::hasPendingActivity(globalScope->thread()->isolate(), scriptContext)); } @@ -121,7 +121,7 @@ if (!m_workerObject || m_askedToTerminate) return; - MessagePortArray* ports = MessagePort::entanglePorts(*m_executionContext.get(), channels); + MessagePortArray* ports = MessagePort::entanglePorts(*m_executionContext.get(), std::move(channels)); m_workerObject->dispatchEvent(MessageEvent::create(ports, message)); } @@ -130,7 +130,7 @@ if (m_askedToTerminate) return; - OwnPtr<ExecutionContextTask> task = createCrossThreadTask(&processMessageOnWorkerGlobalScope, message, channels, AllowCrossThreadAccess(&workerObjectProxy())); + OwnPtr<ExecutionContextTask> task = createCrossThreadTask(&processMessageOnWorkerGlobalScope, message, passed(std::move(channels)), AllowCrossThreadAccess(&workerObjectProxy())); if (m_workerThread) { ++m_unconfirmedMessageCount; m_workerThread->postTask(BLINK_FROM_HERE, task.release()); @@ -145,7 +145,7 @@ return false; DCHECK(m_workerThread); - m_workerThread->postTask(BLINK_FROM_HERE, task); + m_workerThread->postTask(BLINK_FROM_HERE, std::move(task)); return true; } @@ -153,7 +153,7 @@ { // FIXME: In case of nested workers, this should go directly to the root Document context. DCHECK(m_executionContext->isDocument()); - m_executionContext->postTask(BLINK_FROM_HERE, task); + m_executionContext->postTask(BLINK_FROM_HERE, std::move(task)); } void InProcessWorkerMessagingProxy::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, int exceptionId)
diff --git a/third_party/WebKit/Source/core/workers/InProcessWorkerObjectProxy.cpp b/third_party/WebKit/Source/core/workers/InProcessWorkerObjectProxy.cpp index d8f61e1..7d6fb943 100644 --- a/third_party/WebKit/Source/core/workers/InProcessWorkerObjectProxy.cpp +++ b/third_party/WebKit/Source/core/workers/InProcessWorkerObjectProxy.cpp
@@ -48,12 +48,12 @@ void InProcessWorkerObjectProxy::postMessageToWorkerObject(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels) { - getExecutionContext()->postTask(BLINK_FROM_HERE, createCrossThreadTask(&InProcessWorkerMessagingProxy::postMessageToWorkerObject, m_messagingProxy, message, channels)); + getExecutionContext()->postTask(BLINK_FROM_HERE, createCrossThreadTask(&InProcessWorkerMessagingProxy::postMessageToWorkerObject, m_messagingProxy, message, passed(std::move(channels)))); } void InProcessWorkerObjectProxy::postTaskToMainExecutionContext(PassOwnPtr<ExecutionContextTask> task) { - getExecutionContext()->postTask(BLINK_FROM_HERE, task); + getExecutionContext()->postTask(BLINK_FROM_HERE, std::move(task)); } void InProcessWorkerObjectProxy::confirmMessageFromWorkerObject(bool hasPendingActivity)
diff --git a/third_party/WebKit/Source/core/workers/SharedWorker.cpp b/third_party/WebKit/Source/core/workers/SharedWorker.cpp index b0004f3c7..5b5d0bf 100644 --- a/third_party/WebKit/Source/core/workers/SharedWorker.cpp +++ b/third_party/WebKit/Source/core/workers/SharedWorker.cpp
@@ -32,7 +32,6 @@ #include "core/workers/SharedWorker.h" #include "bindings/core/v8/ExceptionState.h" -#include "core/dom/ExceptionCode.h" #include "core/dom/ExecutionContext.h" #include "core/dom/MessageChannel.h" #include "core/dom/MessagePort.h"
diff --git a/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp b/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp index 57b8d4b..5c09b8e 100644 --- a/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp
@@ -59,7 +59,7 @@ } SharedWorkerGlobalScope::SharedWorkerGlobalScope(const String& name, const KURL& url, const String& userAgent, SharedWorkerThread* thread, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilegeData, WorkerClients* workerClients) - : WorkerGlobalScope(url, userAgent, thread, monotonicallyIncreasingTime(), starterOriginPrivilegeData, workerClients) + : WorkerGlobalScope(url, userAgent, thread, monotonicallyIncreasingTime(), std::move(starterOriginPrivilegeData), workerClients) , m_name(name) { }
diff --git a/third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp b/third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp index e4c062c..14c6875f 100644 --- a/third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp +++ b/third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp
@@ -54,7 +54,7 @@ WorkerGlobalScope* SharedWorkerThread::createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData) { - return SharedWorkerGlobalScope::create(m_name, this, startupData); + return SharedWorkerGlobalScope::create(m_name, this, std::move(startupData)); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp index 467c0c0..b4c3334 100644 --- a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp
@@ -87,7 +87,7 @@ { setSecurityOrigin(SecurityOrigin::create(url)); if (starterOriginPrivilageData) - getSecurityOrigin()->transferPrivilegesFrom(starterOriginPrivilageData); + getSecurityOrigin()->transferPrivilegesFrom(std::move(starterOriginPrivilageData)); if (m_workerClients) m_workerClients->reattachThread(); @@ -172,7 +172,7 @@ void WorkerGlobalScope::postTask(const WebTraceLocation& location, PassOwnPtr<ExecutionContextTask> task) { - thread()->postTask(location, task); + thread()->postTask(location, std::move(task)); } void WorkerGlobalScope::clearScript()
diff --git a/third_party/WebKit/Source/core/workers/WorkerLoaderProxy.cpp b/third_party/WebKit/Source/core/workers/WorkerLoaderProxy.cpp index aafee56..aec9ab2 100644 --- a/third_party/WebKit/Source/core/workers/WorkerLoaderProxy.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerLoaderProxy.cpp
@@ -31,7 +31,7 @@ if (!m_loaderProxyProvider) return; - m_loaderProxyProvider->postTaskToLoader(task); + m_loaderProxyProvider->postTaskToLoader(std::move(task)); } bool WorkerLoaderProxy::postTaskToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask> task) @@ -40,7 +40,7 @@ if (!m_loaderProxyProvider) return false; - return m_loaderProxyProvider->postTaskToWorkerGlobalScope(task); + return m_loaderProxyProvider->postTaskToWorkerGlobalScope(std::move(task)); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp index d020fe2..97c44c66 100644 --- a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp
@@ -86,8 +86,8 @@ void WorkerScriptLoader::loadAsynchronously(ExecutionContext& executionContext, const KURL& url, CrossOriginRequestPolicy crossOriginRequestPolicy, WebAddressSpace creationAddressSpace, PassOwnPtr<SameThreadClosure> responseCallback, PassOwnPtr<SameThreadClosure> finishedCallback) { DCHECK(responseCallback || finishedCallback); - m_responseCallback = responseCallback; - m_finishedCallback = finishedCallback; + m_responseCallback = std::move(responseCallback); + m_finishedCallback = std::move(finishedCallback); m_url = url; ResourceRequest request(createResourceRequest(creationAddressSpace));
diff --git a/third_party/WebKit/Source/core/workers/WorkerThread.cpp b/third_party/WebKit/Source/core/workers/WorkerThread.cpp index 3c1725d..399a127 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThread.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerThread.cpp
@@ -126,7 +126,7 @@ DCHECK(isCurrentThread()); InspectorInstrumentation::asyncTaskScheduled(workerGlobalScope(), "Worker task", task.get()); } - return threadSafeBind(&WorkerThread::performTask, AllowCrossThreadAccess(this), task, isInstrumented); + return threadSafeBind(&WorkerThread::performTask, AllowCrossThreadAccess(this), passed(std::move(task)), isInstrumented); } WorkerThread::WorkerThread(PassRefPtr<WorkerLoaderProxy> workerLoaderProxy, WorkerReportingProxy& workerReportingProxy) @@ -166,7 +166,7 @@ return; m_started = true; - workerBackingThread().backingThread().postTask(BLINK_FROM_HERE, threadSafeBind(&WorkerThread::initialize, AllowCrossThreadAccess(this), startupData)); + workerBackingThread().backingThread().postTask(BLINK_FROM_HERE, threadSafeBind(&WorkerThread::initialize, AllowCrossThreadAccess(this), passed(std::move(startupData)))); } PlatformThreadId WorkerThread::platformThreadId() @@ -207,7 +207,7 @@ // Optimize for memory usage instead of latency for the worker isolate. isolate()->IsolateInBackgroundNotification(); - m_workerGlobalScope = createWorkerGlobalScope(startupData); + m_workerGlobalScope = createWorkerGlobalScope(std::move(startupData)); m_workerGlobalScope->scriptLoaded(sourceCode.length(), cachedMetaData.get() ? cachedMetaData->size() : 0); // Notify proxy that a new WorkerGlobalScope has been created and started. @@ -375,7 +375,7 @@ void WorkerThread::postTask(const WebTraceLocation& location, PassOwnPtr<ExecutionContextTask> task) { - workerBackingThread().backingThread().postTask(location, createWorkerThreadTask(task, true)); + workerBackingThread().backingThread().postTask(location, createWorkerThreadTask(std::move(task), true)); } void WorkerThread::runDebuggerTaskDontWait() @@ -392,7 +392,7 @@ if (m_shutdown) return; } - m_inspectorTaskRunner->appendTask(threadSafeBind(&WorkerThread::runDebuggerTask, AllowCrossThreadAccess(this), task)); + m_inspectorTaskRunner->appendTask(threadSafeBind(&WorkerThread::runDebuggerTask, AllowCrossThreadAccess(this), passed(std::move(task)))); { MutexLocker lock(m_threadStateMutex); if (isolate())
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp index 8e21d8a..5b23337 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp
@@ -34,11 +34,11 @@ namespace blink { -WorkerThreadStartupData::WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode startMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin* starterOrigin, WorkerClients* workerClients, WebAddressSpace addressSpace, V8CacheOptions v8CacheOptions) +WorkerThreadStartupData::WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode startMode, PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin* starterOrigin, WorkerClients* workerClients, WebAddressSpace addressSpace, V8CacheOptions v8CacheOptions) : m_scriptURL(scriptURL.copy()) , m_userAgent(userAgent.isolatedCopy()) , m_sourceCode(sourceCode.isolatedCopy()) - , m_cachedMetaData(cachedMetaData) + , m_cachedMetaData(std::move(cachedMetaData)) , m_startMode(startMode) , m_starterOriginPrivilegeData(starterOrigin ? starterOrigin->createPrivilegeData() : nullptr) , m_workerClients(workerClients)
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h index 48a4ed9..cc3501f 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h +++ b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h
@@ -50,9 +50,9 @@ WTF_MAKE_NONCOPYABLE(WorkerThreadStartupData); USING_FAST_MALLOC(WorkerThreadStartupData); public: - static PassOwnPtr<WorkerThreadStartupData> create(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode startMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin* starterOrigin, WorkerClients* workerClients, WebAddressSpace addressSpace, V8CacheOptions v8CacheOptions = V8CacheOptionsDefault) + static PassOwnPtr<WorkerThreadStartupData> create(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode startMode, PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin* starterOrigin, WorkerClients* workerClients, WebAddressSpace addressSpace, V8CacheOptions v8CacheOptions = V8CacheOptionsDefault) { - return adoptPtr(new WorkerThreadStartupData(scriptURL, userAgent, sourceCode, cachedMetaData, startMode, contentSecurityPolicyHeaders, starterOrigin, workerClients, addressSpace, v8CacheOptions)); + return adoptPtr(new WorkerThreadStartupData(scriptURL, userAgent, sourceCode, std::move(cachedMetaData), startMode, std::move(contentSecurityPolicyHeaders), starterOrigin, workerClients, addressSpace, v8CacheOptions)); } ~WorkerThreadStartupData(); @@ -91,7 +91,7 @@ V8CacheOptions m_v8CacheOptions; private: - WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin*, WorkerClients*, WebAddressSpace, V8CacheOptions); + WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode, PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin*, WorkerClients*, WebAddressSpace, V8CacheOptions); }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h b/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h index 43c0824..923ed2a 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h +++ b/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h
@@ -127,7 +127,7 @@ class FakeWorkerGlobalScope : public WorkerGlobalScope { public: FakeWorkerGlobalScope(const KURL& url, const String& userAgent, WorkerThreadForTest* thread, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilegeData, WorkerClients* workerClients) - : WorkerGlobalScope(url, userAgent, thread, monotonicallyIncreasingTime(), starterOriginPrivilegeData, workerClients) + : WorkerGlobalScope(url, userAgent, thread, monotonicallyIncreasingTime(), std::move(starterOriginPrivilegeData), workerClients) , m_thread(thread) { }
diff --git a/third_party/WebKit/Source/core/xml/DOMParser.cpp b/third_party/WebKit/Source/core/xml/DOMParser.cpp index 06b124b..1ed6d4fd 100644 --- a/third_party/WebKit/Source/core/xml/DOMParser.cpp +++ b/third_party/WebKit/Source/core/xml/DOMParser.cpp
@@ -19,7 +19,6 @@ #include "core/xml/DOMParser.h" #include "core/dom/DOMImplementation.h" -#include "core/dom/ExceptionCode.h" #include "wtf/text/WTFString.h" namespace blink {
diff --git a/third_party/WebKit/Source/modules/ModulesInitializer.cpp b/third_party/WebKit/Source/modules/ModulesInitializer.cpp index c20f0b0..1569bbb 100644 --- a/third_party/WebKit/Source/modules/ModulesInitializer.cpp +++ b/third_party/WebKit/Source/modules/ModulesInitializer.cpp
@@ -8,6 +8,7 @@ #include "core/EventTypeNames.h" #include "core/dom/Document.h" #include "core/html/HTMLCanvasElement.h" +#include "core/offscreencanvas/OffscreenCanvas.h" #include "modules/EventModulesFactory.h" #include "modules/EventModulesNames.h" #include "modules/EventTargetModulesNames.h" @@ -17,7 +18,6 @@ #include "modules/compositorworker/CompositorWorkerThread.h" #include "modules/filesystem/DraggedIsolatedFileSystemImpl.h" #include "modules/imagebitmap/ImageBitmapRenderingContext.h" -#include "modules/offscreencanvas/OffscreenCanvas.h" #include "modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.h" #include "modules/webdatabase/DatabaseManager.h" #include "modules/webgl/WebGL2RenderingContext.h"
diff --git a/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.cpp b/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.cpp index 138f07b..7806207 100644 --- a/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.cpp +++ b/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.cpp
@@ -346,10 +346,10 @@ } name->setSources(nameSourceProperties.release()); } - nodeObject->setProperties(properties); + nodeObject->setProperties(std::move(properties)); nodeObject->setName(name.release()); } else { - nodeObject->setProperties(properties); + nodeObject->setProperties(std::move(properties)); } fillCoreProperties(axObject, nodeObject.get());
diff --git a/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp b/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp index d864c6b..d3e2958 100644 --- a/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp +++ b/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp
@@ -16,7 +16,7 @@ PassOwnPtr<AXProperty> createProperty(const String& name, PassOwnPtr<AXValue> value) { - return AXProperty::create().setName(name).setValue(value).build(); + return AXProperty::create().setName(name).setValue(std::move(value)).build(); } String ignoredReasonName(AXIgnoredReason reason)
diff --git a/third_party/WebKit/Source/modules/bluetooth/BluetoothDevice.cpp b/third_party/WebKit/Source/modules/bluetooth/BluetoothDevice.cpp index 3bbcb1a..f5e3f8a3 100644 --- a/third_party/WebKit/Source/modules/bluetooth/BluetoothDevice.cpp +++ b/third_party/WebKit/Source/modules/bluetooth/BluetoothDevice.cpp
@@ -8,7 +8,6 @@ #include "bindings/core/v8/ScriptPromise.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "core/dom/DOMException.h" -#include "core/dom/ExceptionCode.h" #include "core/events/Event.h" #include "modules/bluetooth/BluetoothError.h" #include "modules/bluetooth/BluetoothRemoteGATTServer.h" @@ -19,7 +18,7 @@ BluetoothDevice::BluetoothDevice(ExecutionContext* context, PassOwnPtr<WebBluetoothDevice> webDevice) : ActiveDOMObject(context) - , m_webDevice(webDevice) + , m_webDevice(std::move(webDevice)) , m_adData(BluetoothAdvertisingData::create(m_webDevice->txPower, m_webDevice->rssi)) , m_gatt(BluetoothRemoteGATTServer::create(this)) { @@ -30,7 +29,7 @@ BluetoothDevice* BluetoothDevice::take(ScriptPromiseResolver* resolver, PassOwnPtr<WebBluetoothDevice> webDevice) { ASSERT(webDevice); - BluetoothDevice* device = new BluetoothDevice(resolver->getExecutionContext(), webDevice); + BluetoothDevice* device = new BluetoothDevice(resolver->getExecutionContext(), std::move(webDevice)); device->suspendIfNeeded(); return device; }
diff --git a/third_party/WebKit/Source/modules/bluetooth/BluetoothRemoteGATTCharacteristic.cpp b/third_party/WebKit/Source/modules/bluetooth/BluetoothRemoteGATTCharacteristic.cpp index f609ed47..921625d8 100644 --- a/third_party/WebKit/Source/modules/bluetooth/BluetoothRemoteGATTCharacteristic.cpp +++ b/third_party/WebKit/Source/modules/bluetooth/BluetoothRemoteGATTCharacteristic.cpp
@@ -31,7 +31,7 @@ BluetoothRemoteGATTCharacteristic::BluetoothRemoteGATTCharacteristic(ExecutionContext* context, PassOwnPtr<WebBluetoothRemoteGATTCharacteristicInit> webCharacteristic) : ActiveDOMObject(context) - , m_webCharacteristic(webCharacteristic) + , m_webCharacteristic(std::move(webCharacteristic)) , m_stopped(false) { m_properties = BluetoothCharacteristicProperties::create(m_webCharacteristic->characteristicProperties); @@ -44,7 +44,7 @@ if (!webCharacteristic) { return nullptr; } - BluetoothRemoteGATTCharacteristic* characteristic = new BluetoothRemoteGATTCharacteristic(resolver->getExecutionContext(), webCharacteristic); + BluetoothRemoteGATTCharacteristic* characteristic = new BluetoothRemoteGATTCharacteristic(resolver->getExecutionContext(), std::move(webCharacteristic)); // See note in ActiveDOMObject about suspendIfNeeded. characteristic->suspendIfNeeded(); return characteristic;
diff --git a/third_party/WebKit/Source/modules/bluetooth/BluetoothRemoteGATTService.cpp b/third_party/WebKit/Source/modules/bluetooth/BluetoothRemoteGATTService.cpp index 7216862..4292557 100644 --- a/third_party/WebKit/Source/modules/bluetooth/BluetoothRemoteGATTService.cpp +++ b/third_party/WebKit/Source/modules/bluetooth/BluetoothRemoteGATTService.cpp
@@ -18,7 +18,7 @@ namespace blink { BluetoothRemoteGATTService::BluetoothRemoteGATTService(PassOwnPtr<WebBluetoothRemoteGATTService> webService) - : m_webService(webService) + : m_webService(std::move(webService)) { } @@ -27,7 +27,7 @@ if (!webService) { return nullptr; } - return new BluetoothRemoteGATTService(webService); + return new BluetoothRemoteGATTService(std::move(webService)); } ScriptPromise BluetoothRemoteGATTService::getCharacteristic(ScriptState* scriptState,
diff --git a/third_party/WebKit/Source/modules/cachestorage/Cache.cpp b/third_party/WebKit/Source/modules/cachestorage/Cache.cpp index e1f85c3..e5fdd9e 100644 --- a/third_party/WebKit/Source/modules/cachestorage/Cache.cpp +++ b/third_party/WebKit/Source/modules/cachestorage/Cache.cpp
@@ -12,7 +12,6 @@ #include "bindings/core/v8/V8ThrowException.h" #include "bindings/modules/v8/V8Response.h" #include "core/dom/DOMException.h" -#include "core/dom/ExceptionCode.h" #include "core/inspector/ConsoleMessage.h" #include "modules/cachestorage/CacheStorageError.h" #include "modules/fetch/BodyStreamBuffer.h" @@ -363,7 +362,7 @@ Cache* Cache::create(GlobalFetch::ScopedFetcher* fetcher, PassOwnPtr<WebServiceWorkerCache> webCache) { - return new Cache(fetcher, webCache); + return new Cache(fetcher, std::move(webCache)); } ScriptPromise Cache::match(ScriptState* scriptState, const RequestInfo& request, const CacheQueryOptions& options, ExceptionState& exceptionState) @@ -475,7 +474,7 @@ Cache::Cache(GlobalFetch::ScopedFetcher* fetcher, PassOwnPtr<WebServiceWorkerCache> webCache) : m_scopedFetcher(fetcher) - , m_webCache(webCache) + , m_webCache(std::move(webCache)) { }
diff --git a/third_party/WebKit/Source/modules/cachestorage/CacheStorage.cpp b/third_party/WebKit/Source/modules/cachestorage/CacheStorage.cpp index 30b0e39..1945d68a3 100644 --- a/third_party/WebKit/Source/modules/cachestorage/CacheStorage.cpp +++ b/third_party/WebKit/Source/modules/cachestorage/CacheStorage.cpp
@@ -327,7 +327,7 @@ CacheStorage::CacheStorage(GlobalFetch::ScopedFetcher* fetcher, PassOwnPtr<WebServiceWorkerCacheStorage> webCacheStorage) : m_scopedFetcher(fetcher) - , m_webCacheStorage(webCacheStorage) + , m_webCacheStorage(std::move(webCacheStorage)) { }
diff --git a/third_party/WebKit/Source/modules/cachestorage/InspectorCacheStorageAgent.cpp b/third_party/WebKit/Source/modules/cachestorage/InspectorCacheStorageAgent.cpp index 547ad6b..03cec3f 100644 --- a/third_party/WebKit/Source/modules/cachestorage/InspectorCacheStorageAgent.cpp +++ b/third_party/WebKit/Source/modules/cachestorage/InspectorCacheStorageAgent.cpp
@@ -115,7 +115,7 @@ public: RequestCacheNames(const String& securityOrigin, PassOwnPtr<RequestCacheNamesCallback> callback) : m_securityOrigin(securityOrigin) - , m_callback(callback) + , m_callback(std::move(callback)) { } @@ -170,7 +170,7 @@ : m_params(params) , m_numResponsesLeft(numResponses) , m_responses(static_cast<size_t>(numResponses)) - , m_callback(callback) + , m_callback(std::move(callback)) { } @@ -252,8 +252,8 @@ public: GetCacheKeysForRequestData(const DataRequestParams& params, PassOwnPtr<WebServiceWorkerCache> cache, PassOwnPtr<RequestEntriesCallback> callback) : m_params(params) - , m_cache(cache) - , m_callback(callback) + , m_cache(std::move(cache)) + , m_callback(std::move(callback)) { } ~GetCacheKeysForRequestData() override { } @@ -293,7 +293,7 @@ public: GetCacheForRequestData(const DataRequestParams& params, PassOwnPtr<RequestEntriesCallback> callback) : m_params(params) - , m_callback(callback) + , m_callback(std::move(callback)) { } ~GetCacheForRequestData() override { } @@ -319,7 +319,7 @@ public: DeleteCache(PassOwnPtr<DeleteCacheCallback> callback) - : m_callback(callback) + : m_callback(std::move(callback)) { } ~DeleteCache() override { } @@ -343,7 +343,7 @@ public: DeleteCacheEntry(PassOwnPtr<DeleteEntryCallback> callback) - : m_callback(callback) + : m_callback(std::move(callback)) { } ~DeleteCacheEntry() override { } @@ -370,7 +370,7 @@ GetCacheForDeleteEntry(const String& requestSpec, const String& cacheName, PassOwnPtr<DeleteEntryCallback> callback) : m_requestSpec(requestSpec) , m_cacheName(cacheName) - , m_callback(callback) + , m_callback(std::move(callback)) { } ~GetCacheForDeleteEntry() override { } @@ -427,7 +427,7 @@ callback->sendFailure(*errorString); return; } - cache->dispatchKeys(new RequestCacheNames(securityOrigin, callback)); + cache->dispatchKeys(new RequestCacheNames(securityOrigin, std::move(callback))); } void InspectorCacheStorageAgent::requestEntries(ErrorString* errorString, const String& cacheId, int skipCount, int pageSize, PassOwnPtr<RequestEntriesCallback> callback) @@ -442,7 +442,7 @@ params.cacheName = cacheName; params.pageSize = pageSize; params.skipCount = skipCount; - cache->dispatchOpen(new GetCacheForRequestData(params, callback), WebString(cacheName)); + cache->dispatchOpen(new GetCacheForRequestData(params, std::move(callback)), WebString(cacheName)); } void InspectorCacheStorageAgent::deleteCache(ErrorString* errorString, const String& cacheId, PassOwnPtr<DeleteCacheCallback> callback) @@ -453,7 +453,7 @@ callback->sendFailure(*errorString); return; } - cache->dispatchDelete(new DeleteCache(callback), WebString(cacheName)); + cache->dispatchDelete(new DeleteCache(std::move(callback)), WebString(cacheName)); } void InspectorCacheStorageAgent::deleteEntry(ErrorString* errorString, const String& cacheId, const String& request, PassOwnPtr<DeleteEntryCallback> callback) @@ -464,7 +464,7 @@ callback->sendFailure(*errorString); return; } - cache->dispatchOpen(new GetCacheForDeleteEntry(request, cacheName, callback), WebString(cacheName)); + cache->dispatchOpen(new GetCacheForDeleteEntry(request, cacheName, std::move(callback)), WebString(cacheName)); }
diff --git a/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModule.cpp b/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModule.cpp index 7988132..2e312f3 100644 --- a/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModule.cpp +++ b/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModule.cpp
@@ -6,6 +6,7 @@ #include "core/html/canvas/CanvasContextCreationAttributes.h" #include "core/html/canvas/CanvasRenderingContext.h" +#include "core/offscreencanvas/OffscreenCanvas.h" namespace blink {
diff --git a/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModule.h b/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModule.h index 0364503..e37ceac 100644 --- a/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModule.h +++ b/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModule.h
@@ -7,7 +7,6 @@ #include "core/html/HTMLCanvasElement.h" #include "modules/ModulesExport.h" -#include "modules/offscreencanvas/OffscreenCanvas.h" #include "wtf/text/WTFString.h" namespace blink { @@ -15,6 +14,7 @@ class CanvasContextCreationAttributes; class HTMLCanvasElement; class ScriptState; +class OffscreenCanvas; class MODULES_EXPORT HTMLCanvasElementModule { STATIC_ONLY(HTMLCanvasElementModule);
diff --git a/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModuleTest.cpp b/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModuleTest.cpp index 1388183..4104257 100644 --- a/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModuleTest.cpp +++ b/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModuleTest.cpp
@@ -8,8 +8,8 @@ #include "core/html/HTMLCanvasElement.h" #include "core/html/HTMLDocument.h" #include "core/loader/EmptyClients.h" +#include "core/offscreencanvas/OffscreenCanvas.h" #include "core/testing/DummyPageHolder.h" -#include "modules/offscreencanvas/OffscreenCanvas.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink {
diff --git a/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.cpp b/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.cpp index 4c3f5f3..1044ed1 100644 --- a/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.cpp
@@ -839,7 +839,7 @@ dstRect->move(offset); } -static inline CanvasImageSource* toImageSourceInternal(const CanvasImageSourceUnion& value) +static inline CanvasImageSource* toImageSourceInternal(const CanvasImageSourceUnion& value, ExceptionState& exceptionState) { if (value.isHTMLImageElement()) return value.getAsHTMLImageElement(); @@ -847,15 +847,22 @@ return value.getAsHTMLVideoElement(); if (value.isHTMLCanvasElement()) return value.getAsHTMLCanvasElement(); - if (value.isImageBitmap()) + if (value.isImageBitmap()) { + if (static_cast<ImageBitmap*>(value.getAsImageBitmap())->isNeutered()) { + exceptionState.throwDOMException(InvalidStateError, String::format("The image source is neutered")); + return nullptr; + } return value.getAsImageBitmap(); + } ASSERT_NOT_REACHED(); return nullptr; } void BaseRenderingContext2D::drawImage(const CanvasImageSourceUnion& imageSource, double x, double y, ExceptionState& exceptionState) { - CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource); + CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource, exceptionState); + if (!imageSourceInternal) + return; FloatSize defaultObjectSize(width(), height()); FloatSize sourceRectSize = imageSourceInternal->elementSize(defaultObjectSize); FloatSize destRectSize = imageSourceInternal->defaultDestinationSize(defaultObjectSize); @@ -865,7 +872,9 @@ void BaseRenderingContext2D::drawImage(const CanvasImageSourceUnion& imageSource, double x, double y, double width, double height, ExceptionState& exceptionState) { - CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource); + CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource, exceptionState); + if (!imageSourceInternal) + return; FloatSize defaultObjectSize(this->width(), this->height()); FloatSize sourceRectSize = imageSourceInternal->elementSize(defaultObjectSize); drawImage(imageSourceInternal, 0, 0, sourceRectSize.width(), sourceRectSize.height(), x, y, width, height, exceptionState); @@ -875,7 +884,9 @@ double sx, double sy, double sw, double sh, double dx, double dy, double dw, double dh, ExceptionState& exceptionState) { - CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource); + CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource, exceptionState); + if (!imageSourceInternal) + return; drawImage(imageSourceInternal, sx, sy, sw, sh, dx, dy, dw, dh, exceptionState); } @@ -1085,7 +1096,9 @@ return nullptr; SourceImageStatus status; - CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource); + CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource, exceptionState); + if (!imageSourceInternal) + return nullptr; FloatSize defaultObjectSize(width(), height()); RefPtr<Image> imageForRendering = imageSourceInternal->getSourceImageForCanvas(&status, PreferNoAcceleration, SnapshotReasonCreatePattern, defaultObjectSize);
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.h b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.h index 46245ca..97af942a 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.h +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.h
@@ -78,7 +78,6 @@ return new CanvasRenderingContext2D(canvas, attrs, document); } CanvasRenderingContext::ContextType getContextType() const override { return CanvasRenderingContext::Context2d; } - void onError(HTMLCanvasElement*, const String& error) override { } }; ~CanvasRenderingContext2D() override;
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp index 3498359..38f958c 100644 --- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp
@@ -23,7 +23,7 @@ } CompositorWorkerGlobalScope::CompositorWorkerGlobalScope(const KURL& url, const String& userAgent, CompositorWorkerThread* thread, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilegeData, WorkerClients* workerClients) - : WorkerGlobalScope(url, userAgent, thread, timeOrigin, starterOriginPrivilegeData, workerClients) + : WorkerGlobalScope(url, userAgent, thread, timeOrigin, std::move(starterOriginPrivilegeData), workerClients) , m_callbackCollection(this) { }
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.cpp b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.cpp index 5fe50aa4..644de11 100644 --- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.cpp
@@ -68,7 +68,7 @@ WorkerGlobalScope*CompositorWorkerThread::createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("compositor-worker"), "CompositorWorkerThread::createWorkerGlobalScope"); - return CompositorWorkerGlobalScope::create(this, startupData, m_timeOrigin); + return CompositorWorkerGlobalScope::create(this, std::move(startupData), m_timeOrigin); } void CompositorWorkerThread::clearSharedBackingThread()
diff --git a/third_party/WebKit/Source/modules/credentialmanager/Credential.idl b/third_party/WebKit/Source/modules/credentialmanager/Credential.idl index 6cdb934d..3c48c1c 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/Credential.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/Credential.idl
@@ -2,16 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://w3c.github.io/webappsec/specs/credentialmanagement/#credential +// https://w3c.github.io/webappsec-credential-management/#credential [ RuntimeEnabled=CredentialManager, Exposed=Window ] interface Credential { - readonly attribute DOMString id; + readonly attribute USVString id; readonly attribute DOMString type; - - // TODO(mkwst): These should be on LocallyStoredCredential. - readonly attribute DOMString name; - readonly attribute DOMString iconURL; };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/CredentialsContainer.idl b/third_party/WebKit/Source/modules/credentialmanager/CredentialsContainer.idl index 80d59480..7e3cefe8 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/CredentialsContainer.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/CredentialsContainer.idl
@@ -5,7 +5,7 @@ [ RuntimeEnabled=CredentialManager, ] interface CredentialsContainer { - [CallWith=ScriptState, MeasureAs=CredentialManagerGet] Promise get(optional CredentialRequestOptions options); + [CallWith=ScriptState, MeasureAs=CredentialManagerGet] Promise get(CredentialRequestOptions options); [CallWith=ScriptState, MeasureAs=CredentialManagerStore] Promise store(Credential credential); [CallWith=ScriptState, MeasureAs=CredentialManagerRequireUserMediation] Promise requireUserMediation(); };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/FederatedCredential.cpp b/third_party/WebKit/Source/modules/credentialmanager/FederatedCredential.cpp index 50347a1..d3b159c 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/FederatedCredential.cpp +++ b/third_party/WebKit/Source/modules/credentialmanager/FederatedCredential.cpp
@@ -36,12 +36,12 @@ } FederatedCredential::FederatedCredential(WebFederatedCredential* webFederatedCredential) - : Credential(webFederatedCredential->getPlatformCredential()) + : SiteBoundCredential(webFederatedCredential->getPlatformCredential()) { } FederatedCredential::FederatedCredential(const String& id, const KURL& provider, const String& name, const KURL& icon) - : Credential(PlatformFederatedCredential::create(id, SecurityOrigin::create(provider), name, icon)) + : SiteBoundCredential(PlatformFederatedCredential::create(id, SecurityOrigin::create(provider), name, icon)) { }
diff --git a/third_party/WebKit/Source/modules/credentialmanager/FederatedCredential.h b/third_party/WebKit/Source/modules/credentialmanager/FederatedCredential.h index 403000a..63c99fd 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/FederatedCredential.h +++ b/third_party/WebKit/Source/modules/credentialmanager/FederatedCredential.h
@@ -8,7 +8,7 @@ #include "bindings/core/v8/ScriptWrappable.h" #include "bindings/core/v8/SerializedScriptValue.h" #include "modules/ModulesExport.h" -#include "modules/credentialmanager/Credential.h" +#include "modules/credentialmanager/SiteBoundCredential.h" #include "platform/heap/Handle.h" #include "platform/weborigin/KURL.h" @@ -17,7 +17,7 @@ class FederatedCredentialData; class WebFederatedCredential; -class MODULES_EXPORT FederatedCredential final : public Credential { +class MODULES_EXPORT FederatedCredential final : public SiteBoundCredential { DEFINE_WRAPPERTYPEINFO(); public: static FederatedCredential* create(const FederatedCredentialData&, ExceptionState&);
diff --git a/third_party/WebKit/Source/modules/credentialmanager/FederatedCredential.idl b/third_party/WebKit/Source/modules/credentialmanager/FederatedCredential.idl index f72009a6..e2bcc5e 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/FederatedCredential.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/FederatedCredential.idl
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://w3c.github.io/webappsec/specs/credentialmanagement/#federatedcredential +// https://w3c.github.io/webappsec-credential-management/#federatedcredential [ RuntimeEnabled=CredentialManager, RaisesException=Constructor, Constructor(FederatedCredentialData data), Exposed=Window -] interface FederatedCredential : Credential { +] interface FederatedCredential : SiteBoundCredential { readonly attribute USVString provider; // TODO(mkwst): We don't really support this yet; it always returns ''.
diff --git a/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.cpp b/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.cpp index 98392e0..913a2b9 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.cpp +++ b/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.cpp
@@ -105,14 +105,14 @@ } PasswordCredential::PasswordCredential(WebPasswordCredential* webPasswordCredential) - : Credential(webPasswordCredential->getPlatformCredential()) + : SiteBoundCredential(webPasswordCredential->getPlatformCredential()) , m_idName("username") , m_passwordName("password") { } PasswordCredential::PasswordCredential(const String& id, const String& password, const String& name, const KURL& icon) - : Credential(PlatformPasswordCredential::create(id, password, name, icon)) + : SiteBoundCredential(PlatformPasswordCredential::create(id, password, name, icon)) , m_idName("username") , m_passwordName("password") { @@ -167,7 +167,7 @@ DEFINE_TRACE(PasswordCredential) { - Credential::trace(visitor); + SiteBoundCredential::trace(visitor); visitor->trace(m_additionalData); }
diff --git a/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.h b/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.h index 9fc45a21..7603c49 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.h +++ b/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.h
@@ -9,7 +9,7 @@ #include "bindings/core/v8/SerializedScriptValue.h" #include "bindings/modules/v8/UnionTypesModules.h" #include "modules/ModulesExport.h" -#include "modules/credentialmanager/Credential.h" +#include "modules/credentialmanager/SiteBoundCredential.h" #include "platform/heap/Handle.h" #include "platform/network/EncodedFormData.h" #include "platform/weborigin/KURL.h" @@ -24,7 +24,7 @@ using CredentialPostBodyType = FormDataOrURLSearchParams; -class MODULES_EXPORT PasswordCredential final : public Credential { +class MODULES_EXPORT PasswordCredential final : public SiteBoundCredential { DEFINE_WRAPPERTYPEINFO(); public: static PasswordCredential* create(const PasswordCredentialData&, ExceptionState&);
diff --git a/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.idl b/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.idl index d4d44fc..f552210 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.idl
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// https://w3c.github.io/webappsec-credential-management/#passwordcredential + typedef (FormData or URLSearchParams) CredentialBodyType; [ @@ -10,7 +12,7 @@ Constructor(PasswordCredentialData data), Constructor(HTMLFormElement form), Exposed=Window, -] interface PasswordCredential : Credential { +] interface PasswordCredential : SiteBoundCredential { attribute USVString idName; attribute USVString passwordName; attribute CredentialBodyType? additionalData;
diff --git a/third_party/WebKit/Source/modules/credentialmanager/SiteBoundCredential.cpp b/third_party/WebKit/Source/modules/credentialmanager/SiteBoundCredential.cpp new file mode 100644 index 0000000..2bbbc4c --- /dev/null +++ b/third_party/WebKit/Source/modules/credentialmanager/SiteBoundCredential.cpp
@@ -0,0 +1,14 @@ +// 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 "modules/credentialmanager/SiteBoundCredential.h" + +namespace blink { + +SiteBoundCredential::SiteBoundCredential(PlatformCredential* platformCredential) + : Credential(platformCredential) +{ +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/credentialmanager/SiteBoundCredential.h b/third_party/WebKit/Source/modules/credentialmanager/SiteBoundCredential.h new file mode 100644 index 0000000..b1b8c210 --- /dev/null +++ b/third_party/WebKit/Source/modules/credentialmanager/SiteBoundCredential.h
@@ -0,0 +1,28 @@ +// 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 SiteBoundCredential_h +#define SiteBoundCredential_h + +#include "bindings/core/v8/ScriptWrappable.h" +#include "modules/ModulesExport.h" +#include "modules/credentialmanager/Credential.h" +#include "platform/heap/Handle.h" + +namespace blink { + +class MODULES_EXPORT SiteBoundCredential : public Credential { + DEFINE_WRAPPERTYPEINFO(); +public: + // SiteBoundCredential.idl + const String& name() const { return m_platformCredential->name(); } + const KURL& iconURL() const { return m_platformCredential->iconURL(); } + +protected: + SiteBoundCredential(PlatformCredential*); +}; + +} // namespace blink + +#endif // SiteBoundCredential_h
diff --git a/third_party/WebKit/Source/modules/credentialmanager/SiteBoundCredential.idl b/third_party/WebKit/Source/modules/credentialmanager/SiteBoundCredential.idl new file mode 100644 index 0000000..f716407 --- /dev/null +++ b/third_party/WebKit/Source/modules/credentialmanager/SiteBoundCredential.idl
@@ -0,0 +1,13 @@ +// 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. + +// https://w3c.github.io/webappsec-credential-management/#siteboundcredential + +[ + RuntimeEnabled=CredentialManager, + Exposed=Window +] interface SiteBoundCredential : Credential { + readonly attribute USVString name; + readonly attribute USVString iconURL; +};
diff --git a/third_party/WebKit/Source/modules/crypto/CryptoKey.cpp b/third_party/WebKit/Source/modules/crypto/CryptoKey.cpp index 83d07c2..b6a0009 100644 --- a/third_party/WebKit/Source/modules/crypto/CryptoKey.cpp +++ b/third_party/WebKit/Source/modules/crypto/CryptoKey.cpp
@@ -33,7 +33,6 @@ #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/V8ObjectBuilder.h" #include "bindings/core/v8/V8Uint8Array.h" -#include "core/dom/ExceptionCode.h" #include "platform/CryptoResult.h" #include "public/platform/WebCryptoAlgorithmParams.h" #include "public/platform/WebCryptoKeyAlgorithm.h"
diff --git a/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.cpp b/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.cpp index c9da7ab..3d887ec 100644 --- a/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.cpp +++ b/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.cpp
@@ -9,7 +9,7 @@ namespace blink { PaintRenderingContext2D::PaintRenderingContext2D(PassOwnPtr<ImageBuffer> imageBuffer) - : m_imageBuffer(imageBuffer) + : m_imageBuffer(std::move(imageBuffer)) { m_clipAntialiasing = AntiAliased; modifiableState().setShouldAntialias(true);
diff --git a/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.h b/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.h index 3fdd6f4..35a49cc 100644 --- a/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.h +++ b/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.h
@@ -23,7 +23,7 @@ public: static PaintRenderingContext2D* create(PassOwnPtr<ImageBuffer> imageBuffer) { - return new PaintRenderingContext2D(imageBuffer); + return new PaintRenderingContext2D(std::move(imageBuffer)); } // BaseRenderingContext2D
diff --git a/third_party/WebKit/Source/modules/encoding/TextDecoder.cpp b/third_party/WebKit/Source/modules/encoding/TextDecoder.cpp index d3f50fa..4d0ed176 100644 --- a/third_party/WebKit/Source/modules/encoding/TextDecoder.cpp +++ b/third_party/WebKit/Source/modules/encoding/TextDecoder.cpp
@@ -33,7 +33,6 @@ #include "bindings/core/v8/ExceptionState.h" #include "core/dom/DOMArrayBuffer.h" #include "core/dom/DOMArrayBufferView.h" -#include "core/dom/ExceptionCode.h" #include "modules/encoding/Encoding.h" #include "wtf/StringExtras.h" #include "wtf/text/TextEncodingRegistry.h"
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/HTMLMediaElementEncryptedMedia.cpp b/third_party/WebKit/Source/modules/encryptedmedia/HTMLMediaElementEncryptedMedia.cpp index e019f96..faf41cb 100644 --- a/third_party/WebKit/Source/modules/encryptedmedia/HTMLMediaElementEncryptedMedia.cpp +++ b/third_party/WebKit/Source/modules/encryptedmedia/HTMLMediaElementEncryptedMedia.cpp
@@ -60,8 +60,8 @@ class SetContentDecryptionModuleResult final : public ContentDecryptionModuleResult { public: SetContentDecryptionModuleResult(PassOwnPtr<SuccessCallback> success, PassOwnPtr<FailureCallback> failure) - : m_successCallback(success) - , m_failureCallback(failure) + : m_successCallback(std::move(success)) + , m_failureCallback(std::move(failure)) { }
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeySystemAccess.cpp b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeySystemAccess.cpp index e319ba3..c4712e4 100644 --- a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeySystemAccess.cpp +++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeySystemAccess.cpp
@@ -108,7 +108,7 @@ MediaKeySystemAccess::MediaKeySystemAccess(const String& keySystem, PassOwnPtr<WebContentDecryptionModuleAccess> access) : m_keySystem(keySystem) - , m_access(access) + , m_access(std::move(access)) { }
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeys.cpp b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeys.cpp index 540b4489..0620e002 100644 --- a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeys.cpp +++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeys.cpp
@@ -84,7 +84,7 @@ MediaKeys* MediaKeys::create(ExecutionContext* context, const WebVector<WebEncryptedMediaSessionType>& supportedSessionTypes, PassOwnPtr<WebContentDecryptionModule> cdm) { - MediaKeys* mediaKeys = new MediaKeys(context, supportedSessionTypes, cdm); + MediaKeys* mediaKeys = new MediaKeys(context, supportedSessionTypes, std::move(cdm)); mediaKeys->suspendIfNeeded(); return mediaKeys; } @@ -93,7 +93,7 @@ : ActiveScriptWrappable(this) , ActiveDOMObject(context) , m_supportedSessionTypes(supportedSessionTypes) - , m_cdm(cdm) + , m_cdm(std::move(cdm)) , m_mediaElement(nullptr) , m_reservedForMediaElement(false) , m_timer(this, &MediaKeys::timerFired)
diff --git a/third_party/WebKit/Source/modules/fetch/Body.cpp b/third_party/WebKit/Source/modules/fetch/Body.cpp index 670ea27b..6a00e27 100644 --- a/third_party/WebKit/Source/modules/fetch/Body.cpp +++ b/third_party/WebKit/Source/modules/fetch/Body.cpp
@@ -11,7 +11,6 @@ #include "bindings/core/v8/V8ThrowException.h" #include "core/dom/DOMArrayBuffer.h" #include "core/dom/DOMTypedArray.h" -#include "core/dom/ExceptionCode.h" #include "core/fileapi/Blob.h" #include "core/frame/UseCounter.h" #include "core/streams/ReadableStreamController.h"
diff --git a/third_party/WebKit/Source/modules/fetch/BodyStreamBuffer.cpp b/third_party/WebKit/Source/modules/fetch/BodyStreamBuffer.cpp index 6a4c58e..947d9d1 100644 --- a/third_party/WebKit/Source/modules/fetch/BodyStreamBuffer.cpp +++ b/third_party/WebKit/Source/modules/fetch/BodyStreamBuffer.cpp
@@ -74,7 +74,7 @@ }; BodyStreamBuffer::BodyStreamBuffer(PassOwnPtr<FetchDataConsumerHandle> handle) - : m_handle(handle) + : m_handle(std::move(handle)) , m_reader(m_handle->obtainReader(this)) , m_stream(new ReadableByteStream(this, new ReadableByteStream::StrictStrategy)) , m_streamNeedsMore(false)
diff --git a/third_party/WebKit/Source/modules/fetch/CompositeDataConsumerHandle.cpp b/third_party/WebKit/Source/modules/fetch/CompositeDataConsumerHandle.cpp index 01f5ef33..5679b7b 100644 --- a/third_party/WebKit/Source/modules/fetch/CompositeDataConsumerHandle.cpp +++ b/third_party/WebKit/Source/modules/fetch/CompositeDataConsumerHandle.cpp
@@ -32,7 +32,7 @@ class CompositeDataConsumerHandle::Context final : public ThreadSafeRefCounted<Context> { public: using Token = unsigned; - static PassRefPtr<Context> create(PassOwnPtr<WebDataConsumerHandle> handle) { return adoptRef(new Context(handle)); } + static PassRefPtr<Context> create(PassOwnPtr<WebDataConsumerHandle> handle) { return adoptRef(new Context(std::move(handle))); } ~Context() { ASSERT(!m_readerThread); @@ -67,7 +67,7 @@ void update(PassOwnPtr<WebDataConsumerHandle> handle) { MutexLocker locker(m_mutex); - m_handle = handle; + m_handle = std::move(handle); if (!m_readerThread) { // There is no reader. return; @@ -107,7 +107,7 @@ private: explicit Context(PassOwnPtr<WebDataConsumerHandle> handle) - : m_handle(handle) + : m_handle(std::move(handle)) , m_readerThread(nullptr) , m_client(nullptr) , m_token(0) @@ -196,11 +196,11 @@ { ASSERT(handle); ASSERT(m_thread->isCurrentThread()); - m_context->update(handle); + m_context->update(std::move(handle)); } CompositeDataConsumerHandle::CompositeDataConsumerHandle(PassOwnPtr<WebDataConsumerHandle> handle, Updater** updater) - : m_context(Context::create(handle)) + : m_context(Context::create(std::move(handle))) { *updater = new Updater(m_context); }
diff --git a/third_party/WebKit/Source/modules/fetch/CompositeDataConsumerHandle.h b/third_party/WebKit/Source/modules/fetch/CompositeDataConsumerHandle.h index 2a1a6fb..200797b 100644 --- a/third_party/WebKit/Source/modules/fetch/CompositeDataConsumerHandle.h +++ b/third_party/WebKit/Source/modules/fetch/CompositeDataConsumerHandle.h
@@ -50,9 +50,9 @@ { ASSERT(handle); Updater* u = nullptr; - auto p = adoptPtr(new CompositeDataConsumerHandle(handle, &u)); + OwnPtr<CompositeDataConsumerHandle> p = adoptPtr(new CompositeDataConsumerHandle(std::move(handle), &u)); *updater = u; - return p; + return p.release(); } ~CompositeDataConsumerHandle() override;
diff --git a/third_party/WebKit/Source/modules/fetch/CrossThreadHolder.h b/third_party/WebKit/Source/modules/fetch/CrossThreadHolder.h index be28fae..5610a74a 100644 --- a/third_party/WebKit/Source/modules/fetch/CrossThreadHolder.h +++ b/third_party/WebKit/Source/modules/fetch/CrossThreadHolder.h
@@ -36,7 +36,7 @@ static PassOwnPtr<CrossThreadHolder<T>> create(ExecutionContext* executionContext, PassOwnPtr<T> obj) { ASSERT(executionContext->isContextThread()); - return adoptPtr(new CrossThreadHolder(executionContext, obj)); + return adoptPtr(new CrossThreadHolder(executionContext, std::move(obj))); } // Can be called from any thread. @@ -53,7 +53,7 @@ // The bridge has already disappeared. return; } - m_bridge->getExecutionContext()->postTask(BLINK_FROM_HERE, createCrossThreadTask(&Bridge::runTask, m_bridge.get(), task)); + m_bridge->getExecutionContext()->postTask(BLINK_FROM_HERE, createCrossThreadTask(&Bridge::runTask, m_bridge.get(), passed(std::move(task)))); } ~CrossThreadHolder() @@ -95,7 +95,7 @@ public: Bridge(ExecutionContext* executionContext, PassOwnPtr<T> obj, PassRefPtr<MutexWrapper> mutex, CrossThreadHolder* holder) : ActiveDOMObject(executionContext) - , m_obj(obj) + , m_obj(std::move(obj)) , m_mutex(mutex) , m_holder(holder) { @@ -161,7 +161,7 @@ CrossThreadHolder(ExecutionContext* executionContext, PassOwnPtr<T> obj) : m_mutex(MutexWrapper::create()) - , m_bridge(new Bridge(executionContext, obj, m_mutex, this)) + , m_bridge(new Bridge(executionContext, std::move(obj), m_mutex, this)) { }
diff --git a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp index 9ad9ba5..03422e7c 100644 --- a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp +++ b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp
@@ -231,7 +231,7 @@ DataConsumerHandleTestUtil::HandleReader::HandleReader(PassOwnPtr<WebDataConsumerHandle> handle, PassOwnPtr<OnFinishedReading> onFinishedReading) : m_reader(handle->obtainReader(this)) - , m_onFinishedReading(onFinishedReading) + , m_onFinishedReading(std::move(onFinishedReading)) { } @@ -250,19 +250,19 @@ } OwnPtr<HandleReadResult> result = adoptPtr(new HandleReadResult(r, m_data)); m_data.clear(); - Platform::current()->currentThread()->getWebTaskRunner()->postTask(BLINK_FROM_HERE, bind(&HandleReader::runOnFinishedReading, this, result.release())); + Platform::current()->currentThread()->getWebTaskRunner()->postTask(BLINK_FROM_HERE, bind(&HandleReader::runOnFinishedReading, this, passed(result.release()))); m_reader = nullptr; } void DataConsumerHandleTestUtil::HandleReader::runOnFinishedReading(PassOwnPtr<HandleReadResult> result) { ASSERT(m_onFinishedReading); - (*m_onFinishedReading.release())(result); + (*m_onFinishedReading.release())(std::move(result)); } DataConsumerHandleTestUtil::HandleTwoPhaseReader::HandleTwoPhaseReader(PassOwnPtr<WebDataConsumerHandle> handle, PassOwnPtr<OnFinishedReading> onFinishedReading) : m_reader(handle->obtainReader(this)) - , m_onFinishedReading(onFinishedReading) + , m_onFinishedReading(std::move(onFinishedReading)) { } @@ -284,14 +284,14 @@ } OwnPtr<HandleReadResult> result = adoptPtr(new HandleReadResult(r, m_data)); m_data.clear(); - Platform::current()->currentThread()->getWebTaskRunner()->postTask(BLINK_FROM_HERE, bind(&HandleTwoPhaseReader::runOnFinishedReading, this, result.release())); + Platform::current()->currentThread()->getWebTaskRunner()->postTask(BLINK_FROM_HERE, bind(&HandleTwoPhaseReader::runOnFinishedReading, this, passed(result.release()))); m_reader = nullptr; } void DataConsumerHandleTestUtil::HandleTwoPhaseReader::runOnFinishedReading(PassOwnPtr<HandleReadResult> result) { ASSERT(m_onFinishedReading); - (*m_onFinishedReading.release())(result); + (*m_onFinishedReading.release())(std::move(result)); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.h b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.h index 45cf589..24a43ce 100644 --- a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.h +++ b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.h
@@ -119,13 +119,13 @@ { MutexLocker locker(m_holderMutex); ASSERT(m_holder); - m_holder->readingThread()->postTask(location, task); + m_holder->readingThread()->postTask(location, std::move(task)); } void postTaskToUpdatingThread(const WebTraceLocation& location, PassOwnPtr<CrossThreadClosure> task) { MutexLocker locker(m_holderMutex); ASSERT(m_holder); - m_holder->updatingThread()->postTask(location, task); + m_holder->updatingThread()->postTask(location, std::move(task)); } private: @@ -220,20 +220,20 @@ const String& result() { return m_context->result(); } void postTaskToReadingThread(const WebTraceLocation& location, PassOwnPtr<CrossThreadClosure> task) { - m_context->postTaskToReadingThread(location, task); + m_context->postTaskToReadingThread(location, std::move(task)); } void postTaskToUpdatingThread(const WebTraceLocation& location, PassOwnPtr<CrossThreadClosure> task) { - m_context->postTaskToUpdatingThread(location, task); + m_context->postTaskToUpdatingThread(location, std::move(task)); } void postTaskToReadingThreadAndWait(const WebTraceLocation& location, PassOwnPtr<CrossThreadClosure> task) { - postTaskToReadingThread(location, task); + postTaskToReadingThread(location, std::move(task)); m_waitableEvent->wait(); } void postTaskToUpdatingThreadAndWait(const WebTraceLocation& location, PassOwnPtr<CrossThreadClosure> task) { - postTaskToUpdatingThread(location, task); + postTaskToUpdatingThread(location, std::move(task)); m_waitableEvent->wait(); } protected: @@ -255,7 +255,7 @@ { ThreadHolder holder(this); m_waitableEvent = adoptPtr(new WaitableEvent()); - m_handle = handle; + m_handle = std::move(handle); postTaskToReadingThreadAndWait(BLINK_FROM_HERE, threadSafeBind(&Self::obtainReader, this)); } @@ -284,7 +284,7 @@ { ThreadHolder holder(this); m_waitableEvent = adoptPtr(new WaitableEvent()); - m_handle = handle; + m_handle = std::move(handle); postTaskToReadingThreadAndWait(BLINK_FROM_HERE, threadSafeBind(&Self::obtainReader, this)); } @@ -500,7 +500,7 @@ , m_event(adoptPtr(new WaitableEvent())) , m_isDone(false) { - m_thread->thread()->postTask(BLINK_FROM_HERE, threadSafeBind(&HandleReaderRunner::start, AllowCrossThreadAccess(this), handle)); + m_thread->thread()->postTask(BLINK_FROM_HERE, threadSafeBind(&HandleReaderRunner::start, AllowCrossThreadAccess(this), passed(std::move(handle)))); } ~HandleReaderRunner() { @@ -519,13 +519,13 @@ private: void start(PassOwnPtr<WebDataConsumerHandle> handle) { - m_handleReader = adoptPtr(new T(handle, bind<PassOwnPtr<HandleReadResult>>(&HandleReaderRunner::onFinished, this))); + m_handleReader = adoptPtr(new T(std::move(handle), bind<PassOwnPtr<HandleReadResult>>(&HandleReaderRunner::onFinished, this))); } void onFinished(PassOwnPtr<HandleReadResult> result) { m_handleReader = nullptr; - m_result = result; + m_result = std::move(result); m_event->signal(); }
diff --git a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleUtil.cpp b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleUtil.cpp index 688c95ac..34326a17 100644 --- a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleUtil.cpp +++ b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleUtil.cpp
@@ -71,11 +71,11 @@ class WebToFetchDataConsumerHandleAdapter : public FetchDataConsumerHandle { public: - WebToFetchDataConsumerHandleAdapter(PassOwnPtr<WebDataConsumerHandle> handle) : m_handle(handle) { } + WebToFetchDataConsumerHandleAdapter(PassOwnPtr<WebDataConsumerHandle> handle) : m_handle(std::move(handle)) { } private: class ReaderImpl final : public FetchDataConsumerHandle::Reader { public: - ReaderImpl(PassOwnPtr<WebDataConsumerHandle::Reader> reader) : m_reader(reader) { } + ReaderImpl(PassOwnPtr<WebDataConsumerHandle::Reader> reader) : m_reader(std::move(reader)) { } Result read(void* data, size_t size, Flags flags, size_t* readSize) override { return m_reader->read(data, size, flags, readSize); @@ -119,7 +119,7 @@ PassOwnPtr<FetchDataConsumerHandle> createFetchDataConsumerHandleFromWebHandle(PassOwnPtr<WebDataConsumerHandle> handle) { - return adoptPtr(new WebToFetchDataConsumerHandleAdapter(handle)); + return adoptPtr(new WebToFetchDataConsumerHandleAdapter(std::move(handle))); } NotifyOnReaderCreationHelper::NotifyOnReaderCreationHelper(WebDataConsumerHandle::Client* client)
diff --git a/third_party/WebKit/Source/modules/fetch/DataConsumerTee.cpp b/third_party/WebKit/Source/modules/fetch/DataConsumerTee.cpp index b72c4a6..14aae5a 100644 --- a/third_party/WebKit/Source/modules/fetch/DataConsumerTee.cpp +++ b/third_party/WebKit/Source/modules/fetch/DataConsumerTee.cpp
@@ -408,7 +408,7 @@ RefPtr<DestinationContext> context1 = DestinationContext::create(); RefPtr<DestinationContext> context2 = DestinationContext::create(); - root->initialize(new SourceContext(root, src, context1, context2, executionContext)); + root->initialize(new SourceContext(root, std::move(src), context1, context2, executionContext)); *dest1 = DestinationHandle::create(DestinationContext::Proxy::create(context1, tracker)); *dest2 = DestinationHandle::create(DestinationContext::Proxy::create(context2, tracker)); @@ -424,7 +424,7 @@ } OwnPtr<WebDataConsumerHandle> webDest1, webDest2; - DataConsumerTee::create(executionContext, static_cast<PassOwnPtr<WebDataConsumerHandle>>(src), &webDest1, &webDest2); + DataConsumerTee::create(executionContext, static_cast<PassOwnPtr<WebDataConsumerHandle>>(std::move(src)), &webDest1, &webDest2); *dest1 = createFetchDataConsumerHandleFromWebHandle(webDest1.release()); *dest2 = createFetchDataConsumerHandleFromWebHandle(webDest2.release()); return;
diff --git a/third_party/WebKit/Source/modules/fetch/DataConsumerTeeTest.cpp b/third_party/WebKit/Source/modules/fetch/DataConsumerTeeTest.cpp index 1f746d10..a0cfd18b 100644 --- a/third_party/WebKit/Source/modules/fetch/DataConsumerTeeTest.cpp +++ b/third_party/WebKit/Source/modules/fetch/DataConsumerTeeTest.cpp
@@ -57,7 +57,7 @@ { m_thread = adoptPtr(new Thread("src thread", Thread::WithExecutionContext)); m_waitableEvent = adoptPtr(new WaitableEvent()); - m_thread->thread()->postTask(BLINK_FROM_HERE, threadSafeBind(&TeeCreationThread<Handle>::runInternal, AllowCrossThreadAccess(this), src, AllowCrossThreadAccess(dest1), AllowCrossThreadAccess(dest2))); + m_thread->thread()->postTask(BLINK_FROM_HERE, threadSafeBind(&TeeCreationThread<Handle>::runInternal, AllowCrossThreadAccess(this), passed(std::move(src)), AllowCrossThreadAccess(dest1), AllowCrossThreadAccess(dest2))); m_waitableEvent->wait(); } @@ -66,7 +66,7 @@ private: void runInternal(PassOwnPtr<Handle> src, OwnPtr<Handle>* dest1, OwnPtr<Handle>* dest2) { - DataConsumerTee::create(m_thread->getExecutionContext(), src, dest1, dest2); + DataConsumerTee::create(m_thread->getExecutionContext(), std::move(src), dest1, dest2); m_waitableEvent->signal(); }
diff --git a/third_party/WebKit/Source/modules/fetch/FetchBlobDataConsumerHandle.cpp b/third_party/WebKit/Source/modules/fetch/FetchBlobDataConsumerHandle.cpp index ab08ead..92ced98d 100644 --- a/third_party/WebKit/Source/modules/fetch/FetchBlobDataConsumerHandle.cpp +++ b/third_party/WebKit/Source/modules/fetch/FetchBlobDataConsumerHandle.cpp
@@ -128,7 +128,7 @@ m_updater->update(createUnexpectedErrorDataConsumerHandle()); return; } - m_updater->update(handle); + m_updater->update(std::move(handle)); } void didFinishLoading(unsigned long, double) override @@ -182,7 +182,7 @@ public: ReaderImpl(Client* client, PassRefPtr<ReaderContext> readerContext, PassOwnPtr<WebDataConsumerHandle::Reader> reader) : m_readerContext(readerContext) - , m_reader(reader) + , m_reader(std::move(reader)) , m_notifier(client) { } ~ReaderImpl() override { }
diff --git a/third_party/WebKit/Source/modules/fetch/FetchFormDataConsumerHandleTest.cpp b/third_party/WebKit/Source/modules/fetch/FetchFormDataConsumerHandleTest.cpp index a55257e..e09a1ac6 100644 --- a/third_party/WebKit/Source/modules/fetch/FetchFormDataConsumerHandleTest.cpp +++ b/third_party/WebKit/Source/modules/fetch/FetchFormDataConsumerHandleTest.cpp
@@ -52,7 +52,7 @@ public: explicit LoaderFactory(PassOwnPtr<WebDataConsumerHandle> handle) : m_client(nullptr) - , m_handle(handle) {} + , m_handle(std::move(handle)) {} PassOwnPtr<ThreadableLoader> create(ExecutionContext&, ThreadableLoaderClient* client, const ThreadableLoaderOptions&, const ResourceLoaderOptions&) override { m_client = client;
diff --git a/third_party/WebKit/Source/modules/fetch/FetchManager.cpp b/third_party/WebKit/Source/modules/fetch/FetchManager.cpp index d50b163..a76543f 100644 --- a/third_party/WebKit/Source/modules/fetch/FetchManager.cpp +++ b/third_party/WebKit/Source/modules/fetch/FetchManager.cpp
@@ -10,7 +10,6 @@ #include "bindings/core/v8/V8ThrowException.h" #include "core/dom/DOMArrayBuffer.h" #include "core/dom/Document.h" -#include "core/dom/ExceptionCode.h" #include "core/fetch/FetchUtils.h" #include "core/fileapi/Blob.h" #include "core/frame/Frame.h" @@ -82,7 +81,7 @@ // |updater| must be garbage collected. The other arguments // all must have the lifetime of the give loader. SRIVerifier(PassOwnPtr<WebDataConsumerHandle> handle, CompositeDataConsumerHandle::Updater* updater, Response* response, FetchManager::Loader* loader, String integrityMetadata, const KURL& url) - : m_handle(handle) + : m_handle(std::move(handle)) , m_updater(updater) , m_response(response) , m_loader(loader) @@ -294,7 +293,7 @@ FetchResponseData* responseData = nullptr; CompositeDataConsumerHandle::Updater* updater = nullptr; if (m_request->integrity().isEmpty()) - responseData = FetchResponseData::createWithBuffer(new BodyStreamBuffer(createFetchDataConsumerHandleFromWebHandle(handle))); + responseData = FetchResponseData::createWithBuffer(new BodyStreamBuffer(createFetchDataConsumerHandleFromWebHandle(std::move(handle)))); else responseData = FetchResponseData::createWithBuffer(new BodyStreamBuffer(createFetchDataConsumerHandleFromWebHandle(CompositeDataConsumerHandle::create(createWaitingDataConsumerHandle(), &updater)))); responseData->setStatus(response.httpStatusCode()); @@ -358,7 +357,7 @@ m_resolver.clear(); } else { ASSERT(!m_integrityVerifier); - m_integrityVerifier = new SRIVerifier(handle, updater, r, this, m_request->integrity(), response.url()); + m_integrityVerifier = new SRIVerifier(std::move(handle), updater, r, this, m_request->integrity(), response.url()); } }
diff --git a/third_party/WebKit/Source/modules/fetch/Response.cpp b/third_party/WebKit/Source/modules/fetch/Response.cpp index 930084fe..9eafe2a 100644 --- a/third_party/WebKit/Source/modules/fetch/Response.cpp +++ b/third_party/WebKit/Source/modules/fetch/Response.cpp
@@ -236,7 +236,7 @@ exceptionState.throwTypeError("Response with null body status cannot have body"); return nullptr; } - r->m_response->replaceBodyStreamBuffer(new BodyStreamBuffer(bodyHandle)); + r->m_response->replaceBodyStreamBuffer(new BodyStreamBuffer(std::move(bodyHandle))); if (!contentType.isEmpty() && !r->m_response->headerList()->has("Content-Type")) r->m_response->headerList()->append("Content-Type", contentType); }
diff --git a/third_party/WebKit/Source/modules/fetch/ResponseTest.cpp b/third_party/WebKit/Source/modules/fetch/ResponseTest.cpp index d8ee7eff..a01c3ee1 100644 --- a/third_party/WebKit/Source/modules/fetch/ResponseTest.cpp +++ b/third_party/WebKit/Source/modules/fetch/ResponseTest.cpp
@@ -7,7 +7,6 @@ #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ScriptState.h" #include "core/dom/Document.h" -#include "core/dom/ExceptionCode.h" #include "core/frame/Frame.h" #include "core/testing/DummyPageHolder.h" #include "modules/fetch/BodyStreamBuffer.h"
diff --git a/third_party/WebKit/Source/modules/filesystem/EntrySync.cpp b/third_party/WebKit/Source/modules/filesystem/EntrySync.cpp index edbddc52..4aa749a 100644 --- a/third_party/WebKit/Source/modules/filesystem/EntrySync.cpp +++ b/third_party/WebKit/Source/modules/filesystem/EntrySync.cpp
@@ -32,7 +32,6 @@ #include "bindings/core/v8/ExceptionMessages.h" #include "bindings/core/v8/ExceptionState.h" -#include "core/dom/ExceptionCode.h" #include "modules/filesystem/DOMFilePath.h" #include "modules/filesystem/DirectoryEntry.h" #include "modules/filesystem/DirectoryEntrySync.h"
diff --git a/third_party/WebKit/Source/modules/filesystem/FileSystemCallbacks.cpp b/third_party/WebKit/Source/modules/filesystem/FileSystemCallbacks.cpp index 4cbaf8034..b88517d 100644 --- a/third_party/WebKit/Source/modules/filesystem/FileSystemCallbacks.cpp +++ b/third_party/WebKit/Source/modules/filesystem/FileSystemCallbacks.cpp
@@ -246,7 +246,7 @@ void FileWriterBaseCallbacks::didCreateFileWriter(PassOwnPtr<WebFileWriter> fileWriter, long long length) { - m_fileWriter->initialize(fileWriter, length); + m_fileWriter->initialize(std::move(fileWriter), length); if (m_successCallback) handleEventOrScheduleCallback(m_successCallback.release(), m_fileWriter.release()); }
diff --git a/third_party/WebKit/Source/modules/filesystem/FileWriterBase.cpp b/third_party/WebKit/Source/modules/filesystem/FileWriterBase.cpp index 12c9b9e..ab9f91b 100644 --- a/third_party/WebKit/Source/modules/filesystem/FileWriterBase.cpp +++ b/third_party/WebKit/Source/modules/filesystem/FileWriterBase.cpp
@@ -45,7 +45,7 @@ { ASSERT(!m_writer); ASSERT(length >= 0); - m_writer = writer; + m_writer = std::move(writer); m_length = length; }
diff --git a/third_party/WebKit/Source/modules/filesystem/LocalFileSystem.cpp b/third_party/WebKit/Source/modules/filesystem/LocalFileSystem.cpp index b2af75a2..9741432 100644 --- a/third_party/WebKit/Source/modules/filesystem/LocalFileSystem.cpp +++ b/third_party/WebKit/Source/modules/filesystem/LocalFileSystem.cpp
@@ -58,7 +58,7 @@ class CallbackWrapper final : public GarbageCollectedFinalized<CallbackWrapper> { public: CallbackWrapper(PassOwnPtr<AsyncFileSystemCallbacks> c) - : m_callbacks(c) + : m_callbacks(std::move(c)) { } virtual ~CallbackWrapper() { } @@ -75,7 +75,7 @@ LocalFileSystem* LocalFileSystem::create(PassOwnPtr<FileSystemClient> client) { - return new LocalFileSystem(client); + return new LocalFileSystem(std::move(client)); } LocalFileSystem::~LocalFileSystem() @@ -85,7 +85,7 @@ void LocalFileSystem::resolveURL(ExecutionContext* context, const KURL& fileSystemURL, PassOwnPtr<AsyncFileSystemCallbacks> callbacks) { ExecutionContext* contextPtr(context); - CallbackWrapper* wrapper = new CallbackWrapper(callbacks); + CallbackWrapper* wrapper = new CallbackWrapper(std::move(callbacks)); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::resolveURLInternal, this, contextPtr, fileSystemURL, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); @@ -94,7 +94,7 @@ void LocalFileSystem::requestFileSystem(ExecutionContext* context, FileSystemType type, long long size, PassOwnPtr<AsyncFileSystemCallbacks> callbacks) { ExecutionContext* contextPtr(context); - CallbackWrapper* wrapper = new CallbackWrapper(callbacks); + CallbackWrapper* wrapper = new CallbackWrapper(std::move(callbacks)); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::fileSystemAllowedInternal, this, contextPtr, type, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); @@ -106,7 +106,7 @@ ASSERT(context); ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument()); - CallbackWrapper* wrapper = new CallbackWrapper(callbacks); + CallbackWrapper* wrapper = new CallbackWrapper(std::move(callbacks)); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::deleteFileSystemInternal, this, contextPtr, type, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); @@ -134,21 +134,21 @@ (*allowed)(); return; } - client()->requestFileSystemAccessAsync(context, ContentSettingCallbacks::create(allowed, denied)); + client()->requestFileSystemAccessAsync(context, ContentSettingCallbacks::create(std::move(allowed), std::move(denied))); } void LocalFileSystem::fileSystemNotAvailable( ExecutionContext* context, CallbackWrapper* callbacks) { - context->postTask(BLINK_FROM_HERE, createSameThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR)); + context->postTask(BLINK_FROM_HERE, createSameThreadTask(&reportFailure, passed(callbacks->release()), FileError::ABORT_ERR)); } void LocalFileSystem::fileSystemNotAllowedInternal( ExecutionContext* context, CallbackWrapper* callbacks) { - context->postTask(BLINK_FROM_HERE, createSameThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR)); + context->postTask(BLINK_FROM_HERE, createSameThreadTask(&reportFailure, passed(callbacks->release()), FileError::ABORT_ERR)); } void LocalFileSystem::fileSystemAllowedInternal( @@ -191,7 +191,7 @@ } LocalFileSystem::LocalFileSystem(PassOwnPtr<FileSystemClient> client) - : m_client(client) + : m_client(std::move(client)) { } @@ -212,12 +212,12 @@ void provideLocalFileSystemTo(LocalFrame& frame, PassOwnPtr<FileSystemClient> client) { - frame.provideSupplement(LocalFileSystem::supplementName(), LocalFileSystem::create(client)); + frame.provideSupplement(LocalFileSystem::supplementName(), LocalFileSystem::create(std::move(client))); } void provideLocalFileSystemToWorker(WorkerClients* clients, PassOwnPtr<FileSystemClient> client) { - clients->provideSupplement(LocalFileSystem::supplementName(), LocalFileSystem::create(client)); + clients->provideSupplement(LocalFileSystem::supplementName(), LocalFileSystem::create(std::move(client))); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/imagebitmap/ImageBitmapRenderingContext.h b/third_party/WebKit/Source/modules/imagebitmap/ImageBitmapRenderingContext.h index 1118f80..e872494 100644 --- a/third_party/WebKit/Source/modules/imagebitmap/ImageBitmapRenderingContext.h +++ b/third_party/WebKit/Source/modules/imagebitmap/ImageBitmapRenderingContext.h
@@ -25,7 +25,6 @@ CanvasRenderingContext* create(HTMLCanvasElement*, const CanvasContextCreationAttributes&, Document&) override; CanvasRenderingContext::ContextType getContextType() const override { return CanvasRenderingContext::ContextImageBitmap; } - void onError(HTMLCanvasElement*, const String& error) override { } }; // Script API
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBCursor.cpp b/third_party/WebKit/Source/modules/indexeddb/IDBCursor.cpp index e4ab0851..1889964 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBCursor.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/IDBCursor.cpp
@@ -50,11 +50,11 @@ IDBCursor* IDBCursor::create(PassOwnPtr<WebIDBCursor> backend, WebIDBCursorDirection direction, IDBRequest* request, IDBAny* source, IDBTransaction* transaction) { - return new IDBCursor(backend, direction, request, source, transaction); + return new IDBCursor(std::move(backend), direction, request, source, transaction); } IDBCursor::IDBCursor(PassOwnPtr<WebIDBCursor> backend, WebIDBCursorDirection direction, IDBRequest* request, IDBAny* source, IDBTransaction* transaction) - : m_backend(backend) + : m_backend(std::move(backend)) , m_request(request) , m_direction(direction) , m_source(source)
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBCursorWithValue.cpp b/third_party/WebKit/Source/modules/indexeddb/IDBCursorWithValue.cpp index c4b20f62..c5a2793 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBCursorWithValue.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/IDBCursorWithValue.cpp
@@ -33,11 +33,11 @@ IDBCursorWithValue* IDBCursorWithValue::create(PassOwnPtr<WebIDBCursor> backend, WebIDBCursorDirection direction, IDBRequest* request, IDBAny* source, IDBTransaction* transaction) { - return new IDBCursorWithValue(backend, direction, request, source, transaction); + return new IDBCursorWithValue(std::move(backend), direction, request, source, transaction); } IDBCursorWithValue::IDBCursorWithValue(PassOwnPtr<WebIDBCursor> backend, WebIDBCursorDirection direction, IDBRequest* request, IDBAny* source, IDBTransaction* transaction) - : IDBCursor(backend, direction, request, source, transaction) + : IDBCursor(std::move(backend), direction, request, source, transaction) { }
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBDatabase.cpp b/third_party/WebKit/Source/modules/indexeddb/IDBDatabase.cpp index e578787..14108129 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBDatabase.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/IDBDatabase.cpp
@@ -68,7 +68,7 @@ IDBDatabase* IDBDatabase::create(ExecutionContext* context, PassOwnPtr<WebIDBDatabase> database, IDBDatabaseCallbacks* callbacks) { - IDBDatabase* idbDatabase = new IDBDatabase(context, database, callbacks); + IDBDatabase* idbDatabase = new IDBDatabase(context, std::move(database), callbacks); idbDatabase->suspendIfNeeded(); return idbDatabase; } @@ -76,7 +76,7 @@ IDBDatabase::IDBDatabase(ExecutionContext* context, PassOwnPtr<WebIDBDatabase> backend, IDBDatabaseCallbacks* callbacks) : ActiveScriptWrappable(this) , ActiveDOMObject(context) - , m_backend(backend) + , m_backend(std::move(backend)) , m_databaseCallbacks(callbacks) { m_databaseCallbacks->connect(this);
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBOpenDBRequest.cpp b/third_party/WebKit/Source/modules/indexeddb/IDBOpenDBRequest.cpp index a65d9de0..ce8ba0c 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBOpenDBRequest.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/IDBOpenDBRequest.cpp
@@ -82,7 +82,7 @@ { IDB_TRACE("IDBOpenDBRequest::onUpgradeNeeded()"); if (m_contextStopped || !getExecutionContext()) { - OwnPtr<WebIDBDatabase> db = backend; + OwnPtr<WebIDBDatabase> db = std::move(backend); db->abort(m_transactionId); db->close(); return; @@ -92,7 +92,7 @@ ASSERT(m_databaseCallbacks); - IDBDatabase* idbDatabase = IDBDatabase::create(getExecutionContext(), backend, m_databaseCallbacks.release()); + IDBDatabase* idbDatabase = IDBDatabase::create(getExecutionContext(), std::move(backend), m_databaseCallbacks.release()); idbDatabase->setMetadata(metadata); if (oldVersion == IDBDatabaseMetadata::NoVersion) { @@ -114,7 +114,7 @@ { IDB_TRACE("IDBOpenDBRequest::onSuccess()"); if (m_contextStopped || !getExecutionContext()) { - OwnPtr<WebIDBDatabase> db = backend; + OwnPtr<WebIDBDatabase> db = std::move(backend); if (db) db->close(); return; @@ -132,7 +132,7 @@ } else { ASSERT(backend.get()); ASSERT(m_databaseCallbacks); - idbDatabase = IDBDatabase::create(getExecutionContext(), backend, m_databaseCallbacks.release()); + idbDatabase = IDBDatabase::create(getExecutionContext(), std::move(backend), m_databaseCallbacks.release()); setResult(IDBAny::create(idbDatabase)); } idbDatabase->setMetadata(metadata);
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBRequest.cpp b/third_party/WebKit/Source/modules/indexeddb/IDBRequest.cpp index 09a2b17c..87b075a 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBRequest.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/IDBRequest.cpp
@@ -256,10 +256,10 @@ IDBCursor* cursor = nullptr; switch (m_cursorType) { case IndexedDB::CursorKeyOnly: - cursor = IDBCursor::create(backend, m_cursorDirection, this, m_source.get(), m_transaction.get()); + cursor = IDBCursor::create(std::move(backend), m_cursorDirection, this, m_source.get(), m_transaction.get()); break; case IndexedDB::CursorKeyAndValue: - cursor = IDBCursorWithValue::create(backend, m_cursorDirection, this, m_source.get(), m_transaction.get()); + cursor = IDBCursorWithValue::create(std::move(backend), m_cursorDirection, this, m_source.get(), m_transaction.get()); break; default: ASSERT_NOT_REACHED();
diff --git a/third_party/WebKit/Source/modules/indexeddb/InspectorIndexedDBAgent.cpp b/third_party/WebKit/Source/modules/indexeddb/InspectorIndexedDBAgent.cpp index e080fb3..f74dd647 100644 --- a/third_party/WebKit/Source/modules/indexeddb/InspectorIndexedDBAgent.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/InspectorIndexedDBAgent.cpp
@@ -90,7 +90,7 @@ public: static GetDatabaseNamesCallback* create(PassOwnPtr<RequestDatabaseNamesCallback> requestCallback, const String& securityOrigin) { - return new GetDatabaseNamesCallback(requestCallback, securityOrigin); + return new GetDatabaseNamesCallback(std::move(requestCallback), securityOrigin); } ~GetDatabaseNamesCallback() override { } @@ -129,7 +129,7 @@ private: GetDatabaseNamesCallback(PassOwnPtr<RequestDatabaseNamesCallback> requestCallback, const String& securityOrigin) : EventListener(EventListener::CPPEventListenerType) - , m_requestCallback(requestCallback) + , m_requestCallback(std::move(requestCallback)) , m_securityOrigin(securityOrigin) { } OwnPtr<RequestDatabaseNamesCallback> m_requestCallback; String m_securityOrigin; @@ -300,7 +300,7 @@ public: static PassRefPtr<DatabaseLoader> create(ScriptState* scriptState, PassOwnPtr<RequestDatabaseCallback> requestCallback) { - return adoptRef(new DatabaseLoader(scriptState, requestCallback)); + return adoptRef(new DatabaseLoader(scriptState, std::move(requestCallback))); } ~DatabaseLoader() override { } @@ -346,7 +346,7 @@ private: DatabaseLoader(ScriptState* scriptState, PassOwnPtr<RequestDatabaseCallback> requestCallback) : ExecutableWithDatabase(scriptState) - , m_requestCallback(requestCallback) { } + , m_requestCallback(std::move(requestCallback)) { } OwnPtr<RequestDatabaseCallback> m_requestCallback; }; @@ -409,7 +409,7 @@ public: static OpenCursorCallback* create(ScriptState* scriptState, PassOwnPtr<RequestDataCallback> requestCallback, int skipCount, unsigned pageSize) { - return new OpenCursorCallback(scriptState, requestCallback, skipCount, pageSize); + return new OpenCursorCallback(scriptState, std::move(requestCallback), skipCount, pageSize); } ~OpenCursorCallback() override { } @@ -496,7 +496,7 @@ OpenCursorCallback(ScriptState* scriptState, PassOwnPtr<RequestDataCallback> requestCallback, int skipCount, unsigned pageSize) : EventListener(EventListener::CPPEventListenerType) , m_scriptState(scriptState) - , m_requestCallback(requestCallback) + , m_requestCallback(std::move(requestCallback)) , m_skipCount(skipCount) , m_pageSize(pageSize) { @@ -514,7 +514,7 @@ public: static PassRefPtr<DataLoader> create(ScriptState* scriptState, PassOwnPtr<RequestDataCallback> requestCallback, const String& objectStoreName, const String& indexName, IDBKeyRange* idbKeyRange, int skipCount, unsigned pageSize) { - return adoptRef(new DataLoader(scriptState, requestCallback, objectStoreName, indexName, idbKeyRange, skipCount, pageSize)); + return adoptRef(new DataLoader(scriptState, std::move(requestCallback), objectStoreName, indexName, idbKeyRange, skipCount, pageSize)); } ~DataLoader() override { } @@ -551,7 +551,7 @@ RequestCallback* getRequestCallback() override { return m_requestCallback.get(); } DataLoader(ScriptState* scriptState, PassOwnPtr<RequestDataCallback> requestCallback, const String& objectStoreName, const String& indexName, IDBKeyRange* idbKeyRange, int skipCount, unsigned pageSize) : ExecutableWithDatabase(scriptState) - , m_requestCallback(requestCallback) + , m_requestCallback(std::move(requestCallback)) , m_objectStoreName(objectStoreName) , m_indexName(indexName) , m_idbKeyRange(idbKeyRange) @@ -649,7 +649,7 @@ requestCallback->sendFailure("Could not obtain database names."); return; } - idbRequest->addEventListener(EventTypeNames::success, GetDatabaseNamesCallback::create(requestCallback, document->getSecurityOrigin()->toRawString()), false); + idbRequest->addEventListener(EventTypeNames::success, GetDatabaseNamesCallback::create(std::move(requestCallback), document->getSecurityOrigin()->toRawString()), false); } void InspectorIndexedDBAgent::requestDatabase(ErrorString* errorString, const String& securityOrigin, const String& databaseName, PassOwnPtr<RequestDatabaseCallback> requestCallback) @@ -666,7 +666,7 @@ if (!scriptState) return; ScriptState::Scope scope(scriptState); - RefPtr<DatabaseLoader> databaseLoader = DatabaseLoader::create(scriptState, requestCallback); + RefPtr<DatabaseLoader> databaseLoader = DatabaseLoader::create(scriptState, std::move(requestCallback)); databaseLoader->start(idbFactory, document->getSecurityOrigin(), databaseName); } @@ -678,7 +678,7 @@ int skipCount, int pageSize, const Maybe<protocol::IndexedDB::KeyRange>& keyRange, - const PassOwnPtr<RequestDataCallback> requestCallback) + PassOwnPtr<RequestDataCallback> requestCallback) { LocalFrame* frame = m_inspectedFrames->frameWithSecurityOrigin(securityOrigin); Document* document = assertDocument(errorString, frame); @@ -698,7 +698,7 @@ if (!scriptState) return; ScriptState::Scope scope(scriptState); - RefPtr<DataLoader> dataLoader = DataLoader::create(scriptState, requestCallback, objectStoreName, indexName, idbKeyRange, skipCount, pageSize); + RefPtr<DataLoader> dataLoader = DataLoader::create(scriptState, std::move(requestCallback), objectStoreName, indexName, idbKeyRange, skipCount, pageSize); dataLoader->start(idbFactory, document->getSecurityOrigin(), databaseName); } @@ -707,7 +707,7 @@ public: static ClearObjectStoreListener* create(PassOwnPtr<ClearObjectStoreCallback> requestCallback) { - return new ClearObjectStoreListener(requestCallback); + return new ClearObjectStoreListener(std::move(requestCallback)); } ~ClearObjectStoreListener() override { } @@ -735,7 +735,7 @@ private: ClearObjectStoreListener(PassOwnPtr<ClearObjectStoreCallback> requestCallback) : EventListener(EventListener::CPPEventListenerType) - , m_requestCallback(requestCallback) + , m_requestCallback(std::move(requestCallback)) { } @@ -747,13 +747,13 @@ public: static PassRefPtr<ClearObjectStore> create(ScriptState* scriptState, const String& objectStoreName, PassOwnPtr<ClearObjectStoreCallback> requestCallback) { - return adoptRef(new ClearObjectStore(scriptState, objectStoreName, requestCallback)); + return adoptRef(new ClearObjectStore(scriptState, objectStoreName, std::move(requestCallback))); } ClearObjectStore(ScriptState* scriptState, const String& objectStoreName, PassOwnPtr<ClearObjectStoreCallback> requestCallback) : ExecutableWithDatabase(scriptState) , m_objectStoreName(objectStoreName) - , m_requestCallback(requestCallback) + , m_requestCallback(std::move(requestCallback)) { } @@ -801,7 +801,7 @@ if (!scriptState) return; ScriptState::Scope scope(scriptState); - RefPtr<ClearObjectStore> clearObjectStore = ClearObjectStore::create(scriptState, objectStoreName, requestCallback); + RefPtr<ClearObjectStore> clearObjectStore = ClearObjectStore::create(scriptState, objectStoreName, std::move(requestCallback)); clearObjectStore->start(idbFactory, document->getSecurityOrigin(), databaseName); }
diff --git a/third_party/WebKit/Source/modules/mediacapturefromelement/AutoCanvasDrawListener.cpp b/third_party/WebKit/Source/modules/mediacapturefromelement/AutoCanvasDrawListener.cpp index 6ad17ff..d5aca1b 100644 --- a/third_party/WebKit/Source/modules/mediacapturefromelement/AutoCanvasDrawListener.cpp +++ b/third_party/WebKit/Source/modules/mediacapturefromelement/AutoCanvasDrawListener.cpp
@@ -6,15 +6,15 @@ namespace blink { -AutoCanvasDrawListener::AutoCanvasDrawListener(const PassOwnPtr<WebCanvasCaptureHandler>& handler) - : CanvasDrawListener(handler) +AutoCanvasDrawListener::AutoCanvasDrawListener(PassOwnPtr<WebCanvasCaptureHandler> handler) + : CanvasDrawListener(std::move(handler)) { } // static -AutoCanvasDrawListener* AutoCanvasDrawListener::create(const PassOwnPtr<WebCanvasCaptureHandler>& handler) +AutoCanvasDrawListener* AutoCanvasDrawListener::create(PassOwnPtr<WebCanvasCaptureHandler> handler) { - return new AutoCanvasDrawListener(handler); + return new AutoCanvasDrawListener(std::move(handler)); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/mediacapturefromelement/AutoCanvasDrawListener.h b/third_party/WebKit/Source/modules/mediacapturefromelement/AutoCanvasDrawListener.h index 879a727..4a3fdf31d 100644 --- a/third_party/WebKit/Source/modules/mediacapturefromelement/AutoCanvasDrawListener.h +++ b/third_party/WebKit/Source/modules/mediacapturefromelement/AutoCanvasDrawListener.h
@@ -14,12 +14,12 @@ class AutoCanvasDrawListener final : public GarbageCollectedFinalized<AutoCanvasDrawListener>, public CanvasDrawListener { USING_GARBAGE_COLLECTED_MIXIN(AutoCanvasDrawListener); public: - static AutoCanvasDrawListener* create(const PassOwnPtr<WebCanvasCaptureHandler>&); + static AutoCanvasDrawListener* create(PassOwnPtr<WebCanvasCaptureHandler>); ~AutoCanvasDrawListener() {} DEFINE_INLINE_TRACE() {} private: - AutoCanvasDrawListener(const PassOwnPtr<WebCanvasCaptureHandler>&); + AutoCanvasDrawListener(PassOwnPtr<WebCanvasCaptureHandler>); }; } // namespace blink
diff --git a/third_party/WebKit/Source/modules/mediacapturefromelement/CanvasCaptureMediaStreamTrack.cpp b/third_party/WebKit/Source/modules/mediacapturefromelement/CanvasCaptureMediaStreamTrack.cpp index 53ae3e1..023e959 100644 --- a/third_party/WebKit/Source/modules/mediacapturefromelement/CanvasCaptureMediaStreamTrack.cpp +++ b/third_party/WebKit/Source/modules/mediacapturefromelement/CanvasCaptureMediaStreamTrack.cpp
@@ -12,14 +12,14 @@ namespace blink { -CanvasCaptureMediaStreamTrack* CanvasCaptureMediaStreamTrack::create(MediaStreamComponent* component, HTMLCanvasElement* element, const PassOwnPtr<WebCanvasCaptureHandler> handler) +CanvasCaptureMediaStreamTrack* CanvasCaptureMediaStreamTrack::create(MediaStreamComponent* component, HTMLCanvasElement* element, PassOwnPtr<WebCanvasCaptureHandler> handler) { - return new CanvasCaptureMediaStreamTrack(component, element, handler); + return new CanvasCaptureMediaStreamTrack(component, element, std::move(handler)); } -CanvasCaptureMediaStreamTrack* CanvasCaptureMediaStreamTrack::create(MediaStreamComponent* component, HTMLCanvasElement* element, const PassOwnPtr<WebCanvasCaptureHandler> handler, double frameRate) +CanvasCaptureMediaStreamTrack* CanvasCaptureMediaStreamTrack::create(MediaStreamComponent* component, HTMLCanvasElement* element, PassOwnPtr<WebCanvasCaptureHandler> handler, double frameRate) { - return new CanvasCaptureMediaStreamTrack(component, element, handler, frameRate); + return new CanvasCaptureMediaStreamTrack(component, element, std::move(handler), frameRate); } HTMLCanvasElement* CanvasCaptureMediaStreamTrack::canvas() const @@ -56,24 +56,24 @@ m_canvasElement->addListener(m_drawListener.get()); } -CanvasCaptureMediaStreamTrack::CanvasCaptureMediaStreamTrack(MediaStreamComponent* component, HTMLCanvasElement* element, const PassOwnPtr<WebCanvasCaptureHandler> handler) +CanvasCaptureMediaStreamTrack::CanvasCaptureMediaStreamTrack(MediaStreamComponent* component, HTMLCanvasElement* element, PassOwnPtr<WebCanvasCaptureHandler> handler) : MediaStreamTrack(element->getExecutionContext(), component) , m_canvasElement(element) { suspendIfNeeded(); - m_drawListener = AutoCanvasDrawListener::create(handler); + m_drawListener = AutoCanvasDrawListener::create(std::move(handler)); m_canvasElement->addListener(m_drawListener.get()); } -CanvasCaptureMediaStreamTrack::CanvasCaptureMediaStreamTrack(MediaStreamComponent* component, HTMLCanvasElement* element, const PassOwnPtr<WebCanvasCaptureHandler> handler, double frameRate) +CanvasCaptureMediaStreamTrack::CanvasCaptureMediaStreamTrack(MediaStreamComponent* component, HTMLCanvasElement* element, PassOwnPtr<WebCanvasCaptureHandler> handler, double frameRate) : MediaStreamTrack(element->getExecutionContext(), component) , m_canvasElement(element) { suspendIfNeeded(); if (frameRate == 0) { - m_drawListener = OnRequestCanvasDrawListener::create(handler); + m_drawListener = OnRequestCanvasDrawListener::create(std::move(handler)); } else { - m_drawListener = TimedCanvasDrawListener::create(handler, frameRate); + m_drawListener = TimedCanvasDrawListener::create(std::move(handler), frameRate); } m_canvasElement->addListener(m_drawListener.get()); }
diff --git a/third_party/WebKit/Source/modules/mediacapturefromelement/CanvasCaptureMediaStreamTrack.h b/third_party/WebKit/Source/modules/mediacapturefromelement/CanvasCaptureMediaStreamTrack.h index 9ba323e..a906bf1 100644 --- a/third_party/WebKit/Source/modules/mediacapturefromelement/CanvasCaptureMediaStreamTrack.h +++ b/third_party/WebKit/Source/modules/mediacapturefromelement/CanvasCaptureMediaStreamTrack.h
@@ -17,8 +17,8 @@ class CanvasCaptureMediaStreamTrack final : public MediaStreamTrack { DEFINE_WRAPPERTYPEINFO(); public: - static CanvasCaptureMediaStreamTrack* create(MediaStreamComponent*, HTMLCanvasElement*, const PassOwnPtr<WebCanvasCaptureHandler>); - static CanvasCaptureMediaStreamTrack* create(MediaStreamComponent*, HTMLCanvasElement*, const PassOwnPtr<WebCanvasCaptureHandler>, double frameRate); + static CanvasCaptureMediaStreamTrack* create(MediaStreamComponent*, HTMLCanvasElement*, PassOwnPtr<WebCanvasCaptureHandler>); + static CanvasCaptureMediaStreamTrack* create(MediaStreamComponent*, HTMLCanvasElement*, PassOwnPtr<WebCanvasCaptureHandler>, double frameRate); HTMLCanvasElement* canvas() const; void requestFrame(); @@ -29,8 +29,8 @@ private: CanvasCaptureMediaStreamTrack(const CanvasCaptureMediaStreamTrack&, MediaStreamComponent*); - CanvasCaptureMediaStreamTrack(MediaStreamComponent*, HTMLCanvasElement*, const PassOwnPtr<WebCanvasCaptureHandler>); - CanvasCaptureMediaStreamTrack(MediaStreamComponent*, HTMLCanvasElement*, const PassOwnPtr<WebCanvasCaptureHandler>, double frameRate); + CanvasCaptureMediaStreamTrack(MediaStreamComponent*, HTMLCanvasElement*, PassOwnPtr<WebCanvasCaptureHandler>); + CanvasCaptureMediaStreamTrack(MediaStreamComponent*, HTMLCanvasElement*, PassOwnPtr<WebCanvasCaptureHandler>, double frameRate); Member<HTMLCanvasElement> m_canvasElement; Member<CanvasDrawListener> m_drawListener;
diff --git a/third_party/WebKit/Source/modules/mediacapturefromelement/OnRequestCanvasDrawListener.cpp b/third_party/WebKit/Source/modules/mediacapturefromelement/OnRequestCanvasDrawListener.cpp index 4f81c7f..87cee32 100644 --- a/third_party/WebKit/Source/modules/mediacapturefromelement/OnRequestCanvasDrawListener.cpp +++ b/third_party/WebKit/Source/modules/mediacapturefromelement/OnRequestCanvasDrawListener.cpp
@@ -6,17 +6,17 @@ namespace blink { -OnRequestCanvasDrawListener::OnRequestCanvasDrawListener(const PassOwnPtr<WebCanvasCaptureHandler>& handler) - :CanvasDrawListener(handler) +OnRequestCanvasDrawListener::OnRequestCanvasDrawListener(PassOwnPtr<WebCanvasCaptureHandler> handler) + : CanvasDrawListener(std::move(handler)) { } OnRequestCanvasDrawListener::~OnRequestCanvasDrawListener() {} // static -OnRequestCanvasDrawListener* OnRequestCanvasDrawListener::create(const PassOwnPtr<WebCanvasCaptureHandler>& handler) +OnRequestCanvasDrawListener* OnRequestCanvasDrawListener::create(PassOwnPtr<WebCanvasCaptureHandler> handler) { - return new OnRequestCanvasDrawListener(handler); + return new OnRequestCanvasDrawListener(std::move(handler)); } void OnRequestCanvasDrawListener::sendNewFrame(const WTF::PassRefPtr<SkImage>& image)
diff --git a/third_party/WebKit/Source/modules/mediacapturefromelement/OnRequestCanvasDrawListener.h b/third_party/WebKit/Source/modules/mediacapturefromelement/OnRequestCanvasDrawListener.h index 306de51..5992b90 100644 --- a/third_party/WebKit/Source/modules/mediacapturefromelement/OnRequestCanvasDrawListener.h +++ b/third_party/WebKit/Source/modules/mediacapturefromelement/OnRequestCanvasDrawListener.h
@@ -15,12 +15,12 @@ USING_GARBAGE_COLLECTED_MIXIN(OnRequestCanvasDrawListener); public: ~OnRequestCanvasDrawListener(); - static OnRequestCanvasDrawListener* create(const PassOwnPtr<WebCanvasCaptureHandler>&); + static OnRequestCanvasDrawListener* create(PassOwnPtr<WebCanvasCaptureHandler>); void sendNewFrame(const WTF::PassRefPtr<SkImage>&) override; DEFINE_INLINE_TRACE() {} private: - OnRequestCanvasDrawListener(const PassOwnPtr<WebCanvasCaptureHandler>&); + OnRequestCanvasDrawListener(PassOwnPtr<WebCanvasCaptureHandler>); }; } // namespace blink
diff --git a/third_party/WebKit/Source/modules/mediacapturefromelement/TimedCanvasDrawListener.cpp b/third_party/WebKit/Source/modules/mediacapturefromelement/TimedCanvasDrawListener.cpp index f05e2c55..60a8586 100644 --- a/third_party/WebKit/Source/modules/mediacapturefromelement/TimedCanvasDrawListener.cpp +++ b/third_party/WebKit/Source/modules/mediacapturefromelement/TimedCanvasDrawListener.cpp
@@ -6,8 +6,8 @@ namespace blink { -TimedCanvasDrawListener::TimedCanvasDrawListener(const PassOwnPtr<WebCanvasCaptureHandler>& handler, double frameRate) - : CanvasDrawListener(handler) +TimedCanvasDrawListener::TimedCanvasDrawListener(PassOwnPtr<WebCanvasCaptureHandler> handler, double frameRate) + : CanvasDrawListener(std::move(handler)) , m_frameInterval(1 / frameRate) , m_requestFrameTimer(this, &TimedCanvasDrawListener::requestFrameTimerFired) { @@ -16,9 +16,9 @@ TimedCanvasDrawListener::~TimedCanvasDrawListener() {} // static -TimedCanvasDrawListener* TimedCanvasDrawListener::create(const PassOwnPtr<WebCanvasCaptureHandler>& handler, double frameRate) +TimedCanvasDrawListener* TimedCanvasDrawListener::create(PassOwnPtr<WebCanvasCaptureHandler> handler, double frameRate) { - TimedCanvasDrawListener* listener = new TimedCanvasDrawListener(handler, frameRate); + TimedCanvasDrawListener* listener = new TimedCanvasDrawListener(std::move(handler), frameRate); listener->m_requestFrameTimer.startRepeating(listener->m_frameInterval, BLINK_FROM_HERE); return listener; }
diff --git a/third_party/WebKit/Source/modules/mediacapturefromelement/TimedCanvasDrawListener.h b/third_party/WebKit/Source/modules/mediacapturefromelement/TimedCanvasDrawListener.h index 71fe534..1786473 100644 --- a/third_party/WebKit/Source/modules/mediacapturefromelement/TimedCanvasDrawListener.h +++ b/third_party/WebKit/Source/modules/mediacapturefromelement/TimedCanvasDrawListener.h
@@ -16,12 +16,12 @@ USING_GARBAGE_COLLECTED_MIXIN(TimedCanvasDrawListener); public: ~TimedCanvasDrawListener(); - static TimedCanvasDrawListener* create(const PassOwnPtr<WebCanvasCaptureHandler>&, double frameRate); + static TimedCanvasDrawListener* create(PassOwnPtr<WebCanvasCaptureHandler>, double frameRate); void sendNewFrame(const WTF::PassRefPtr<SkImage>&) override; DEFINE_INLINE_TRACE() {} private: - TimedCanvasDrawListener(const PassOwnPtr<WebCanvasCaptureHandler>&, double frameRate); + TimedCanvasDrawListener(PassOwnPtr<WebCanvasCaptureHandler>, double frameRate); // Implementation of TimerFiredFunction. void requestFrameTimerFired(Timer<TimedCanvasDrawListener>*);
diff --git a/third_party/WebKit/Source/modules/mediasession/MediaSession.cpp b/third_party/WebKit/Source/modules/mediasession/MediaSession.cpp index 8ccf10c4..89c16783 100644 --- a/third_party/WebKit/Source/modules/mediasession/MediaSession.cpp +++ b/third_party/WebKit/Source/modules/mediasession/MediaSession.cpp
@@ -18,7 +18,7 @@ namespace blink { MediaSession::MediaSession(PassOwnPtr<WebMediaSession> webMediaSession) - : m_webMediaSession(webMediaSession) + : m_webMediaSession(std::move(webMediaSession)) { ASSERT(m_webMediaSession); }
diff --git a/third_party/WebKit/Source/modules/mediasource/MediaSource.cpp b/third_party/WebKit/Source/modules/mediasource/MediaSource.cpp index 865c9aa..8089d19 100644 --- a/third_party/WebKit/Source/modules/mediasource/MediaSource.cpp +++ b/third_party/WebKit/Source/modules/mediasource/MediaSource.cpp
@@ -290,7 +290,7 @@ ASSERT(webMediaSource); ASSERT(!m_webMediaSource); ASSERT(m_attachedElement); - m_webMediaSource = webMediaSource; + m_webMediaSource = std::move(webMediaSource); setReadyState(openKeyword()); }
diff --git a/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp b/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp index 5466c5a..3e8dffe 100644 --- a/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp +++ b/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp
@@ -98,7 +98,7 @@ SourceBuffer* SourceBuffer::create(PassOwnPtr<WebSourceBuffer> webSourceBuffer, MediaSource* source, GenericEventQueue* asyncEventQueue) { - SourceBuffer* sourceBuffer = new SourceBuffer(webSourceBuffer, source, asyncEventQueue); + SourceBuffer* sourceBuffer = new SourceBuffer(std::move(webSourceBuffer), source, asyncEventQueue); sourceBuffer->suspendIfNeeded(); return sourceBuffer; } @@ -106,7 +106,7 @@ SourceBuffer::SourceBuffer(PassOwnPtr<WebSourceBuffer> webSourceBuffer, MediaSource* source, GenericEventQueue* asyncEventQueue) : ActiveScriptWrappable(this) , ActiveDOMObject(source->getExecutionContext()) - , m_webSourceBuffer(webSourceBuffer) + , m_webSourceBuffer(std::move(webSourceBuffer)) , m_source(source) , m_trackDefaults(TrackDefaultList::create()) , m_asyncEventQueue(asyncEventQueue)
diff --git a/third_party/WebKit/Source/modules/mediastream/RTCDTMFSender.cpp b/third_party/WebKit/Source/modules/mediastream/RTCDTMFSender.cpp index b83312e..feb241c 100644 --- a/third_party/WebKit/Source/modules/mediastream/RTCDTMFSender.cpp +++ b/third_party/WebKit/Source/modules/mediastream/RTCDTMFSender.cpp
@@ -61,7 +61,7 @@ , m_track(track) , m_duration(defaultToneDurationMs) , m_interToneGap(defaultInterToneGapMs) - , m_handler(handler) + , m_handler(std::move(handler)) , m_stopped(false) , m_scheduledEventTimer(this, &RTCDTMFSender::scheduledEventTimerFired) {
diff --git a/third_party/WebKit/Source/modules/mediastream/RTCDataChannel.cpp b/third_party/WebKit/Source/modules/mediastream/RTCDataChannel.cpp index 85bc34f..c9f5345 100644 --- a/third_party/WebKit/Source/modules/mediastream/RTCDataChannel.cpp +++ b/third_party/WebKit/Source/modules/mediastream/RTCDataChannel.cpp
@@ -54,7 +54,7 @@ RTCDataChannel* RTCDataChannel::create(ExecutionContext* context, PassOwnPtr<WebRTCDataChannelHandler> handler) { DCHECK(handler); - RTCDataChannel* channel = new RTCDataChannel(context, handler); + RTCDataChannel* channel = new RTCDataChannel(context, std::move(handler)); channel->suspendIfNeeded(); return channel; @@ -76,7 +76,7 @@ RTCDataChannel::RTCDataChannel(ExecutionContext* context, PassOwnPtr<WebRTCDataChannelHandler> handler) : ActiveScriptWrappable(this) , ActiveDOMObject(context) - , m_handler(handler) + , m_handler(std::move(handler)) , m_readyState(ReadyStateConnecting) , m_binaryType(BinaryTypeArrayBuffer) , m_scheduledEventTimer(this, &RTCDataChannel::scheduledEventTimerFired)
diff --git a/third_party/WebKit/Source/modules/mediastream/RTCPeerConnection.cpp b/third_party/WebKit/Source/modules/mediastream/RTCPeerConnection.cpp index 1ff1f53..b421958 100644 --- a/third_party/WebKit/Source/modules/mediastream/RTCPeerConnection.cpp +++ b/third_party/WebKit/Source/modules/mediastream/RTCPeerConnection.cpp
@@ -361,7 +361,7 @@ Event* event, PassOwnPtr<BoolFunction> function) : m_event(event) - , m_setupFunction(function) + , m_setupFunction(std::move(function)) { } @@ -1186,7 +1186,7 @@ void RTCPeerConnection::scheduleDispatchEvent(Event* event, PassOwnPtr<BoolFunction> setupFunction) { - m_scheduledEvents.append(new EventWrapper(event, setupFunction)); + m_scheduledEvents.append(new EventWrapper(event, std::move(setupFunction))); m_dispatchScheduledEventRunner->runAsync(); }
diff --git a/third_party/WebKit/Source/modules/modules.gypi b/third_party/WebKit/Source/modules/modules.gypi index 4f648d4..24b70ae 100644 --- a/third_party/WebKit/Source/modules/modules.gypi +++ b/third_party/WebKit/Source/modules/modules.gypi
@@ -39,6 +39,7 @@ 'credentialmanager/CredentialsContainer.idl', 'credentialmanager/FederatedCredential.idl', 'credentialmanager/PasswordCredential.idl', + 'credentialmanager/SiteBoundCredential.idl', 'crypto/Crypto.idl', 'crypto/CryptoKey.idl', 'crypto/SubtleCrypto.idl', @@ -150,7 +151,6 @@ 'notifications/Notification.idl', 'notifications/NotificationEvent.idl', 'notifications/NotificationPermissionCallback.idl', - 'offscreencanvas/OffscreenCanvas.idl', 'offscreencanvas2d/OffscreenCanvasRenderingContext2D.idl', 'payments/PaymentRequest.idl', 'payments/PaymentResponse.idl', @@ -381,6 +381,7 @@ 'netinfo/WorkerNavigatorNetworkInformation.idl', 'notifications/ServiceWorkerGlobalScopeNotifications.idl', 'notifications/ServiceWorkerRegistrationNotifications.idl', + 'offscreencanvas/OffscreenCanvasModules.idl', 'permissions/NavigatorPermissions.idl', 'permissions/WorkerNavigatorPermissions.idl', 'plugins/NavigatorPlugins.idl', @@ -906,10 +907,12 @@ 'credentialmanager/CredentialsContainer.h', 'credentialmanager/FederatedCredential.cpp', 'credentialmanager/FederatedCredential.h', - 'credentialmanager/PasswordCredential.cpp', - 'credentialmanager/PasswordCredential.h', 'credentialmanager/NavigatorCredentials.cpp', 'credentialmanager/NavigatorCredentials.h', + 'credentialmanager/PasswordCredential.cpp', + 'credentialmanager/PasswordCredential.h', + 'credentialmanager/SiteBoundCredential.cpp', + 'credentialmanager/SiteBoundCredential.h', 'crypto/Crypto.cpp', 'crypto/Crypto.h', 'crypto/CryptoHistograms.cpp', @@ -1337,11 +1340,8 @@ 'notifications/ServiceWorkerGlobalScopeNotifications.h', 'notifications/ServiceWorkerRegistrationNotifications.cpp', 'notifications/ServiceWorkerRegistrationNotifications.h', - 'offscreencanvas/OffscreenCanvas.cpp', - 'offscreencanvas/OffscreenCanvas.h', - 'offscreencanvas/OffscreenCanvasRenderingContext.cpp', - 'offscreencanvas/OffscreenCanvasRenderingContext.h', - 'offscreencanvas/OffscreenCanvasRenderingContextFactory.h', + 'offscreencanvas/OffscreenCanvasModules.cpp', + 'offscreencanvas/OffscreenCanvasModules.h', 'offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp', 'offscreencanvas2d/OffscreenCanvasRenderingContext2D.h', 'payments/PaymentCompleter.h',
diff --git a/third_party/WebKit/Source/modules/notifications/NotificationImageLoader.cpp b/third_party/WebKit/Source/modules/notifications/NotificationImageLoader.cpp index dbd0919..d908074 100644 --- a/third_party/WebKit/Source/modules/notifications/NotificationImageLoader.cpp +++ b/third_party/WebKit/Source/modules/notifications/NotificationImageLoader.cpp
@@ -30,7 +30,7 @@ { DCHECK(!m_stopped); - m_imageCallback = imageCallback; + m_imageCallback = std::move(imageCallback); // TODO(mvanouwerkerk): Add a timeout mechanism: crbug.com/579137. ThreadableLoaderOptions threadableLoaderOptions;
diff --git a/third_party/WebKit/Source/modules/notifications/NotificationResourcesLoader.cpp b/third_party/WebKit/Source/modules/notifications/NotificationResourcesLoader.cpp index 6e59fd3..365512a 100644 --- a/third_party/WebKit/Source/modules/notifications/NotificationResourcesLoader.cpp +++ b/third_party/WebKit/Source/modules/notifications/NotificationResourcesLoader.cpp
@@ -29,7 +29,7 @@ } // namespace NotificationResourcesLoader::NotificationResourcesLoader(PassOwnPtr<CompletionCallback> completionCallback) - : m_started(false), m_completionCallback(completionCallback), m_pendingRequestCount(0) + : m_started(false), m_completionCallback(std::move(completionCallback)), m_pendingRequestCount(0) { ThreadState::current()->registerPreFinalizer(this); DCHECK(m_completionCallback); @@ -84,7 +84,7 @@ NotificationImageLoader* imageLoader = new NotificationImageLoader(); m_imageLoaders.append(imageLoader); - imageLoader->start(executionContext, url, imageCallback); + imageLoader->start(executionContext, url, std::move(imageCallback)); } void NotificationResourcesLoader::didLoadIcon(const SkBitmap& image)
diff --git a/third_party/WebKit/Source/modules/notifications/ServiceWorkerRegistrationNotifications.cpp b/third_party/WebKit/Source/modules/notifications/ServiceWorkerRegistrationNotifications.cpp index 47a5566..56eba48 100644 --- a/third_party/WebKit/Source/modules/notifications/ServiceWorkerRegistrationNotifications.cpp +++ b/third_party/WebKit/Source/modules/notifications/ServiceWorkerRegistrationNotifications.cpp
@@ -130,7 +130,7 @@ void ServiceWorkerRegistrationNotifications::prepareShow(const WebNotificationData& data, PassOwnPtr<WebNotificationShowCallbacks> callbacks) { RefPtr<SecurityOrigin> origin = getExecutionContext()->getSecurityOrigin(); - NotificationResourcesLoader* loader = new NotificationResourcesLoader(bind<NotificationResourcesLoader*>(&ServiceWorkerRegistrationNotifications::didLoadResources, WeakPersistentThisPointer<ServiceWorkerRegistrationNotifications>(this), origin.release(), data, callbacks)); + NotificationResourcesLoader* loader = new NotificationResourcesLoader(bind<NotificationResourcesLoader*>(&ServiceWorkerRegistrationNotifications::didLoadResources, WeakPersistentThisPointer<ServiceWorkerRegistrationNotifications>(this), origin.release(), data, passed(std::move(callbacks)))); m_loaders.add(loader); loader->start(getExecutionContext(), data); }
diff --git a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvas.cpp b/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvas.cpp deleted file mode 100644 index 0aedca5..0000000 --- a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvas.cpp +++ /dev/null
@@ -1,113 +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. - -#include "modules/offscreencanvas/OffscreenCanvas.h" - -#include "core/dom/ExceptionCode.h" -#include "core/html/canvas/CanvasContextCreationAttributes.h" -#include "modules/offscreencanvas/OffscreenCanvasRenderingContext.h" -#include "modules/offscreencanvas/OffscreenCanvasRenderingContextFactory.h" -#include "modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.h" -#include "wtf/MathExtras.h" - -namespace blink { - -OffscreenCanvas::OffscreenCanvas(const IntSize& size) - : m_size(size) -{ } - -OffscreenCanvas::~OffscreenCanvas() -{ } - -OffscreenCanvas* OffscreenCanvas::create(unsigned width, unsigned height) -{ - return new OffscreenCanvas(IntSize(clampTo<int>(width), clampTo<int>(height))); -} - -void OffscreenCanvas::setWidth(unsigned width) -{ - m_size.setWidth(clampTo<int>(width)); -} - -void OffscreenCanvas::setHeight(unsigned height) -{ - m_size.setHeight(clampTo<int>(height)); -} - -OffscreenCanvasRenderingContext2D* OffscreenCanvas::getContext(const String& id, const CanvasContextCreationAttributes& attributes) -{ - OffscreenCanvasRenderingContext::ContextType contextType = OffscreenCanvasRenderingContext::contextTypeFromId(id); - - // Unknown type. - if (contextType == OffscreenCanvasRenderingContext::ContextTypeCount) - return nullptr; - - OffscreenCanvasRenderingContextFactory* factory = getRenderingContextFactory(contextType); - if (!factory) - return nullptr; - - if (m_context) { - if (m_context->getContextType() != contextType) { - factory->onError(this, "OffscreenCanvas has an existing context of a different type"); - return nullptr; - } - } else { - m_context = factory->create(this, attributes); - } - - // TODO: When there're more than one context type implemented in the future, - // the return type here should be changed to base class of all Offscreen - // context types. - return static_cast<OffscreenCanvasRenderingContext2D*>(m_context.get()); -} - -ImageBitmap* OffscreenCanvas::transferToImageBitmap(ExceptionState& exceptionState) -{ - if (!m_context) { - exceptionState.throwDOMException(InvalidStateError, "Cannot transfer an ImageBitmap from an OffscreenCanvas with no context"); - return nullptr; - } - ImageBitmap* image = m_context->transferToImageBitmap(exceptionState); - if (!image) { - // Undocumented exception (not in spec) - exceptionState.throwDOMException(V8GeneralError, "Out of memory"); - } - return image; -} - -OffscreenCanvasRenderingContext2D* OffscreenCanvas::renderingContext() const -{ - // TODO: When there're more than one context type implemented in the future, - // the return type here should be changed to base class of all Offscreen - // context types. - return static_cast<OffscreenCanvasRenderingContext2D*>(m_context.get()); -} - -OffscreenCanvas::ContextFactoryVector& OffscreenCanvas::renderingContextFactories() -{ - DEFINE_STATIC_LOCAL(ContextFactoryVector, s_contextFactories, (OffscreenCanvasRenderingContext::ContextTypeCount)); - return s_contextFactories; -} - -OffscreenCanvasRenderingContextFactory* OffscreenCanvas::getRenderingContextFactory(int type) -{ - ASSERT(type < OffscreenCanvasRenderingContext::ContextTypeCount); - return renderingContextFactories()[type].get(); -} - -void OffscreenCanvas::registerRenderingContextFactory(PassOwnPtr<OffscreenCanvasRenderingContextFactory> renderingContextFactory) -{ - OffscreenCanvasRenderingContext::ContextType type = renderingContextFactory->getContextType(); - ASSERT(type < OffscreenCanvasRenderingContext::ContextTypeCount); - ASSERT(!renderingContextFactories()[type]); - renderingContextFactories()[type] = renderingContextFactory; -} - -DEFINE_TRACE(OffscreenCanvas) -{ - visitor->trace(m_context); - visitor->trace(m_canvas); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasModules.cpp b/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasModules.cpp new file mode 100644 index 0000000..2979dcba --- /dev/null +++ b/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasModules.cpp
@@ -0,0 +1,22 @@ +// 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 "modules/offscreencanvas/OffscreenCanvasModules.h" + +#include "core/html/canvas/CanvasContextCreationAttributes.h" +#include "core/offscreencanvas/OffscreenCanvas.h" +#include "modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.h" + +namespace blink { + +OffscreenCanvasRenderingContext2D* OffscreenCanvasModules::getContext(OffscreenCanvas& offscreenCanvas, const String& id, const CanvasContextCreationAttributes& attributes) +{ + CanvasRenderingContext* context = offscreenCanvas.getCanvasRenderingContext(id, attributes); + if (!context) + return nullptr; + + return static_cast<OffscreenCanvasRenderingContext2D*>(context); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasModules.h b/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasModules.h new file mode 100644 index 0000000..a35c36f --- /dev/null +++ b/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasModules.h
@@ -0,0 +1,27 @@ +// 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 OffscreenCanvasModules_h +#define OffscreenCanvasModules_h + +#include "modules/ModulesExport.h" +#include "wtf/Allocator.h" +#include "wtf/text/WTFString.h" + +namespace blink { + +class CanvasContextCreationAttributes; +class OffscreenCanvas; +class OffscreenCanvasRenderingContext2D; + +class MODULES_EXPORT OffscreenCanvasModules { + STATIC_ONLY(OffscreenCanvasModules) +public: + static OffscreenCanvasRenderingContext2D* getContext(OffscreenCanvas&, const String&, const CanvasContextCreationAttributes&); +}; + +} // namespace blink + +#endif // OffscreenCanvasModules_h +
diff --git a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasModules.idl b/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasModules.idl new file mode 100644 index 0000000..2d34f03b6 --- /dev/null +++ b/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasModules.idl
@@ -0,0 +1,9 @@ +// 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. + +typedef OffscreenCanvasRenderingContext2D OffscreenRenderingContext; + +partial interface OffscreenCanvas { + [RuntimeEnabled=ExperimentalCanvasFeatures] OffscreenRenderingContext? getContext(DOMString contextId, optional CanvasContextCreationAttributes attributes); +};
diff --git a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasRenderingContext.cpp b/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasRenderingContext.cpp deleted file mode 100644 index 5b3234c6..0000000 --- a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasRenderingContext.cpp +++ /dev/null
@@ -1,30 +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 "modules/offscreencanvas/OffscreenCanvasRenderingContext.h" - -namespace blink { - -OffscreenCanvasRenderingContext::OffscreenCanvasRenderingContext(OffscreenCanvas* canvas) - : m_offscreenCanvas(canvas) -{ -} - -OffscreenCanvasRenderingContext::ContextType OffscreenCanvasRenderingContext::contextTypeFromId(const String& id) -{ - if (id == "2d") - return Context2d; - if (id == "webgl") - return ContextWebgl; - if (id == "webgl2") - return ContextWebgl2; - return ContextTypeCount; -} - -DEFINE_TRACE(OffscreenCanvasRenderingContext) -{ - visitor->trace(m_offscreenCanvas); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasRenderingContext.h b/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasRenderingContext.h deleted file mode 100644 index 0eff273..0000000 --- a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasRenderingContext.h +++ /dev/null
@@ -1,43 +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 OffscreenCanvasRenderingContext_h -#define OffscreenCanvasRenderingContext_h - -#include "modules/ModulesExport.h" -#include "modules/offscreencanvas/OffscreenCanvas.h" - -namespace blink { - -class ImageBitmap; - -class MODULES_EXPORT OffscreenCanvasRenderingContext : public GarbageCollectedFinalized<OffscreenCanvasRenderingContext>, public ScriptWrappable { - WTF_MAKE_NONCOPYABLE(OffscreenCanvasRenderingContext); -public: - virtual ~OffscreenCanvasRenderingContext() { } - enum ContextType { - Context2d = 0, - ContextWebgl = 1, - ContextWebgl2 = 2, - ContextTypeCount - }; - static ContextType contextTypeFromId(const String& id); - - OffscreenCanvas* getOffscreenCanvas() const { return m_offscreenCanvas; } - virtual ContextType getContextType() const = 0; - virtual ImageBitmap* transferToImageBitmap(ExceptionState&) = 0; - - virtual bool is2d() const { return false; } - -protected: - OffscreenCanvasRenderingContext(OffscreenCanvas*); - DECLARE_VIRTUAL_TRACE(); - -private: - Member<OffscreenCanvas> m_offscreenCanvas; -}; - -} // namespace blink - -#endif // OffscreenCanvasRenderingContext_h
diff --git a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasRenderingContextFactory.h b/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasRenderingContextFactory.h deleted file mode 100644 index 3dd3498..0000000 --- a/third_party/WebKit/Source/modules/offscreencanvas/OffscreenCanvasRenderingContextFactory.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright (c) 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 OffscreenCanvasRenderingContextFactory_h -#define OffscreenCanvasRenderingContextFactory_h - -#include "wtf/Allocator.h" -#include "wtf/PassRefPtr.h" - -namespace blink { - -class CanvasContextCreationAttributes; -class OffscreenCanvas; -class OffscreenCanvasRenderingContext; - -class OffscreenCanvasRenderingContextFactory { - USING_FAST_MALLOC(OffscreenCanvasRenderingContextFactory); - WTF_MAKE_NONCOPYABLE(OffscreenCanvasRenderingContextFactory); -public: - OffscreenCanvasRenderingContextFactory() = default; - virtual ~OffscreenCanvasRenderingContextFactory() { } - - virtual OffscreenCanvasRenderingContext* create(OffscreenCanvas*, const CanvasContextCreationAttributes&) = 0; - virtual OffscreenCanvasRenderingContext::ContextType getContextType() const = 0; - virtual void onError(OffscreenCanvas*, const String& error) = 0; -}; - -} // namespace blink - -#endif // OffscreenCanvasRenderingContextFactory_h
diff --git a/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp b/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp index d5e85db..d8fc549 100644 --- a/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp +++ b/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp
@@ -19,14 +19,14 @@ } OffscreenCanvasRenderingContext2D::OffscreenCanvasRenderingContext2D(OffscreenCanvas* canvas, const CanvasContextCreationAttributes& attrs) - : OffscreenCanvasRenderingContext(canvas) + : CanvasRenderingContext(canvas) , m_hasAlpha(attrs.alpha()) { } DEFINE_TRACE(OffscreenCanvasRenderingContext2D) { - OffscreenCanvasRenderingContext::trace(visitor); + CanvasRenderingContext::trace(visitor); BaseRenderingContext2D::trace(visitor); }
diff --git a/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.h b/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.h index d3c80b8c..d358c39 100644 --- a/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.h +++ b/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.h
@@ -6,38 +6,42 @@ #define OffscreenCanvasRenderingContext2D_h #include "core/html/canvas/CanvasContextCreationAttributes.h" +#include "core/html/canvas/CanvasRenderingContext.h" +#include "core/html/canvas/CanvasRenderingContextFactory.h" #include "modules/canvas2d/BaseRenderingContext2D.h" -#include "modules/offscreencanvas/OffscreenCanvasRenderingContext.h" -#include "modules/offscreencanvas/OffscreenCanvasRenderingContextFactory.h" namespace blink { -class MODULES_EXPORT OffscreenCanvasRenderingContext2D final : public OffscreenCanvasRenderingContext, public BaseRenderingContext2D { +class HTMLCanvasElement; + +class MODULES_EXPORT OffscreenCanvasRenderingContext2D final : public CanvasRenderingContext, public BaseRenderingContext2D { DEFINE_WRAPPERTYPEINFO(); USING_GARBAGE_COLLECTED_MIXIN(OffscreenCanvasRenderingContext2D); public: - class Factory : public OffscreenCanvasRenderingContextFactory { + class Factory : public CanvasRenderingContextFactory { public: Factory() {} ~Factory() override {} - OffscreenCanvasRenderingContext* create(OffscreenCanvas* canvas, const CanvasContextCreationAttributes& attrs) override + CanvasRenderingContext* create(OffscreenCanvas* canvas, const CanvasContextCreationAttributes& attrs) override { return new OffscreenCanvasRenderingContext2D(canvas, attrs); } - OffscreenCanvasRenderingContext::ContextType getContextType() const override + CanvasRenderingContext::ContextType getContextType() const override { - return OffscreenCanvasRenderingContext::Context2d; + return CanvasRenderingContext::Context2d; } - - void onError(OffscreenCanvas* canvas, const String& error) override {} }; - // OffscreenCanvasRenderingContext implementation + // CanvasRenderingContext implementation ~OffscreenCanvasRenderingContext2D() override; ContextType getContextType() const override { return Context2d; } bool is2d() const override { return true; } + void setIsHidden(bool) final { ASSERT_NOT_REACHED(); } + void stop() final { ASSERT_NOT_REACHED(); } + void setCanvasGetContextResult(RenderingContext&) final {} + void clearRect(double x, double y, double width, double height) override { BaseRenderingContext2D::clearRect(x, y, width, height); } // BaseRenderingContext2D implementation bool originClean() const final;
diff --git a/third_party/WebKit/Source/modules/permissions/PermissionsCallback.cpp b/third_party/WebKit/Source/modules/permissions/PermissionsCallback.cpp index c850718..b60a017 100644 --- a/third_party/WebKit/Source/modules/permissions/PermissionsCallback.cpp +++ b/third_party/WebKit/Source/modules/permissions/PermissionsCallback.cpp
@@ -10,9 +10,9 @@ namespace blink { PermissionsCallback::PermissionsCallback(ScriptPromiseResolver* resolver, PassOwnPtr<Vector<WebPermissionType>> internalPermissions, PassOwnPtr<Vector<int>> callerIndexToInternalIndex) - : m_resolver(resolver), - m_internalPermissions(internalPermissions), - m_callerIndexToInternalIndex(callerIndexToInternalIndex) + : m_resolver(resolver) + , m_internalPermissions(std::move(internalPermissions)) + , m_callerIndexToInternalIndex(std::move(callerIndexToInternalIndex)) { ASSERT(m_resolver); }
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp b/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp index a8f8806..a2f0dfa 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp
@@ -186,7 +186,7 @@ if (!controller) return nullptr; - return take(controller, client, request); + return take(controller, std::move(client), request); } // static
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorker.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorker.cpp index aa39db2..2c549bb4 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorker.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorker.cpp
@@ -114,7 +114,7 @@ ServiceWorker* ServiceWorker::from(ExecutionContext* executionContext, PassOwnPtr<WebServiceWorker::Handle> handle) { - return getOrCreate(executionContext, handle); + return getOrCreate(executionContext, std::move(handle)); } bool ServiceWorker::hasPendingActivity() const @@ -140,7 +140,7 @@ return existingWorker; } - ServiceWorker* newWorker = new ServiceWorker(executionContext, handle); + ServiceWorker* newWorker = new ServiceWorker(executionContext, std::move(handle)); newWorker->suspendIfNeeded(); return newWorker; } @@ -148,7 +148,7 @@ ServiceWorker::ServiceWorker(ExecutionContext* executionContext, PassOwnPtr<WebServiceWorker::Handle> handle) : AbstractWorker(executionContext) , ActiveScriptWrappable(this) - , m_handle(handle) + , m_handle(std::move(handle)) , m_wasStopped(false) { ASSERT(m_handle);
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainerClient.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainerClient.cpp index 62b071b6..8842166 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainerClient.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainerClient.cpp
@@ -15,11 +15,11 @@ ServiceWorkerContainerClient* ServiceWorkerContainerClient::create(PassOwnPtr<WebServiceWorkerProvider> provider) { - return new ServiceWorkerContainerClient(provider); + return new ServiceWorkerContainerClient(std::move(provider)); } ServiceWorkerContainerClient::ServiceWorkerContainerClient(PassOwnPtr<WebServiceWorkerProvider> provider) - : m_provider(provider) + : m_provider(std::move(provider)) { } @@ -53,7 +53,7 @@ void provideServiceWorkerContainerClientToWorker(WorkerClients* clients, PassOwnPtr<WebServiceWorkerProvider> provider) { - clients->provideSupplement(ServiceWorkerContainerClient::supplementName(), ServiceWorkerContainerClient::create(provider)); + clients->provideSupplement(ServiceWorkerContainerClient::supplementName(), ServiceWorkerContainerClient::create(std::move(provider))); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainerTest.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainerTest.cpp index 5b4fa59..bcccc7a 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainerTest.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainerTest.cpp
@@ -164,7 +164,7 @@ void provide(PassOwnPtr<WebServiceWorkerProvider> provider) { - Supplement<Document>::provideTo(m_page->document(), ServiceWorkerContainerClient::supplementName(), ServiceWorkerContainerClient::create(provider)); + Supplement<Document>::provideTo(m_page->document(), ServiceWorkerContainerClient::supplementName(), ServiceWorkerContainerClient::create(std::move(provider))); } void setPageURL(const String& url)
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.cpp index 7e8513e..4da396d 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.cpp
@@ -78,7 +78,7 @@ } ServiceWorkerGlobalScope::ServiceWorkerGlobalScope(const KURL& url, const String& userAgent, ServiceWorkerThread* thread, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilegeData, WorkerClients* workerClients) - : WorkerGlobalScope(url, userAgent, thread, timeOrigin, starterOriginPrivilegeData, workerClients) + : WorkerGlobalScope(url, userAgent, thread, timeOrigin, std::move(starterOriginPrivilegeData), workerClients) , m_didEvaluateScript(false) , m_hadErrorInTopLevelEventHandler(false) , m_eventNestingLevel(0)
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerRegistration.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerRegistration.cpp index ee5bc055..48ed65acc 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerRegistration.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerRegistration.cpp
@@ -59,7 +59,7 @@ return existingRegistration; } - ServiceWorkerRegistration* newRegistration = new ServiceWorkerRegistration(executionContext, handle); + ServiceWorkerRegistration* newRegistration = new ServiceWorkerRegistration(executionContext, std::move(handle)); newRegistration->suspendIfNeeded(); return newRegistration; } @@ -100,7 +100,7 @@ ServiceWorkerRegistration::ServiceWorkerRegistration(ExecutionContext* executionContext, PassOwnPtr<WebServiceWorkerRegistration::Handle> handle) : ActiveScriptWrappable(this) , ActiveDOMObject(executionContext) - , m_handle(handle) + , m_handle(std::move(handle)) , m_provider(nullptr) , m_stopped(false) {
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.cpp index efa391c..933be5c 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.cpp
@@ -53,7 +53,7 @@ WorkerGlobalScope* ServiceWorkerThread::createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData) { - return ServiceWorkerGlobalScope::create(this, startupData); + return ServiceWorkerGlobalScope::create(this, std::move(startupData)); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/speech/SpeechRecognitionController.cpp b/third_party/WebKit/Source/modules/speech/SpeechRecognitionController.cpp index 0a6d094c..7867771 100644 --- a/third_party/WebKit/Source/modules/speech/SpeechRecognitionController.cpp +++ b/third_party/WebKit/Source/modules/speech/SpeechRecognitionController.cpp
@@ -33,7 +33,7 @@ } SpeechRecognitionController::SpeechRecognitionController(PassOwnPtr<SpeechRecognitionClient> client) - : m_client(client) + : m_client(std::move(client)) { } @@ -44,12 +44,12 @@ SpeechRecognitionController* SpeechRecognitionController::create(PassOwnPtr<SpeechRecognitionClient> client) { - return new SpeechRecognitionController(client); + return new SpeechRecognitionController(std::move(client)); } void provideSpeechRecognitionTo(Page& page, PassOwnPtr<SpeechRecognitionClient> client) { - SpeechRecognitionController::provideTo(page, SpeechRecognitionController::supplementName(), SpeechRecognitionController::create(client)); + SpeechRecognitionController::provideTo(page, SpeechRecognitionController::supplementName(), SpeechRecognitionController::create(std::move(client))); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/storage/InspectorDOMStorageAgent.cpp b/third_party/WebKit/Source/modules/storage/InspectorDOMStorageAgent.cpp index 91dd2155..51594694 100644 --- a/third_party/WebKit/Source/modules/storage/InspectorDOMStorageAgent.cpp +++ b/third_party/WebKit/Source/modules/storage/InspectorDOMStorageAgent.cpp
@@ -110,7 +110,7 @@ void InspectorDOMStorageAgent::getDOMStorageItems(ErrorString* errorString, PassOwnPtr<protocol::DOMStorage::StorageId> storageId, OwnPtr<protocol::Array<protocol::Array<String>>>* items) { LocalFrame* frame; - StorageArea* storageArea = findStorageArea(errorString, storageId, frame); + StorageArea* storageArea = findStorageArea(errorString, std::move(storageId), frame); if (!storageArea) return; @@ -142,7 +142,7 @@ void InspectorDOMStorageAgent::setDOMStorageItem(ErrorString* errorString, PassOwnPtr<protocol::DOMStorage::StorageId> storageId, const String& key, const String& value) { LocalFrame* frame; - StorageArea* storageArea = findStorageArea(0, storageId, frame); + StorageArea* storageArea = findStorageArea(0, std::move(storageId), frame); if (!storageArea) { *errorString = "Storage not found"; return; @@ -156,7 +156,7 @@ void InspectorDOMStorageAgent::removeDOMStorageItem(ErrorString* errorString, PassOwnPtr<protocol::DOMStorage::StorageId> storageId, const String& key) { LocalFrame* frame; - StorageArea* storageArea = findStorageArea(0, storageId, frame); + StorageArea* storageArea = findStorageArea(0, std::move(storageId), frame); if (!storageArea) { *errorString = "Storage not found"; return;
diff --git a/third_party/WebKit/Source/modules/storage/StorageArea.cpp b/third_party/WebKit/Source/modules/storage/StorageArea.cpp index c92f402..ca5f398 100644 --- a/third_party/WebKit/Source/modules/storage/StorageArea.cpp +++ b/third_party/WebKit/Source/modules/storage/StorageArea.cpp
@@ -48,12 +48,12 @@ StorageArea* StorageArea::create(PassOwnPtr<WebStorageArea> storageArea, StorageType storageType) { - return new StorageArea(storageArea, storageType); + return new StorageArea(std::move(storageArea), storageType); } StorageArea::StorageArea(PassOwnPtr<WebStorageArea> storageArea, StorageType storageType) : LocalFrameLifecycleObserver(nullptr) - , m_storageArea(storageArea) + , m_storageArea(std::move(storageArea)) , m_storageType(storageType) , m_canAccessStorageCachedResult(false) {
diff --git a/third_party/WebKit/Source/modules/storage/StorageNamespace.cpp b/third_party/WebKit/Source/modules/storage/StorageNamespace.cpp index 60d0744..60f68693 100644 --- a/third_party/WebKit/Source/modules/storage/StorageNamespace.cpp +++ b/third_party/WebKit/Source/modules/storage/StorageNamespace.cpp
@@ -34,7 +34,7 @@ namespace blink { StorageNamespace::StorageNamespace(PassOwnPtr<WebStorageNamespace> webStorageNamespace) - : m_webStorageNamespace(webStorageNamespace) + : m_webStorageNamespace(std::move(webStorageNamespace)) { }
diff --git a/third_party/WebKit/Source/modules/vr/VRHardwareUnitCollection.cpp b/third_party/WebKit/Source/modules/vr/VRHardwareUnitCollection.cpp index cfcb2de..830cac0 100644 --- a/third_party/WebKit/Source/modules/vr/VRHardwareUnitCollection.cpp +++ b/third_party/WebKit/Source/modules/vr/VRHardwareUnitCollection.cpp
@@ -6,7 +6,6 @@ #include "bindings/core/v8/ScriptPromiseResolver.h" #include "core/dom/Document.h" -#include "core/dom/ExceptionCode.h" #include "core/frame/LocalDOMWindow.h" #include "core/frame/LocalFrame.h" #include "core/frame/Navigator.h"
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioBasicProcessorHandler.cpp b/third_party/WebKit/Source/modules/webaudio/AudioBasicProcessorHandler.cpp index 8d3970cf..9e6cc6a 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioBasicProcessorHandler.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioBasicProcessorHandler.cpp
@@ -32,7 +32,7 @@ AudioBasicProcessorHandler::AudioBasicProcessorHandler(NodeType nodeType, AudioNode& node, float sampleRate, PassOwnPtr<AudioProcessor> processor) : AudioHandler(nodeType, node, sampleRate) - , m_processor(processor) + , m_processor(std::move(processor)) { addInput(); addOutput(1); @@ -40,7 +40,7 @@ PassRefPtr<AudioBasicProcessorHandler> AudioBasicProcessorHandler::create(NodeType nodeType, AudioNode& node, float sampleRate, PassOwnPtr<AudioProcessor> processor) { - return adoptRef(new AudioBasicProcessorHandler(nodeType, node, sampleRate, processor)); + return adoptRef(new AudioBasicProcessorHandler(nodeType, node, sampleRate, std::move(processor))); } AudioBasicProcessorHandler::~AudioBasicProcessorHandler()
diff --git a/third_party/WebKit/Source/modules/webaudio/MediaStreamAudioSourceNode.cpp b/third_party/WebKit/Source/modules/webaudio/MediaStreamAudioSourceNode.cpp index 573270f3..860dd15b 100644 --- a/third_party/WebKit/Source/modules/webaudio/MediaStreamAudioSourceNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/MediaStreamAudioSourceNode.cpp
@@ -34,7 +34,7 @@ : AudioHandler(NodeTypeMediaStreamAudioSource, node, node.context()->sampleRate()) , m_mediaStream(mediaStream) , m_audioTrack(audioTrack) - , m_audioSourceProvider(audioSourceProvider) + , m_audioSourceProvider(std::move(audioSourceProvider)) , m_sourceNumberOfChannels(0) { // Default to stereo. This could change depending on the format of the @@ -46,7 +46,7 @@ PassRefPtr<MediaStreamAudioSourceHandler> MediaStreamAudioSourceHandler::create(AudioNode& node, MediaStream& mediaStream, MediaStreamTrack* audioTrack, PassOwnPtr<AudioSourceProvider> audioSourceProvider) { - return adoptRef(new MediaStreamAudioSourceHandler(node, mediaStream, audioTrack, audioSourceProvider)); + return adoptRef(new MediaStreamAudioSourceHandler(node, mediaStream, audioTrack, std::move(audioSourceProvider))); } MediaStreamAudioSourceHandler::~MediaStreamAudioSourceHandler() @@ -111,12 +111,12 @@ MediaStreamAudioSourceNode::MediaStreamAudioSourceNode(AbstractAudioContext& context, MediaStream& mediaStream, MediaStreamTrack* audioTrack, PassOwnPtr<AudioSourceProvider> audioSourceProvider) : AudioSourceNode(context) { - setHandler(MediaStreamAudioSourceHandler::create(*this, mediaStream, audioTrack, audioSourceProvider)); + setHandler(MediaStreamAudioSourceHandler::create(*this, mediaStream, audioTrack, std::move(audioSourceProvider))); } MediaStreamAudioSourceNode* MediaStreamAudioSourceNode::create(AbstractAudioContext& context, MediaStream& mediaStream, MediaStreamTrack* audioTrack, PassOwnPtr<AudioSourceProvider> audioSourceProvider) { - return new MediaStreamAudioSourceNode(context, mediaStream, audioTrack, audioSourceProvider); + return new MediaStreamAudioSourceNode(context, mediaStream, audioTrack, std::move(audioSourceProvider)); } DEFINE_TRACE(MediaStreamAudioSourceNode)
diff --git a/third_party/WebKit/Source/modules/webdatabase/Database.cpp b/third_party/WebKit/Source/modules/webdatabase/Database.cpp index 1347d9a..16d6ab1 100644 --- a/third_party/WebKit/Source/modules/webdatabase/Database.cpp +++ b/third_party/WebKit/Source/modules/webdatabase/Database.cpp
@@ -836,7 +836,7 @@ ASSERT(callback == originalErrorCallback); if (callback) { OwnPtr<SQLErrorData> error = SQLErrorData::create(SQLError::UNKNOWN_ERR, "database has been closed"); - getExecutionContext()->postTask(BLINK_FROM_HERE, createSameThreadTask(&callTransactionErrorCallback, callback, error.release())); + getExecutionContext()->postTask(BLINK_FROM_HERE, createSameThreadTask(&callTransactionErrorCallback, callback, passed(error.release()))); } } }
diff --git a/third_party/WebKit/Source/modules/webdatabase/DatabaseThread.cpp b/third_party/WebKit/Source/modules/webdatabase/DatabaseThread.cpp index ed5a4f23..d49a612 100644 --- a/third_party/WebKit/Source/modules/webdatabase/DatabaseThread.cpp +++ b/third_party/WebKit/Source/modules/webdatabase/DatabaseThread.cpp
@@ -169,7 +169,7 @@ } #endif // WebThread takes ownership of the task. - m_thread->postTask(BLINK_FROM_HERE, threadSafeBind(&DatabaseTask::run, task)); + m_thread->postTask(BLINK_FROM_HERE, threadSafeBind(&DatabaseTask::run, std::move(task))); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/webdatabase/InspectorDatabaseAgent.cpp b/third_party/WebKit/Source/modules/webdatabase/InspectorDatabaseAgent.cpp index 2281d98..7edd195 100644 --- a/third_party/WebKit/Source/modules/webdatabase/InspectorDatabaseAgent.cpp +++ b/third_party/WebKit/Source/modules/webdatabase/InspectorDatabaseAgent.cpp
@@ -62,7 +62,7 @@ class ExecuteSQLCallbackWrapper : public RefCounted<ExecuteSQLCallbackWrapper> { public: - static PassRefPtr<ExecuteSQLCallbackWrapper> create(PassOwnPtr<ExecuteSQLCallback> callback) { return adoptRef(new ExecuteSQLCallbackWrapper(callback)); } + static PassRefPtr<ExecuteSQLCallbackWrapper> create(PassOwnPtr<ExecuteSQLCallback> callback) { return adoptRef(new ExecuteSQLCallbackWrapper(std::move(callback))); } ~ExecuteSQLCallbackWrapper() { } ExecuteSQLCallback* get() { return m_callback.get(); } @@ -75,7 +75,7 @@ } private: - explicit ExecuteSQLCallbackWrapper(PassOwnPtr<ExecuteSQLCallback> callback) : m_callback(callback) { } + explicit ExecuteSQLCallbackWrapper(PassOwnPtr<ExecuteSQLCallback> callback) : m_callback(std::move(callback)) { } OwnPtr<ExecuteSQLCallback> m_callback; }; @@ -307,7 +307,7 @@ void InspectorDatabaseAgent::executeSQL(ErrorString*, const String& databaseId, const String& query, PassOwnPtr<ExecuteSQLCallback> prpRequestCallback) { - OwnPtr<ExecuteSQLCallback> requestCallback = prpRequestCallback; + OwnPtr<ExecuteSQLCallback> requestCallback = std::move(prpRequestCallback); if (!m_enabled) { requestCallback->sendFailure("Database agent is not enabled");
diff --git a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContext.cpp b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContext.cpp index a2767a08..671319c 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContext.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContext.cpp
@@ -69,7 +69,7 @@ } WebGL2RenderingContext::WebGL2RenderingContext(HTMLCanvasElement* passedCanvas, PassOwnPtr<WebGraphicsContext3DProvider> contextProvider, const WebGLContextAttributes& requestedAttributes) - : WebGL2RenderingContextBase(passedCanvas, contextProvider, requestedAttributes) + : WebGL2RenderingContextBase(passedCanvas, std::move(contextProvider), requestedAttributes) { }
diff --git a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp index 7923895..78c2559 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp
@@ -116,7 +116,7 @@ }; WebGL2RenderingContextBase::WebGL2RenderingContextBase(HTMLCanvasElement* passedCanvas, PassOwnPtr<WebGraphicsContext3DProvider> contextProvider, const WebGLContextAttributes& requestedAttributes) - : WebGLRenderingContextBase(passedCanvas, contextProvider, requestedAttributes) + : WebGLRenderingContextBase(passedCanvas, std::move(contextProvider), requestedAttributes) { m_supportedInternalFormatsStorage.insert(kSupportedInternalFormatsStorage, kSupportedInternalFormatsStorage + WTF_ARRAY_LENGTH(kSupportedInternalFormatsStorage)); m_supportedInternalFormatsStorage.insert(kCompressedTextureFormatsETC2EAC, kCompressedTextureFormatsETC2EAC + WTF_ARRAY_LENGTH(kCompressedTextureFormatsETC2EAC));
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContext.cpp b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContext.cpp index b55b2256..abd64cd 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContext.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContext.cpp
@@ -99,7 +99,7 @@ } WebGLRenderingContext::WebGLRenderingContext(HTMLCanvasElement* passedCanvas, PassOwnPtr<WebGraphicsContext3DProvider> contextProvider, const WebGLContextAttributes& requestedAttributes) - : WebGLRenderingContextBase(passedCanvas, contextProvider, requestedAttributes) + : WebGLRenderingContextBase(passedCanvas, std::move(contextProvider), requestedAttributes) { }
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp index c9463771d..999af82 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp
@@ -30,7 +30,6 @@ #include "bindings/modules/v8/WebGLAny.h" #include "core/dom/DOMArrayBuffer.h" #include "core/dom/DOMTypedArray.h" -#include "core/dom/ExceptionCode.h" #include "core/dom/FlexibleArrayBufferView.h" #include "core/fetch/ImageResource.h" #include "core/frame/ImageBitmap.h" @@ -810,7 +809,7 @@ m_maxViewportDims[0] = m_maxViewportDims[1] = 0; contextProvider->contextGL()->GetIntegerv(GL_MAX_VIEWPORT_DIMS, m_maxViewportDims); - RefPtr<DrawingBuffer> buffer = createDrawingBuffer(contextProvider); + RefPtr<DrawingBuffer> buffer = createDrawingBuffer(std::move(contextProvider)); if (!buffer) { m_contextLostMode = SyntheticLostContext; return; @@ -841,7 +840,7 @@ bool wantAntialiasing = m_requestedAttributes.antialias(); DrawingBuffer::PreserveDrawingBuffer preserve = m_requestedAttributes.preserveDrawingBuffer() ? DrawingBuffer::Preserve : DrawingBuffer::Discard; return DrawingBuffer::create( - contextProvider, + std::move(contextProvider), clampedCanvasSize(), premultipliedAlpha, wantAlphaChannel,
diff --git a/third_party/WebKit/Source/modules/webmidi/MIDIAccess.cpp b/third_party/WebKit/Source/modules/webmidi/MIDIAccess.cpp index 425997d3..342fd3f 100644 --- a/third_party/WebKit/Source/modules/webmidi/MIDIAccess.cpp +++ b/third_party/WebKit/Source/modules/webmidi/MIDIAccess.cpp
@@ -50,7 +50,7 @@ MIDIAccess::MIDIAccess(PassOwnPtr<MIDIAccessor> accessor, bool sysexEnabled, const Vector<MIDIAccessInitializer::PortDescriptor>& ports, ExecutionContext* executionContext) : ActiveScriptWrappable(this) , ActiveDOMObject(executionContext) - , m_accessor(accessor) + , m_accessor(std::move(accessor)) , m_sysexEnabled(sysexEnabled) , m_hasPendingActivity(false) {
diff --git a/third_party/WebKit/Source/modules/webmidi/MIDIAccess.h b/third_party/WebKit/Source/modules/webmidi/MIDIAccess.h index c930c93e..6484a205 100644 --- a/third_party/WebKit/Source/modules/webmidi/MIDIAccess.h +++ b/third_party/WebKit/Source/modules/webmidi/MIDIAccess.h
@@ -56,7 +56,7 @@ public: static MIDIAccess* create(PassOwnPtr<MIDIAccessor> accessor, bool sysexEnabled, const Vector<MIDIAccessInitializer::PortDescriptor>& ports, ExecutionContext* executionContext) { - MIDIAccess* access = new MIDIAccess(accessor, sysexEnabled, ports, executionContext); + MIDIAccess* access = new MIDIAccess(std::move(accessor), sysexEnabled, ports, executionContext); access->suspendIfNeeded(); return access; }
diff --git a/third_party/WebKit/Source/modules/webmidi/MIDIController.cpp b/third_party/WebKit/Source/modules/webmidi/MIDIController.cpp index d76b6b6..8ea0a21 100644 --- a/third_party/WebKit/Source/modules/webmidi/MIDIController.cpp +++ b/third_party/WebKit/Source/modules/webmidi/MIDIController.cpp
@@ -41,7 +41,7 @@ } MIDIController::MIDIController(PassOwnPtr<MIDIClient> client) - : m_client(client) + : m_client(std::move(client)) { DCHECK(m_client); } @@ -52,7 +52,7 @@ MIDIController* MIDIController::create(PassOwnPtr<MIDIClient> client) { - return new MIDIController(client); + return new MIDIController(std::move(client)); } void MIDIController::requestPermission(MIDIAccessInitializer* initializer, const MIDIOptions& options) @@ -67,7 +67,7 @@ void provideMIDITo(LocalFrame& frame, PassOwnPtr<MIDIClient> client) { - MIDIController::provideTo(frame, MIDIController::supplementName(), MIDIController::create(client)); + MIDIController::provideTo(frame, MIDIController::supplementName(), MIDIController::create(std::move(client))); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/websockets/DOMWebSocketTest.cpp b/third_party/WebKit/Source/modules/websockets/DOMWebSocketTest.cpp index 1010e7a..3ff23ec 100644 --- a/third_party/WebKit/Source/modules/websockets/DOMWebSocketTest.cpp +++ b/third_party/WebKit/Source/modules/websockets/DOMWebSocketTest.cpp
@@ -50,8 +50,16 @@ MOCK_METHOD1(send, void(const CString&)); MOCK_METHOD3(send, void(const DOMArrayBuffer&, unsigned, unsigned)); MOCK_METHOD1(send, void(PassRefPtr<BlobDataHandle>)); - MOCK_METHOD1(sendTextAsCharVector, void(PassOwnPtr<Vector<char>>)); - MOCK_METHOD1(sendBinaryAsCharVector, void(PassOwnPtr<Vector<char>>)); + MOCK_METHOD1(sendTextAsCharVectorMock, void(Vector<char>*)); + void sendTextAsCharVector(PassOwnPtr<Vector<char>> vector) + { + sendTextAsCharVectorMock(vector.get()); + } + MOCK_METHOD1(sendBinaryAsCharVectorMock, void(Vector<char>*)); + void sendBinaryAsCharVector(PassOwnPtr<Vector<char>> vector) + { + sendBinaryAsCharVectorMock(vector.get()); + } MOCK_CONST_METHOD0(bufferedAmount, unsigned()); MOCK_METHOD2(close, void(int, const String&)); MOCK_METHOD4(fail, void(const String&, MessageLevel, const String&, unsigned));
diff --git a/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannel.cpp b/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannel.cpp index 25a282a8..10e7c02 100644 --- a/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannel.cpp +++ b/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannel.cpp
@@ -233,7 +233,7 @@ // FIXME: Change the inspector API to show the entire message instead // of individual frames. InspectorInstrumentation::didSendWebSocketFrame(document(), m_identifier, WebSocketFrame::OpCodeText, true, data->data(), data->size()); - m_messages.append(new Message(data, MessageTypeTextAsCharVector)); + m_messages.append(new Message(std::move(data), MessageTypeTextAsCharVector)); processSendQueue(); } @@ -243,7 +243,7 @@ // FIXME: Change the inspector API to show the entire message instead // of individual frames. InspectorInstrumentation::didSendWebSocketFrame(document(), m_identifier, WebSocketFrame::OpCodeBinary, true, data->data(), data->size()); - m_messages.append(new Message(data, MessageTypeBinaryAsCharVector)); + m_messages.append(new Message(std::move(data), MessageTypeBinaryAsCharVector)); processSendQueue(); } @@ -300,7 +300,7 @@ DocumentWebSocketChannel::Message::Message(PassOwnPtr<Vector<char>> vectorData, MessageType type) : type(type) - , vectorData(vectorData) + , vectorData(std::move(vectorData)) { ASSERT(type == MessageTypeTextAsCharVector || type == MessageTypeBinaryAsCharVector); }
diff --git a/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp b/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp index 1fb4579..f9ac89b 100644 --- a/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp +++ b/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp
@@ -61,7 +61,7 @@ public: static WebSocketChannelSyncHelper* create(PassOwnPtr<WaitableEvent> event) { - return new WebSocketChannelSyncHelper(event); + return new WebSocketChannelSyncHelper(std::move(event)); } ~WebSocketChannelSyncHelper() @@ -95,7 +95,7 @@ private: explicit WebSocketChannelSyncHelper(PassOwnPtr<WaitableEvent> event) - : m_event(event) + : m_event(std::move(event)) , m_connectRequestResult(false) { } @@ -219,14 +219,14 @@ { ASSERT(isMainThread()); if (m_mainWebSocketChannel) - m_mainWebSocketChannel->sendTextAsCharVector(data); + m_mainWebSocketChannel->sendTextAsCharVector(std::move(data)); } void Peer::sendBinaryAsCharVector(PassOwnPtr<Vector<char>> data) { ASSERT(isMainThread()); if (m_mainWebSocketChannel) - m_mainWebSocketChannel->sendBinaryAsCharVector(data); + m_mainWebSocketChannel->sendBinaryAsCharVector(std::move(data)); } void Peer::sendBlob(PassRefPtr<BlobDataHandle> blobData) @@ -295,13 +295,13 @@ { ASSERT_UNUSED(context, context->isWorkerGlobalScope()); if (bridge->client()) - bridge->client()->didReceiveBinaryMessage(payload); + bridge->client()->didReceiveBinaryMessage(std::move(payload)); } void Peer::didReceiveBinaryMessage(PassOwnPtr<Vector<char>> payload) { ASSERT(isMainThread()); - m_loaderProxy->postTaskToWorkerGlobalScope(createCrossThreadTask(&workerGlobalScopeDidReceiveBinaryMessage, m_bridge, payload)); + m_loaderProxy->postTaskToWorkerGlobalScope(createCrossThreadTask(&workerGlobalScopeDidReceiveBinaryMessage, m_bridge, passed(std::move(payload)))); } static void workerGlobalScopeDidConsumeBufferedAmount(Bridge* bridge, uint64_t consumed, ExecutionContext* context) @@ -408,7 +408,7 @@ if (message.length()) memcpy(data->data(), static_cast<const char*>(message.data()), message.length()); - m_loaderProxy->postTaskToLoader(createCrossThreadTask(&Peer::sendTextAsCharVector, m_peer.get(), data.release())); + m_loaderProxy->postTaskToLoader(createCrossThreadTask(&Peer::sendTextAsCharVector, m_peer.get(), passed(data.release()))); } void Bridge::send(const DOMArrayBuffer& binaryData, unsigned byteOffset, unsigned byteLength) @@ -419,7 +419,7 @@ if (binaryData.byteLength()) memcpy(data->data(), static_cast<const char*>(binaryData.data()) + byteOffset, byteLength); - m_loaderProxy->postTaskToLoader(createCrossThreadTask(&Peer::sendBinaryAsCharVector, m_peer.get(), data.release())); + m_loaderProxy->postTaskToLoader(createCrossThreadTask(&Peer::sendBinaryAsCharVector, m_peer.get(), passed(data.release()))); } void Bridge::send(PassRefPtr<BlobDataHandle> data) @@ -462,7 +462,7 @@ ASSERT(m_workerGlobalScope); ASSERT(m_syncHelper); - m_loaderProxy->postTaskToLoader(task); + m_loaderProxy->postTaskToLoader(std::move(task)); // We wait for the syncHelper event even if a shutdown event is fired. // See https://codereview.chromium.org/267323004/#msg43 for why we need to wait this.
diff --git a/third_party/WebKit/Source/modules/webusb/USBEndpoint.cpp b/third_party/WebKit/Source/modules/webusb/USBEndpoint.cpp index 69879f42..f645b0e 100644 --- a/third_party/WebKit/Source/modules/webusb/USBEndpoint.cpp +++ b/third_party/WebKit/Source/modules/webusb/USBEndpoint.cpp
@@ -6,7 +6,6 @@ #include "bindings/core/v8/ExceptionState.h" #include "core/dom/DOMException.h" -#include "core/dom/ExceptionCode.h" #include "device/usb/public/interfaces/device.mojom-wtf.h" #include "modules/webusb/USBAlternateInterface.h"
diff --git a/third_party/WebKit/Source/platform/WebThreadSupportingGC.cpp b/third_party/WebKit/Source/platform/WebThreadSupportingGC.cpp index a0d4ad3..00f39c38 100644 --- a/third_party/WebKit/Source/platform/WebThreadSupportingGC.cpp +++ b/third_party/WebKit/Source/platform/WebThreadSupportingGC.cpp
@@ -10,19 +10,18 @@ namespace blink { -PassOwnPtr<WebThreadSupportingGC> WebThreadSupportingGC::create(const char* name, bool perThreadHeapEnabled) +PassOwnPtr<WebThreadSupportingGC> WebThreadSupportingGC::create(const char* name) { - return adoptPtr(new WebThreadSupportingGC(name, nullptr, perThreadHeapEnabled)); + return adoptPtr(new WebThreadSupportingGC(name, nullptr)); } -PassOwnPtr<WebThreadSupportingGC> WebThreadSupportingGC::createForThread(WebThread* thread, bool perThreadHeapEnabled) +PassOwnPtr<WebThreadSupportingGC> WebThreadSupportingGC::createForThread(WebThread* thread) { - return adoptPtr(new WebThreadSupportingGC(nullptr, thread, perThreadHeapEnabled)); + return adoptPtr(new WebThreadSupportingGC(nullptr, thread)); } -WebThreadSupportingGC::WebThreadSupportingGC(const char* name, WebThread* thread, bool perThreadHeapEnabled) +WebThreadSupportingGC::WebThreadSupportingGC(const char* name, WebThread* thread) : m_thread(thread) - , m_perThreadHeapEnabled(perThreadHeapEnabled) { #if ENABLE(ASSERT) ASSERT(!name || !thread); @@ -48,7 +47,7 @@ void WebThreadSupportingGC::initialize() { - ThreadState::attachCurrentThread(m_perThreadHeapEnabled); + ThreadState::attachCurrentThread(); m_gcTaskRunner = adoptPtr(new GCTaskRunner(m_thread)); }
diff --git a/third_party/WebKit/Source/platform/WebThreadSupportingGC.h b/third_party/WebKit/Source/platform/WebThreadSupportingGC.h index b64835ba..32ea91a 100644 --- a/third_party/WebKit/Source/platform/WebThreadSupportingGC.h +++ b/third_party/WebKit/Source/platform/WebThreadSupportingGC.h
@@ -29,8 +29,8 @@ USING_FAST_MALLOC(WebThreadSupportingGC); WTF_MAKE_NONCOPYABLE(WebThreadSupportingGC); public: - static PassOwnPtr<WebThreadSupportingGC> create(const char* name, bool perThreadHeapEnabled = false); - static PassOwnPtr<WebThreadSupportingGC> createForThread(WebThread*, bool perThreadHeapEnabled = false); + static PassOwnPtr<WebThreadSupportingGC> create(const char* name); + static PassOwnPtr<WebThreadSupportingGC> createForThread(WebThread*); ~WebThreadSupportingGC(); void postTask(const WebTraceLocation& location, PassOwnPtr<SameThreadClosure> task) @@ -78,7 +78,7 @@ } private: - WebThreadSupportingGC(const char* name, WebThread*, bool perThreadHeapEnabled); + WebThreadSupportingGC(const char* name, WebThread*); OwnPtr<GCTaskRunner> m_gcTaskRunner; @@ -87,7 +87,6 @@ // existing thread via createForThread(). WebThread* m_thread = nullptr; OwnPtr<WebThread> m_owningThread; - bool m_perThreadHeapEnabled; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/heap/Handle.h b/third_party/WebKit/Source/platform/heap/Handle.h index 7a42f169..292897f 100644 --- a/third_party/WebKit/Source/platform/heap/Handle.h +++ b/third_party/WebKit/Source/platform/heap/Handle.h
@@ -181,17 +181,23 @@ return *this; } -#if defined(LEAK_SANITIZER) + // Register the persistent node as a 'static reference', + // belonging to the current thread and a persistent that must + // be cleared when the ThreadState itself is cleared out and + // destructed. + // + // Static singletons arrange for this to happen, either to ensure + // clean LSan leak reports or to register a thread-local persistent + // needing to be cleared out before the thread is terminated. PersistentBase* registerAsStaticReference() { if (m_persistentNode) { ASSERT(ThreadState::current()); - ThreadState::current()->registerStaticPersistentNode(m_persistentNode); + ThreadState::current()->registerStaticPersistentNode(m_persistentNode, nullptr); LEAK_SANITIZER_IGNORE_OBJECT(this); } return this; } -#endif protected: T* atomicGet() { return reinterpret_cast<T*>(acquireLoad(reinterpret_cast<void* volatile*>(&m_raw))); } @@ -246,7 +252,7 @@ ASSERT(state->checkThread()); // Persistent handle must be created and destructed in the same thread. ASSERT(m_state == state); - state->getPersistentRegion()->freePersistentNode(m_persistentNode); + state->freePersistentNode(m_persistentNode); } m_persistentNode = nullptr; } @@ -329,33 +335,6 @@ Parent::operator=(other); return *this; } - - // Requests that the thread state clear this handle when the thread shuts - // down. This is intended for use with ThreadSpecific<Persistent<T>>. - // It's important that the Persistent<T> exist until then, because this - // takes a raw pointer to that handle. - // - // Example: - // Foo& sharedFoo() - // { - // DEFINE_THREAD_SAFE_STATIC_LOCAL( - // ThreadSpecific<Persistent<Foo>>, threadSpecificFoo, - // new ThreadSpecific<Persistent<Foo>>); - // Persistent<Foo>& fooHandle = *threadSpecificFoo; - // if (!fooHandle) { - // fooHandle = new Foo; - // fooHandle.clearOnThreadShutdown(); - // } - // return *fooHandle; - // } - void clearOnThreadShutdown() - { - void (*closure)(Persistent<T>*) = [](Persistent<T>* handle) - { - *handle = nullptr; - }; - ThreadState::current()->registerThreadShutdownHook(WTF::bind(closure, this)); - } }; // WeakPersistent is a way to create a weak pointer from an off-heap object @@ -554,20 +533,26 @@ visitor->trace(*static_cast<Collection*>(this)); } -#if defined(LEAK_SANITIZER) + // See PersistentBase::registerAsStaticReference() comment. PersistentHeapCollectionBase* registerAsStaticReference() { if (m_persistentNode) { ASSERT(ThreadState::current()); - ThreadState::current()->registerStaticPersistentNode(m_persistentNode); + ThreadState::current()->registerStaticPersistentNode(m_persistentNode, &PersistentHeapCollectionBase<Collection>::clearPersistentNode); LEAK_SANITIZER_IGNORE_OBJECT(this); } return this; } -#endif private: + // Used when the registered PersistentNode of this object is + // released during ThreadState shutdown, clearing the association. + static void clearPersistentNode(void *self) + { + (reinterpret_cast<PersistentHeapCollectionBase<Collection>*>(self))->uninitialize(); + } + NO_LAZY_SWEEP_SANITIZE_ADDRESS void initialize() { @@ -582,11 +567,14 @@ void uninitialize() { + if (!m_persistentNode) + return; ThreadState* state = ThreadState::current(); ASSERT(state->checkThread()); // Persistent handle must be created and destructed in the same thread. ASSERT(m_state == state); - state->getPersistentRegion()->freePersistentNode(m_persistentNode); + state->freePersistentNode(m_persistentNode); + m_persistentNode = nullptr; } PersistentNode* m_persistentNode;
diff --git a/third_party/WebKit/Source/platform/heap/HeapTest.cpp b/third_party/WebKit/Source/platform/heap/HeapTest.cpp index 0c4bcb0..2b570f0 100644 --- a/third_party/WebKit/Source/platform/heap/HeapTest.cpp +++ b/third_party/WebKit/Source/platform/heap/HeapTest.cpp
@@ -525,7 +525,7 @@ void runThread() override { OwnPtr<GlobalIntWrapperPersistent> longLivingPersistent; - ThreadState::attachCurrentThread(false); + ThreadState::attachCurrentThread(); longLivingPersistent = createGlobalPersistent(0x2a2a2a2a); int gcCount = 0; @@ -584,7 +584,7 @@ private: void runThread() override { - ThreadState::attachCurrentThread(false); + ThreadState::attachCurrentThread(); int gcCount = 0; while (!done()) { @@ -678,7 +678,7 @@ void runThread() override { - ThreadState::attachCurrentThread(false); + ThreadState::attachCurrentThread(); PersistentChain::create(100); @@ -4720,7 +4720,7 @@ private: static void sleeperMainFunc() { - ThreadState::attachCurrentThread(false); + ThreadState::attachCurrentThread(); s_sleeperRunning = true; // Simulate a long running op that is not entering a safepoint. @@ -5405,7 +5405,7 @@ { MutexLocker locker(workerThreadMutex()); - ThreadState::attachCurrentThread(false); + ThreadState::attachCurrentThread(); { // Create a worker object that is not kept alive except the @@ -5526,7 +5526,7 @@ { MutexLocker locker(workerThreadMutex()); - ThreadState::attachCurrentThread(false); + ThreadState::attachCurrentThread(); { Persistent<WeakCollectionType> collection = allocateCollection(); @@ -5687,7 +5687,7 @@ static void workerThreadMain() { MutexLocker locker(workerThreadMutex()); - ThreadState::attachCurrentThread(false); + ThreadState::attachCurrentThread(); DestructorLockingObject* dlo = DestructorLockingObject::create(); ASSERT_UNUSED(dlo, dlo); @@ -6376,7 +6376,7 @@ { // Step 2: Create an object and store the pointer. MutexLocker locker(workerThreadMutex()); - ThreadState::attachCurrentThread(false); + ThreadState::attachCurrentThread(); *object = DestructorLockingObject::create(); wakeMainThread(); parkWorkerThread(); @@ -6500,7 +6500,7 @@ private: void runThread() override { - ThreadState::attachCurrentThread(false); + ThreadState::attachCurrentThread(); EXPECT_EQ(42, threadSpecificIntWrapper().value()); ThreadState::detachCurrentThread(); atomicDecrement(&m_threadsToFinish); @@ -6514,7 +6514,7 @@ Persistent<IntWrapper>& handle = *intWrapper; if (!handle) { handle = new IntWrapper(42); - handle.clearOnThreadShutdown(); + handle.registerAsStaticReference(); } return *handle; }
diff --git a/third_party/WebKit/Source/platform/heap/PersistentNode.cpp b/third_party/WebKit/Source/platform/heap/PersistentNode.cpp index 233fbc3..df3cfa7c 100644 --- a/third_party/WebKit/Source/platform/heap/PersistentNode.cpp +++ b/third_party/WebKit/Source/platform/heap/PersistentNode.cpp
@@ -8,6 +8,15 @@ namespace blink { +namespace { + +class DummyGCBase final : public GarbageCollected<DummyGCBase> { +public: + DEFINE_INLINE_TRACE() { } +}; + +} + PersistentRegion::~PersistentRegion() { PersistentNodeSlots* slots = m_slots; @@ -45,11 +54,26 @@ m_slots = slots; } +void PersistentRegion::releasePersistentNode(PersistentNode* persistentNode, ThreadState::PersistentClearCallback callback) +{ + ASSERT(!persistentNode->isUnused()); + // 'self' is in use, containing the persistent wrapper object. + void* self = persistentNode->self(); + if (callback) { + (*callback)(self); + ASSERT(persistentNode->isUnused()); + return; + } + Persistent<DummyGCBase>* persistent = reinterpret_cast<Persistent<DummyGCBase>*>(self); + persistent->clear(); + ASSERT(persistentNode->isUnused()); +} + // This function traces all PersistentNodes. If we encounter // a PersistentNodeSlot that contains only freed PersistentNodes, // we delete the PersistentNodeSlot. This function rebuilds the free // list of PersistentNodes. -void PersistentRegion::tracePersistentNodes(Visitor* visitor, ShouldTraceCallback shouldTrace) +void PersistentRegion::tracePersistentNodes(Visitor* visitor) { size_t debugMarkedObjectSize = ProcessHeap::totalMarkedObjectSize(); base::debug::Alias(&debugMarkedObjectSize); @@ -71,10 +95,8 @@ freeListNext = node; ++freeCount; } else { - ++persistentCount; - if (!shouldTrace(visitor, node)) - continue; node->tracePersistentNode(visitor); + ++persistentCount; debugMarkedObjectSize = ProcessHeap::totalMarkedObjectSize(); } } @@ -97,6 +119,7 @@ ASSERT(persistentCount == m_persistentCount); } + namespace { class GCObject final : public GarbageCollected<GCObject> { public: @@ -104,16 +127,6 @@ }; } -bool CrossThreadPersistentRegion::shouldTracePersistentNode(Visitor* visitor, PersistentNode* node) -{ - CrossThreadPersistent<GCObject>* persistent = reinterpret_cast<CrossThreadPersistent<GCObject>*>(node->self()); - ASSERT(persistent); - Address rawObject = reinterpret_cast<Address>(persistent->get()); - if (!rawObject) - return false; - return &visitor->heap() == &ThreadState::fromObject(rawObject)->heap(); -} - void CrossThreadPersistentRegion::prepareForThreadStateTermination(ThreadState* threadState) { // For heaps belonging to a thread that's detaching, any cross-thread persistents @@ -131,7 +144,7 @@ continue; // 'self' is in use, containing the cross-thread persistent wrapper object. - CrossThreadPersistent<GCObject>* persistent = reinterpret_cast<CrossThreadPersistent<GCObject>*>(slots->m_slot[i].self()); + CrossThreadPersistent<DummyGCBase>* persistent = reinterpret_cast<CrossThreadPersistent<DummyGCBase>*>(slots->m_slot[i].self()); ASSERT(persistent); void* rawObject = persistent->atomicGet(); if (!rawObject)
diff --git a/third_party/WebKit/Source/platform/heap/PersistentNode.h b/third_party/WebKit/Source/platform/heap/PersistentNode.h index 260e585..7b94bbe7 100644 --- a/third_party/WebKit/Source/platform/heap/PersistentNode.h +++ b/third_party/WebKit/Source/platform/heap/PersistentNode.h
@@ -139,6 +139,7 @@ ASSERT(!node->isUnused()); return node; } + void freePersistentNode(PersistentNode* persistentNode) { ASSERT(m_persistentCount > 0); @@ -149,10 +150,8 @@ #endif } - static bool shouldTracePersistentNode(Visitor*, PersistentNode*) { return true; } - - using ShouldTraceCallback = bool (*)(Visitor*, PersistentNode*); - void tracePersistentNodes(Visitor*, ShouldTraceCallback = PersistentRegion::shouldTracePersistentNode); + void releasePersistentNode(PersistentNode*, ThreadState::PersistentClearCallback); + void tracePersistentNodes(Visitor*); int numberOfPersistents(); private: @@ -187,13 +186,11 @@ void tracePersistentNodes(Visitor* visitor) { MutexLocker lock(m_mutex); - m_persistentRegion->tracePersistentNodes(visitor, CrossThreadPersistentRegion::shouldTracePersistentNode); + m_persistentRegion->tracePersistentNodes(visitor); } void prepareForThreadStateTermination(ThreadState*); - static bool shouldTracePersistentNode(Visitor*, PersistentNode*); - private: // We don't make CrossThreadPersistentRegion inherit from PersistentRegion // because we don't want to virtualize performance-sensitive methods
diff --git a/third_party/WebKit/Source/platform/heap/ThreadState.cpp b/third_party/WebKit/Source/platform/heap/ThreadState.cpp index 155e311..ef6b720 100644 --- a/third_party/WebKit/Source/platform/heap/ThreadState.cpp +++ b/third_party/WebKit/Source/platform/heap/ThreadState.cpp
@@ -73,7 +73,7 @@ uintptr_t ThreadState::s_mainThreadUnderestimatedStackSize = 0; uint8_t ThreadState::s_mainThreadStateStorage[sizeof(ThreadState)]; -ThreadState::ThreadState(bool perThreadHeapEnabled) +ThreadState::ThreadState() : m_thread(currentThread()) , m_persistentRegion(adoptPtr(new PersistentRegion())) #if OS(WIN) && COMPILER(MSVC) @@ -90,7 +90,6 @@ , m_accumulatedSweepingTime(0) , m_vectorBackingArenaIndex(BlinkGC::Vector1ArenaIndex) , m_currentArenaAges(0) - , m_perThreadHeapEnabled(perThreadHeapEnabled) , m_isTerminating(false) , m_gcMixinMarker(nullptr) , m_shouldFlushHeapDoesNotContainCache(false) @@ -111,12 +110,7 @@ ASSERT(!**s_threadSpecific); **s_threadSpecific = this; - // TODO(keishi) Remove when per thread heap is ready. - CHECK(!m_perThreadHeapEnabled); - - if (m_perThreadHeapEnabled) { - m_heap = new ThreadHeap(); - } else if (isMainThread()) { + if (isMainThread()) { s_mainThreadStackStart = reinterpret_cast<uintptr_t>(m_startOfStack) - sizeof(void*); size_t underestimatedStackSize = StackFrameDepth::getUnderestimatedStackSize(); if (underestimatedStackSize > sizeof(void*)) @@ -195,13 +189,13 @@ { RELEASE_ASSERT(!ProcessHeap::s_shutdownComplete); s_threadSpecific = new WTF::ThreadSpecific<ThreadState*>(); - new (s_mainThreadStateStorage) ThreadState(false); + new (s_mainThreadStateStorage) ThreadState(); } -void ThreadState::attachCurrentThread(bool perThreadHeapEnabled) +void ThreadState::attachCurrentThread() { RELEASE_ASSERT(!ProcessHeap::s_shutdownComplete); - new ThreadState(perThreadHeapEnabled); + new ThreadState(); } void ThreadState::cleanupPages() @@ -226,7 +220,7 @@ // pointers into the heap owned by this thread. m_isTerminating = true; - ThreadState::callThreadShutdownHooks(); + releaseStaticPersistentNodes(); // Set the terminate flag on all heap pages of this thread. This is used to // ensure we don't trace pages on other threads that are not part of the @@ -261,15 +255,17 @@ { ASSERT(isMainThread()); + releaseStaticPersistentNodes(); + #if defined(LEAK_SANITIZER) - // If LSan is about to perform leak detection, release all the registered - // static Persistent<> root references to global caches that Blink keeps, - // followed by GCs to clear out all they referred to. + // If LSan is about to perform leak detection, after having released all + // the registered static Persistent<> root references to global caches + // that Blink keeps, follow up with a round of GCs to clear out all + // what they referred to. // // This is not needed for caches over non-Oilpan objects, as they're // not scanned by LSan due to being held in non-global storage // ("static" references inside functions/methods.) - releaseStaticPersistentNodes(); ThreadHeap::collectAllGarbage(); #endif @@ -296,15 +292,6 @@ state->~ThreadState(); } -void ThreadState::callThreadShutdownHooks() -{ - // Invoke the cleanup hooks. This gives an opportunity to release any - // persistent handles that may exist, e.g. in thread-specific static - // locals. - for (const OwnPtr<SameThreadClosure>& hook : m_threadShutdownHooks) - (*hook)(); -} - void ThreadState::detachCurrentThread() { ThreadState* state = current(); @@ -1322,31 +1309,40 @@ } } -void ThreadState::registerThreadShutdownHook(PassOwnPtr<SameThreadClosure> hook) +void ThreadState::registerStaticPersistentNode(PersistentNode* node, PersistentClearCallback callback) { - ASSERT(checkThread()); - ASSERT(!isTerminating()); - m_threadShutdownHooks.append(hook); -} - #if defined(LEAK_SANITIZER) -void ThreadState::registerStaticPersistentNode(PersistentNode* node) -{ if (m_disabledStaticPersistentsRegistration) return; +#endif ASSERT(!m_staticPersistents.contains(node)); - m_staticPersistents.add(node); + m_staticPersistents.add(node, callback); } void ThreadState::releaseStaticPersistentNodes() { - for (PersistentNode* node : m_staticPersistents) - getPersistentRegion()->freePersistentNode(node); + HashMap<PersistentNode*, ThreadState::PersistentClearCallback> staticPersistents; + staticPersistents.swap(m_staticPersistents); - m_staticPersistents.clear(); + PersistentRegion* persistentRegion = getPersistentRegion(); + for (const auto& it : staticPersistents) + persistentRegion->releasePersistentNode(it.key, it.value); } +void ThreadState::freePersistentNode(PersistentNode* persistentNode) +{ + PersistentRegion* persistentRegion = getPersistentRegion(); + persistentRegion->freePersistentNode(persistentNode); + // Do not allow static persistents to be freed before + // they're all released in releaseStaticPersistentNodes(). + // + // There's no fundamental reason why this couldn't be supported, + // but no known use for it. + ASSERT(!m_staticPersistents.contains(persistentNode)); +} + +#if defined(LEAK_SANITIZER) void ThreadState::enterStaticReferenceRegistrationDisabledScope() { m_disabledStaticPersistentsRegistration++;
diff --git a/third_party/WebKit/Source/platform/heap/ThreadState.h b/third_party/WebKit/Source/platform/heap/ThreadState.h index 572810d..5efb062 100644 --- a/third_party/WebKit/Source/platform/heap/ThreadState.h +++ b/third_party/WebKit/Source/platform/heap/ThreadState.h
@@ -173,8 +173,6 @@ void lockThreadAttachMutex(); void unlockThreadAttachMutex(); - bool perThreadHeapEnabled() const { return m_perThreadHeapEnabled; } - bool isTerminating() { return m_isTerminating; } static void attachMainThread(); @@ -184,7 +182,7 @@ // Associate ThreadState object with the current thread. After this // call thread can start using the garbage collected heap infrastructure. // It also has to periodically check for safepoints. - static void attachCurrentThread(bool perThreadHeapEnabled); + static void attachCurrentThread(); // Disassociate attached ThreadState from the current thread. The thread // can no longer use the garbage collected heap after this call. @@ -503,15 +501,14 @@ size_t threadStackSize(); #endif - // Registers a closure that will be called while the thread is shutting down - // (i.e. ThreadState::isTerminating will be true), in order to allow for any - // persistent handles that should be cleared. - void registerThreadShutdownHook(PassOwnPtr<SameThreadClosure>); + void freePersistentNode(PersistentNode*); -#if defined(LEAK_SANITIZER) - void registerStaticPersistentNode(PersistentNode*); + using PersistentClearCallback = void(*)(void*); + + void registerStaticPersistentNode(PersistentNode*, PersistentClearCallback); void releaseStaticPersistentNodes(); +#if defined(LEAK_SANITIZER) void enterStaticReferenceRegistrationDisabledScope(); void leaveStaticReferenceRegistrationDisabledScope(); #endif @@ -529,7 +526,7 @@ FreelistSnapshot }; - ThreadState(bool perThreadHeapEnabled); + ThreadState(); ~ThreadState(); NO_SANITIZE_ADDRESS void copyStackUntilSafePointScope(); @@ -639,7 +636,6 @@ size_t m_arenaAges[BlinkGC::NumberOfArenas]; size_t m_currentArenaAges; - bool m_perThreadHeapEnabled; bool m_isTerminating; GarbageCollectedMixinConstructorMarker* m_gcMixinMarker; @@ -656,19 +652,17 @@ v8::Isolate* m_isolate; void (*m_traceDOMWrappers)(v8::Isolate*, Visitor*); - // Invoked while the thread is terminating. Intended to be used to free - // persistent pointers into the thread's heap. - Vector<OwnPtr<SameThreadClosure>> m_threadShutdownHooks; - #if defined(ADDRESS_SANITIZER) void* m_asanFakeStack; #endif -#if defined(LEAK_SANITIZER) // PersistentNodes that are stored in static references; - // references we have to clear before initiating LSan's leak detection. - HashSet<PersistentNode*> m_staticPersistents; + // references that either have to be cleared upon the thread + // detaching from Oilpan and shutting down or references we + // have to clear before initiating LSan's leak detection. + HashMap<PersistentNode*, PersistentClearCallback> m_staticPersistents; +#if defined(LEAK_SANITIZER) // Count that controls scoped disabling of persistent registration. size_t m_disabledStaticPersistentsRegistration; #endif
diff --git a/third_party/WebKit/Source/platform/heap/Visitor.h b/third_party/WebKit/Source/platform/heap/Visitor.h index 8ee8243..46260bdd 100644 --- a/third_party/WebKit/Source/platform/heap/Visitor.h +++ b/third_party/WebKit/Source/platform/heap/Visitor.h
@@ -313,8 +313,6 @@ inline MarkingMode getMarkingMode() const { return m_markingMode; } - inline ThreadHeap& heap() const { return m_state->heap(); } - protected: Visitor(ThreadState*, MarkingMode);
diff --git a/third_party/WebKit/Source/web/AssertMatchingEnums.cpp b/third_party/WebKit/Source/web/AssertMatchingEnums.cpp index f2c70fa..e288e3c 100644 --- a/third_party/WebKit/Source/web/AssertMatchingEnums.cpp +++ b/third_party/WebKit/Source/web/AssertMatchingEnums.cpp
@@ -33,7 +33,6 @@ #include "bindings/core/v8/SerializedScriptValue.h" #include "core/dom/AXObjectCache.h" -#include "core/dom/ExceptionCode.h" #include "core/dom/IconURL.h" #include "core/editing/SelectionType.h" #include "core/editing/TextAffinity.h"
diff --git a/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp b/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp index 903e23d88..1ca5219 100644 --- a/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp +++ b/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp
@@ -746,7 +746,7 @@ { DCHECK(frame()); - MessageLevel webCoreMessageLevel; + MessageLevel webCoreMessageLevel = LogMessageLevel; switch (message.level) { case WebConsoleMessage::LevelDebug: webCoreMessageLevel = DebugMessageLevel; @@ -760,9 +760,10 @@ case WebConsoleMessage::LevelError: webCoreMessageLevel = ErrorMessageLevel; break; - default: - NOTREACHED(); - return; + // Unsupported values. + case WebConsoleMessage::LevelInfo: + case WebConsoleMessage::LevelRevokedError: + break; } frame()->document()->addConsoleMessage(ConsoleMessage::create(OtherMessageSource, webCoreMessageLevel, message.text, message.url, message.lineNumber, message.columnNumber));
diff --git a/third_party/WebKit/Source/web/tests/RunAllTests.cpp b/third_party/WebKit/Source/web/tests/RunAllTests.cpp index 8b1298c..86751eb1 100644 --- a/third_party/WebKit/Source/web/tests/RunAllTests.cpp +++ b/third_party/WebKit/Source/web/tests/RunAllTests.cpp
@@ -57,7 +57,6 @@ // Collect garbage (including threadspecific persistent handles) in order // to release mock objects referred from v8 or Oilpan heap. Otherwise false // mock leaks will be reported. - blink::ThreadState::current()->callThreadShutdownHooks(); blink::V8GCController::collectAllGarbageForTesting(v8::Isolate::GetCurrent()); content::TearDownBlinkTestEnvironment();
diff --git a/third_party/wayland/BUILD.gn b/third_party/wayland/BUILD.gn index e9652b38..ecb81e0 100644 --- a/third_party/wayland/BUILD.gn +++ b/third_party/wayland/BUILD.gn
@@ -33,7 +33,7 @@ configs -= [ "//build/config/compiler:chromium_code" ] configs += [ "//build/config/compiler:no_chromium_code", - "//build/config/linux:libffi", + "//build/config/linux/libffi", ":wayland_config", ] } @@ -70,7 +70,7 @@ configs -= [ "//build/config/compiler:chromium_code" ] configs += [ "//build/config/compiler:no_chromium_code", - "//build/config/linux:libffi", + "//build/config/linux/libffi", ] public_configs = [ ":wayland_config" ] @@ -91,7 +91,7 @@ configs -= [ "//build/config/compiler:chromium_code" ] configs += [ "//build/config/compiler:no_chromium_code", - "//build/config/linux:libffi", + "//build/config/linux/libffi", ] public_configs = [ ":wayland_config" ]
diff --git a/third_party/woff2/BUILD.gn b/third_party/woff2/BUILD.gn index b7abd19..431ceca 100644 --- a/third_party/woff2/BUILD.gn +++ b/third_party/woff2/BUILD.gn
@@ -2,12 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -config("woff2_warnings") { - if (!is_win || is_clang) { - cflags = [ "-Wno-unused-function" ] - } -} - source_set("woff2_dec") { sources = [ "src/buffer.h", @@ -27,7 +21,6 @@ configs -= [ "//build/config/compiler:chromium_code" ] configs += [ "//build/config/compiler:no_chromium_code" ] - configs += [ ":woff2_warnings" ] deps = [ "//third_party/brotli",
diff --git a/third_party/woff2/README.chromium b/third_party/woff2/README.chromium index e45a118..6a0d5de 100644 --- a/third_party/woff2/README.chromium +++ b/third_party/woff2/README.chromium
@@ -1,6 +1,6 @@ Name: woff2 URL: https://github.com/google/woff2 -Version: 4e698b8c6c5e070d53c340db9ddf160e21070ede +Version: 2bc6acf6dfa2f6dd2f8da63b4fe2e27851e45e11 License: Apache 2.0 License File: LICENSE Security Critical: yes @@ -13,7 +13,3 @@ - BUILD.gn: Added. - woff2.gyp: Added. -- src/port.h: Include <assert.h>. -- src/woff2_dec.cc: Msan error fix. - -Changes under src/ will be fixed in the upstream repository soon.
diff --git a/third_party/woff2/src/font.cc b/third_party/woff2/src/font.cc index b2228e39d..3679a4c0 100644 --- a/third_party/woff2/src/font.cc +++ b/third_party/woff2/src/font.cc
@@ -141,7 +141,7 @@ } std::vector<uint32_t> offsets; - for (auto i = 0; i < num_fonts; i++) { + for (size_t i = 0; i < num_fonts; i++) { uint32_t offset; if (!file->ReadU32(&offset)) { return FONT_COMPRESSION_FAILURE(); @@ -297,7 +297,7 @@ // Offset Table, zeroed for now size_t offset_table = offset; // where to write offsets later - for (int i = 0; i < font_collection.fonts.size(); i++) { + for (size_t i = 0; i < font_collection.fonts.size(); i++) { StoreU32(0, &offset, dst); } @@ -308,7 +308,7 @@ } // Write fonts and their offsets. - for (int i = 0; i < font_collection.fonts.size(); i++) { + for (size_t i = 0; i < font_collection.fonts.size(); i++) { const auto& font = font_collection.fonts[i]; StoreU32(offset, &offset_table, dst); if (!WriteFont(font, &offset, dst, dst_size)) {
diff --git a/third_party/woff2/src/glyph.cc b/third_party/woff2/src/glyph.cc index 17bef38..1dadafc 100644 --- a/third_party/woff2/src/glyph.cc +++ b/third_party/woff2/src/glyph.cc
@@ -122,7 +122,7 @@ uint8_t flag_repeat = 0; for (int i = 0; i < num_contours; ++i) { flags[i].resize(glyph->contours[i].size()); - for (int j = 0; j < glyph->contours[i].size(); ++j) { + for (size_t j = 0; j < glyph->contours[i].size(); ++j) { if (flag_repeat == 0) { if (!buffer.ReadU8(&flag)) { return FONT_COMPRESSION_FAILURE(); @@ -143,7 +143,7 @@ // Read the x coordinates. int prev_x = 0; for (int i = 0; i < num_contours; ++i) { - for (int j = 0; j < glyph->contours[i].size(); ++j) { + for (size_t j = 0; j < glyph->contours[i].size(); ++j) { uint8_t flag = flags[i][j]; if (flag & kFLAG_XSHORT) { // single byte x-delta coord value @@ -170,7 +170,7 @@ // Read the y coordinates. int prev_y = 0; for (int i = 0; i < num_contours; ++i) { - for (int j = 0; j < glyph->contours[i].size(); ++j) { + for (size_t j = 0; j < glyph->contours[i].size(); ++j) { uint8_t flag = flags[i][j]; if (flag & kFLAG_YSHORT) { // single byte y-delta coord value
diff --git a/third_party/woff2/src/transform.cc b/third_party/woff2/src/transform.cc index b7b0cf0..2ad8b16 100644 --- a/third_party/woff2/src/transform.cc +++ b/third_party/woff2/src/transform.cc
@@ -39,7 +39,7 @@ } void WriteBytes(std::vector<uint8_t>* out, const std::vector<uint8_t>& in) { - for (int i = 0; i < in.size(); ++i) { + for (size_t i = 0; i < in.size(); ++i) { out->push_back(in[i]); } }
diff --git a/third_party/woff2/src/woff2_dec.cc b/third_party/woff2/src/woff2_dec.cc index ea1f1693..1e63caa 100644 --- a/third_party/woff2/src/woff2_dec.cc +++ b/third_party/woff2/src/woff2_dec.cc
@@ -634,35 +634,6 @@ return NULL; } -// This is linear search, but could be changed to binary because we -// do have a guarantee that the tables are sorted by tag. But the total -// cpu time is expected to be very small in any case. -const Table* FindTable(const std::vector<Table>& tables, uint32_t tag) { - size_t n_tables = tables.size(); - for (size_t i = 0; i < n_tables; ++i) { - if (tables[i].tag == tag) { - return &tables[i]; - } - } - return NULL; -} - -// https://www.microsoft.com/typography/otspec/maxp.htm -bool ReadNumGlyphs(const Table* maxp_table, - const uint8_t* dst, size_t dst_length, - uint16_t* num_glyphs) { - if (PREDICT_FALSE(static_cast<uint64_t>(maxp_table->dst_offset + - maxp_table->dst_length) > dst_length)) { - return FONT_COMPRESSION_FAILURE(); - } - Buffer buffer(dst + maxp_table->dst_offset, maxp_table->dst_length); - // Skip 4 to reach 'maxp' numGlyphs - if (PREDICT_FALSE(!buffer.Skip(4) || !buffer.ReadU16(num_glyphs))) { - return FONT_COMPRESSION_FAILURE(); - } - return true; -} - // Get numberOfHMetrics, https://www.microsoft.com/typography/otspec/hhea.htm bool ReadNumHMetrics(const uint8_t* data, size_t data_size, uint16_t* num_hmetrics) { @@ -674,37 +645,6 @@ return true; } -// x_min for glyph; https://www.microsoft.com/typography/otspec/glyf.htm -bool ReadGlyphXMin(Buffer* glyf_buff, Buffer* loca_buff, int16_t loca_format, - uint16_t index, int16_t* x_min) { - uint32_t offset1, offset2; - loca_buff->set_offset((loca_format == 0 ? 2 : 4) * index); - if (loca_format == 0) { - uint16_t tmp1, tmp2; - if (PREDICT_FALSE(!loca_buff->ReadU16(&tmp1) || - !loca_buff->ReadU16(&tmp2))) { - return FONT_COMPRESSION_FAILURE(); - } - // https://www.microsoft.com/typography/otspec/loca.htm - // "The actual local offset divided by 2 is stored." - offset1 = tmp1 * 2; - offset2 = tmp2 * 2; - } else if (PREDICT_FALSE(!loca_buff->ReadU32(&offset1) || - !loca_buff->ReadU32(&offset2))) { - return FONT_COMPRESSION_FAILURE(); - } - - if (offset1 != offset2) { - glyf_buff->set_offset(offset1 + 2); - if (!glyf_buff->ReadS16(x_min)) { - return FONT_COMPRESSION_FAILURE(); - } - } else { - *x_min = 0; - } - return true; -} - // http://dev.w3.org/webfonts/WOFF2/spec/Overview.html#hmtx_table_format bool ReconstructTransformedHmtx(const uint8_t* transformed_buf, size_t transformed_size, @@ -784,18 +724,6 @@ return true; } -uint32_t ComputeChecksum(const Table* table, const uint8_t* dst) { - return ComputeULongSum(dst + table->dst_offset, table->dst_length); -} - -const Table* FindTable(TtcFont ttc_font, const std::vector<Table>& tables, - uint32_t tag) { - for (const auto i : ttc_font.table_indices) { - if (tables[i].tag == tag) return &tables[i]; - } - return NULL; -} - bool Woff2Uncompress(uint8_t* dst_buf, size_t dst_size, const uint8_t* src_buf, size_t src_size) { size_t uncompressed_size = dst_size;
diff --git a/third_party/woff2/src/woff2_enc.cc b/third_party/woff2/src/woff2_enc.cc index 920c614f..48878b5 100644 --- a/third_party/woff2/src/woff2_enc.cc +++ b/third_party/woff2/src/woff2_enc.cc
@@ -23,7 +23,7 @@ #include <string> #include <vector> -#include "./encode.h" +#include "./compressor.h" #include "./buffer.h" #include "./font.h" #include "./normalize.h" @@ -148,14 +148,6 @@ return size; } -size_t ComputeTTFLength(const std::vector<Table>& tables) { - size_t size = 12 + 16 * tables.size(); // sfnt header - for (const auto& table : tables) { - size += Round4(table.src_length); - } - return size; -} - size_t ComputeUncompressedLength(const Font& font) { // sfnt header + offset table size_t size = 12 + 16 * font.num_tables;
diff --git a/third_party/woff2/woff2.gyp b/third_party/woff2/woff2.gyp index c23a20c..9c52a79 100644 --- a/third_party/woff2/woff2.gyp +++ b/third_party/woff2/woff2.gyp
@@ -33,11 +33,6 @@ 'msvs_disabled_warnings': [ 4267, ], - 'variables': { - 'clang_warning_flags': [ - '-Wno-unused-function', - ], - }, }, ], }
diff --git a/tools/android/loading/metrics.py b/tools/android/loading/metrics.py new file mode 100644 index 0000000..b56c54c --- /dev/null +++ b/tools/android/loading/metrics.py
@@ -0,0 +1,103 @@ +# 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. + +"""Descriptive metrics for Clovis. + +When executed as a script, shows a graph of the amount of data to download for +a new visit to the same page, with a given time interval. +""" + + +from request_track import CachingPolicy + + +def _RequestTransferSize(request): + def HeadersSize(headers): + # 4: ':', ' ', '\r', '\n' + return sum(len(k) + len(v) + 4 for (k, v) in headers.items()) + if request.protocol == 'data': + return {'get': 0, 'request_headers': 0, 'response_headers': 0, 'body': 0} + return {'get': len('GET ') + len(request.url) + 2, + 'request_headers': HeadersSize(request.request_headers or {}), + 'response_headers': HeadersSize(request.response_headers or {}), + 'body': request.encoded_data_length} + + +def TotalTransferSize(trace): + """Returns the total transfer size (uploaded, downloaded) from a trace. + + This is an estimate as we assume: + - 200s (for the size computation) + - GET only. + """ + uploaded_bytes = 0 + downloaded_bytes = 0 + for request in trace.request_track.GetEvents(): + request_bytes = _RequestTransferSize(request) + uploaded_bytes += request_bytes['get'] + request_bytes['request_headers'] + downloaded_bytes += (len('HTTP/1.1 200 OK') + + request_bytes['response_headers'] + + request_bytes['body']) + return (uploaded_bytes, downloaded_bytes) + + +def TransferredDataRevisit(trace, after_time_s, assume_validation_ok=False): + """Returns the amount of data transferred for a revisit. + + Args: + trace: (LoadingTrace) loading trace. + after_time_s: (float) Time in s after which the site is revisited. + assume_validation_ok: (bool) Assumes that the resources to validate return + 304s. + + Returns: + (uploaded_bytes, downloaded_bytes) + """ + uploaded_bytes = 0 + downloaded_bytes = 0 + for request in trace.request_track.GetEvents(): + caching_policy = CachingPolicy(request) + policy = caching_policy.PolicyAtDate(request.wall_time + after_time_s) + request_bytes = _RequestTransferSize(request) + if policy == CachingPolicy.VALIDATION_NONE: + continue + uploaded_bytes += request_bytes['get'] + request_bytes['request_headers'] + if (policy in (CachingPolicy.VALIDATION_SYNC, + CachingPolicy.VALIDATION_ASYNC) + and caching_policy.HasValidators() and assume_validation_ok): + downloaded_bytes += len('HTTP/1.1 304 NOT MODIFIED\r\n') + continue + downloaded_bytes += (len('HTTP/1.1 200 OK\r\n') + + request_bytes['response_headers'] + + request_bytes['body']) + return (uploaded_bytes, downloaded_bytes) + + +def PlotTransferSizeVsTimeBetweenVisits(trace): + times = [10, 60, 300, 600, 3600, 4 * 3600, 12 * 3600, 24 * 3600] + labels = ['10s', '1m', '10m', '1h', '4h', '12h', '1d'] + (_, total_downloaded) = TotalTransferSize(trace) + downloaded = [TransferredDataRevisit(trace, delta_t)[1] for delta_t in times] + plt.figure() + plt.title('Amount of data to download for a revisit - %s' % trace.url) + plt.xlabel('Time between visits (log)') + plt.ylabel('Amount of data (bytes)') + plt.plot(times, downloaded, 'k+--') + plt.axhline(total_downloaded, color='k', linewidth=2) + plt.xscale('log') + plt.xticks(times, labels) + plt.show() + + +def main(trace_filename): + trace = loading_trace.LoadingTrace.FromJsonFile(trace_filename) + PlotTransferSizeVsTimeBetweenVisits(trace) + + +if __name__ == '__main__': + import sys + from matplotlib import pylab as plt + import loading_trace + + main(sys.argv[1])
diff --git a/tools/android/loading/metrics_unittest.py b/tools/android/loading/metrics_unittest.py new file mode 100644 index 0000000..cc439ce --- /dev/null +++ b/tools/android/loading/metrics_unittest.py
@@ -0,0 +1,75 @@ +# 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. + +import copy +import unittest + +import metrics +import request_track +import test_utils + + +class MetricsTestCase(unittest.TestCase): + _BODY_SIZE = 14187 + _URL = 'http://www.example.com/' + _REQUEST_HEADERS_SIZE = (len(_URL) + len('GET ') + 2 + + len('Accept: Everything\r\n')) + _RESPONSE_HEADERS_SIZE = 124 + _REQUEST = { + 'encoded_data_length': _BODY_SIZE, + 'request_id': '2291.1', + 'request_headers': { + 'Accept': 'Everything', + }, + 'response_headers': { + 'Age': '866', + 'Content-Length': str(_BODY_SIZE), + 'Etag': 'ABCD', + 'Date': 'Fri, 22 Apr 2016 08:56:19 -0200', + 'Vary': 'Accept-Encoding', + }, + 'timestamp': 5535648.730768, + 'timing': { + 'receive_headers_end': 47.0650000497699, + 'request_time': 5535648.73264, + }, + 'url': _URL, + 'status': 200, + 'wall_time': 1461322579.59422} + + def testTransferredDataRevisitNoCache(self): + trace = self._MakeTrace() + (uploaded, downloaded) = metrics.TransferredDataRevisit(trace, 10) + self.assertEqual(self._REQUEST_HEADERS_SIZE, uploaded) + self.assertEqual(self._BODY_SIZE + self._RESPONSE_HEADERS_SIZE, downloaded) + + def testTransferredDataRevisitNoCacheAssumeValidates(self): + trace = self._MakeTrace() + (uploaded, downloaded) = metrics.TransferredDataRevisit(trace, 10, True) + self.assertEqual(self._REQUEST_HEADERS_SIZE, uploaded) + not_modified_length = len('HTTP/1.1 304 NOT MODIFIED\r\n') + self.assertEqual(not_modified_length, downloaded) + + def testTransferredDataRevisitCacheable(self): + trace = self._MakeTrace() + r = trace.request_track.GetEvents()[0] + r.response_headers['Cache-Control'] = 'max-age=1000' + (uploaded, downloaded) = metrics.TransferredDataRevisit(trace, 10) + self.assertEqual(0, uploaded) + self.assertEqual(0, downloaded) + (uploaded, downloaded) = metrics.TransferredDataRevisit(trace, 1000) + self.assertEqual(self._REQUEST_HEADERS_SIZE, uploaded) + cache_control_length = len('Cache-Control: max-age=1000\r\n') + self.assertEqual( + self._BODY_SIZE + self._RESPONSE_HEADERS_SIZE + cache_control_length, + downloaded) + + @classmethod + def _MakeTrace(cls): + request = request_track.Request.FromJsonDict(copy.deepcopy(cls._REQUEST)) + return test_utils.LoadingTraceFromEvents([request]) + + +if __name__ == '__main__': + unittest.main()
diff --git a/tools/android/loading/request_track.py b/tools/android/loading/request_track.py index 613f6e0..31eca518 100644 --- a/tools/android/loading/request_track.py +++ b/tools/android/loading/request_track.py
@@ -10,6 +10,8 @@ import bisect import collections import copy +import datetime +import email.utils import json import logging import re @@ -248,6 +250,21 @@ break return result + def GetResponseHeaderValue(self, header, value): + """Returns True iff the response headers |header| contains |value|.""" + header_values = self.GetHTTPResponseHeader(header) + if not header_values: + return None + values = header_values.split(',') + for header_value in values: + if header_value.lower() == value.lower(): + return header_value + return None + + def HasResponseHeaderValue(self, header, value): + """Returns True iff the response headers |header| contains |value|.""" + return self.GetResponseHeaderValue(header, value) is not None + def GetContentType(self): """Returns the content type, or None.""" # Check for redirects. Use the "Location" header, because the HTTP status is @@ -272,6 +289,21 @@ def IsDataRequest(self): return self.protocol == 'data' + def GetCacheControlDirective(self, directive_name): + """Returns the value of a Cache-Control directive, or None.""" + cache_control_str = self.GetHTTPResponseHeader('Cache-Control') + if cache_control_str is None: + return None + directives = [s.strip() for s in cache_control_str.split(',')] + for directive in directives: + parts = directive.split('=') + if len(parts) == 1: + continue + (name, value) = parts + if name == directive_name: + return value + return None + def MaxAge(self): """Returns the max-age of a resource, or -1.""" # TODO(lizeb): Handle the "Expires" header as well. @@ -292,11 +324,9 @@ or u'no-cache' in cache_control or len(cache_control) == 0): return -1 - if 'max-age' in cache_control: - age_match = re.match(r'\s*(\d+)+', cache_control['max-age']) - if not age_match: - return -1 - return int(age_match.group(1)) + max_age = self.GetCacheControlDirective('max-age') + if max_age: + return int(max_age) return -1 def Cost(self): @@ -316,6 +346,126 @@ return json.dumps(self.ToJsonDict(), sort_keys=True, indent=2) +class CachingPolicy(object): + """Represents the caching policy at an arbitrary time for a cached response. + """ + FETCH = 'FETCH' + VALIDATION_NONE = 'VALIDATION_NONE' + VALIDATION_SYNC = 'VALIDATION_SYNC' + VALIDATION_ASYNC = 'VALIDATION_ASYNC' + POLICIES = (FETCH, VALIDATION_NONE, VALIDATION_SYNC, VALIDATION_ASYNC) + def __init__(self, request): + """Constructor. + + Args: + request: (Request) + """ + assert request.response_headers is not None + self.request = request + # This is incorrect, as the timestamp corresponds to when devtools is made + # aware of the request, not when it was sent. However, this is good enough + # for computing cache expiration, which doesn't need sub-second precision. + self._request_time = self.request.wall_time + # Used when the date is not available. + self._response_time = ( + self._request_time + self.request.timing.receive_headers_end) + + def HasValidators(self): + """Returns wether the request has a validator.""" + # Assuming HTTP 1.1+. + return (self.request.GetHTTPResponseHeader('Last-Modified') + or self.request.GetHTTPResponseHeader('Etag')) + + def IsCacheable(self): + """Returns whether the request could be stored in the cache.""" + return not self.request.HasResponseHeaderValue('Cache-Control', 'no-store') + + def PolicyAtDate(self, timestamp): + """Returns the caching policy at an aribitrary timestamp. + + Args: + timestamp: (float) Seconds since Epoch. + + Returns: + A policy in POLICIES. + """ + # Note: the implementation is largely transcribed from + # net/http/http_response_headers.cc, itself following RFC 2616. + if not self.IsCacheable(): + return self.FETCH + freshness = self._GetFreshnessLifetimes() + if freshness[0] == 0 and freshness[1] == 0: + return self.VALIDATION_SYNC + age = self._GetCurrentAge(timestamp) + if freshness[0] > age: + return self.VALIDATION_NONE + if freshness[1] > age: + return self.VALIDATION_ASYNC + return self.VALIDATION_SYNC + + def _GetFreshnessLifetimes(self): + """Returns [freshness, stale-while-revalidate freshness] in seconds.""" + # This is adapted from GetFreshnessLifetimes() in + # //net/http/http_response_headers.cc (which follows the RFC). + r = self.request + result = [0, 0] + if (r.HasResponseHeaderValue('Cache-Control', 'no-cache') + or r.HasResponseHeaderValue('Cache-Control', 'no-store') + or r.HasResponseHeaderValue('Vary', '*')): # RFC 2616, 13.6. + return result + must_revalidate = r.HasResponseHeaderValue( + 'Cache-Control', 'must-revalidate') + swr_header = r.GetCacheControlDirective('stale-while-revalidate') + if not must_revalidate and swr_header: + result[1] = int(swr_header) + + max_age_header = r.GetCacheControlDirective('max-age') + if max_age_header: + result[0] = int(max_age_header) + return result + + date = self._GetDateValue('Date') or self._response_time + expires = self._GetDateValue('Expires') + if expires: + result[0] = expires - date + return result + + if self.request.status in (200, 203, 206) and not must_revalidate: + last_modified = self._GetDateValue('Last-Modified') + if last_modified and last_modified < date: + result[0] = (date - last_modified) / 10 + return result + + if self.request.status in (300, 301, 308, 410): + return [2**48, 0] # ~forever. + # No header -> not fresh. + return result + + def _GetDateValue(self, name): + date_str = self.request.GetHTTPResponseHeader(name) + if not date_str: + return None + parsed_date = email.utils.parsedate_tz(date_str) + if parsed_date is None: + return None + return email.utils.mktime_tz(parsed_date) + + def _GetCurrentAge(self, current_time): + # See GetCurrentAge() in //net/http/http_response_headers.cc. + r = self.request + date_value = self._GetDateValue('Date') or self._response_time + age_value = int(r.GetHTTPResponseHeader('Age') or '0') + + apparent_age = max(0, self._response_time - date_value) + corrected_received_age = max(apparent_age, age_value) + response_delay = self._response_time - self._request_time + corrected_initial_age = corrected_received_age + response_delay + resident_time = current_time - self._response_time + current_age = corrected_initial_age + resident_time + + return current_age + + class RequestTrack(devtools_monitor.Track): """Aggregates request data.""" _REDIRECT_SUFFIX = '.redirect'
diff --git a/tools/android/loading/request_track_unittest.py b/tools/android/loading/request_track_unittest.py index a613397..19f7b4af 100644 --- a/tools/android/loading/request_track_unittest.py +++ b/tools/android/loading/request_track_unittest.py
@@ -6,7 +6,8 @@ import json import unittest -from request_track import (TimeBetween, Request, RequestTrack, Timing) +from request_track import (TimeBetween, Request, CachingPolicy, RequestTrack, + Timing) class TimeBetweenTestCase(unittest.TestCase): @@ -74,6 +75,133 @@ self.assertEquals('Bar', r.GetHTTPResponseHeader('Foo')) +class CachingPolicyTestCase(unittest.TestCase): + _REQUEST = { + 'encoded_data_length': 14726, + 'request_id': '2291.1', + 'response_headers': { + 'Age': '866', + 'Content-Length': '14187', + 'Date': 'Fri, 22 Apr 2016 08:56:19 -0200', + 'Vary': 'Accept-Encoding', + }, + 'timestamp': 5535648.730768, + 'timing': { + 'connect_end': 34.0510001406074, + 'connect_start': 21.6859998181462, + 'dns_end': 21.6859998181462, + 'dns_start': 0, + 'loading_finished': 58.76399949193001, + 'receive_headers_end': 47.0650000497699, + 'request_time': 5535648.73264, + 'send_end': 34.6099995076656, + 'send_start': 34.2979999259114 + }, + 'url': 'http://www.example.com/', + 'status': 200, + 'wall_time': 1461322579.59422} + + def testHasValidators(self): + r = self._MakeRequest() + self.assertFalse(CachingPolicy(r).HasValidators()) + r.response_headers['Last-Modified'] = 'Yesterday all my troubles' + self.assertTrue(CachingPolicy(r).HasValidators()) + r = self._MakeRequest() + r.response_headers['ETAG'] = 'ABC' + self.assertTrue(CachingPolicy(r).HasValidators()) + + def testIsCacheable(self): + r = self._MakeRequest() + self.assertTrue(CachingPolicy(r).IsCacheable()) + r.response_headers['Cache-Control'] = 'Whatever,no-store' + self.assertFalse(CachingPolicy(r).IsCacheable()) + + def testPolicyNoStore(self): + r = self._MakeRequest() + r.response_headers['Cache-Control'] = 'Whatever,no-store' + self.assertEqual(CachingPolicy.FETCH, CachingPolicy(r).PolicyAtDate(0)) + + def testPolicyMaxAge(self): + r = self._MakeRequest() + r.response_headers['Cache-Control'] = 'whatever,max-age=1000,whatever' + self.assertEqual( + CachingPolicy.VALIDATION_NONE, + CachingPolicy(r).PolicyAtDate(r.wall_time)) + self.assertEqual( + CachingPolicy.VALIDATION_SYNC, + CachingPolicy(r).PolicyAtDate(r.wall_time + 10000)) + # Take current age into account. + self.assertEqual( + CachingPolicy.VALIDATION_SYNC, + CachingPolicy(r).PolicyAtDate(r.wall_time + 500)) + # Max-Age before Expires. + r.response_headers['Expires'] = 'Thu, 21 Apr 2016 00:00:00 -0200' + self.assertEqual( + CachingPolicy.VALIDATION_NONE, + CachingPolicy(r).PolicyAtDate(r.wall_time)) + # Max-Age < age + r.response_headers['Cache-Control'] = 'whatever,max-age=100,whatever' + self.assertEqual( + CachingPolicy.VALIDATION_SYNC, + CachingPolicy(r).PolicyAtDate(r.wall_time + 2)) + + def testPolicyExpires(self): + r = self._MakeRequest() + # Already expired + r.response_headers['Expires'] = 'Thu, 21 Apr 2016 00:00:00 -0200' + self.assertEqual( + CachingPolicy.VALIDATION_SYNC, + CachingPolicy(r).PolicyAtDate(r.wall_time)) + r.response_headers['Expires'] = 'Thu, 25 Apr 2016 00:00:00 -0200' + self.assertEqual( + CachingPolicy.VALIDATION_NONE,\ + CachingPolicy(r).PolicyAtDate(r.wall_time)) + self.assertEqual( + CachingPolicy.VALIDATION_NONE, + CachingPolicy(r).PolicyAtDate(r.wall_time + 86400)) + self.assertEqual(CachingPolicy.VALIDATION_SYNC, + CachingPolicy(r).PolicyAtDate(r.wall_time + 86400 * 5)) + + def testStaleWhileRevalidate(self): + r = self._MakeRequest() + r.response_headers['Cache-Control'] = ( + 'whatever,max-age=100,stale-while-revalidate=2000') + self.assertEqual( + CachingPolicy.VALIDATION_ASYNC, + CachingPolicy(r).PolicyAtDate(r.wall_time + 200)) + self.assertEqual( + CachingPolicy.VALIDATION_SYNC, + CachingPolicy(r).PolicyAtDate(r.wall_time + 2000)) + # must-revalidate overrides stale-while-revalidate. + r.response_headers['Cache-Control'] += ',must-revalidate' + self.assertEqual( + CachingPolicy.VALIDATION_SYNC, + CachingPolicy(r).PolicyAtDate(r.wall_time + 200)) + + def test301NeverExpires(self): + r = self._MakeRequest() + r.status = 301 + self.assertEqual( + CachingPolicy.VALIDATION_NONE, + CachingPolicy(r).PolicyAtDate(r.wall_time + 2000)) + + def testLastModifiedHeuristic(self): + r = self._MakeRequest() + # 8 hours ago. + r.response_headers['Last-Modified'] = 'Fri, 22 Apr 2016 00:56:19 -0200' + del r.response_headers['Age'] + self.assertEqual( + CachingPolicy.VALIDATION_NONE, + CachingPolicy(r).PolicyAtDate(r.wall_time + 60)) + self.assertEqual( + CachingPolicy.VALIDATION_SYNC, + CachingPolicy(r).PolicyAtDate(r.wall_time + 3600)) + + @classmethod + def _MakeRequest(cls): + return Request.FromJsonDict(copy.deepcopy(cls._REQUEST)) + + class RequestTrackTestCase(unittest.TestCase): _REQUEST_WILL_BE_SENT = { 'method': 'Network.requestWillBeSent',
diff --git a/tools/gn/visual_studio_writer.cc b/tools/gn/visual_studio_writer.cc index 14a02cd..87dfa81 100644 --- a/tools/gn/visual_studio_writer.cc +++ b/tools/gn/visual_studio_writer.cc
@@ -189,6 +189,14 @@ VisualStudioWriter::SolutionProject::~SolutionProject() = default; +VisualStudioWriter::SourceFileCompileTypePair::SourceFileCompileTypePair( + const SourceFile* _file, + const char* _compile_type) + : file(_file), compile_type(_compile_type) {} + +VisualStudioWriter::SourceFileCompileTypePair::~SourceFileCompileTypePair() = + default; + VisualStudioWriter::VisualStudioWriter(const BuildSettings* build_settings, const char* config_platform, Version version) @@ -321,8 +329,9 @@ project_config_platform)); std::stringstream vcxproj_string_out; + SourceFileCompileTypePairs source_types; if (!WriteProjectFileContents(vcxproj_string_out, *projects_.back(), target, - err)) { + &source_types, err)) { projects_.pop_back(); return false; } @@ -335,7 +344,7 @@ base::FilePath filters_path = UTF8ToFilePath(vcxproj_path_str + ".filters"); std::stringstream filters_string_out; - WriteFiltersFileContents(filters_string_out, target); + WriteFiltersFileContents(filters_string_out, target, source_types); return WriteFileIfChanged(filters_path, filters_string_out.str(), err); } @@ -343,6 +352,7 @@ std::ostream& out, const SolutionProject& solution_project, const Target* target, + SourceFileCompileTypePairs* source_types, Err* err) { PathOutput path_output(GetTargetOutputDir(target), build_settings_->root_path_utf8(), @@ -481,13 +491,7 @@ cl_compile->SubElement("MinimalRebuild")->Text("false"); if (!options.optimization.empty()) cl_compile->SubElement("Optimization")->Text(options.optimization); - if (target->config_values().has_precompiled_headers()) { - cl_compile->SubElement("PrecompiledHeader")->Text("Use"); - cl_compile->SubElement("PrecompiledHeaderFile") - ->Text(target->config_values().precompiled_header()); - } else { - cl_compile->SubElement("PrecompiledHeader")->Text("NotUsing"); - } + cl_compile->SubElement("PrecompiledHeader")->Text("NotUsing"); { std::unique_ptr<XmlElementWriter> preprocessor_definitions = cl_compile->SubElement("PreprocessorDefinitions"); @@ -512,22 +516,25 @@ { std::unique_ptr<XmlElementWriter> group = project.SubElement("ItemGroup"); - if (!target->config_values().precompiled_source().is_null()) { - group - ->SubElement( - "ClCompile", "Include", - SourceFileWriter(path_output, - target->config_values().precompiled_source())) - ->SubElement("PrecompiledHeader") - ->Text("Create"); - } + std::vector<OutputFile> tool_outputs; // Prevent reallocation in loop. for (const SourceFile& file : target->sources()) { - SourceFileType type = GetSourceFileType(file); - if (type == SOURCE_H || type == SOURCE_CPP || type == SOURCE_C) { - group->SubElement(type == SOURCE_H ? "ClInclude" : "ClCompile", - "Include", SourceFileWriter(path_output, file)); + const char* compile_type; + Toolchain::ToolType tool_type = Toolchain::TYPE_NONE; + if (target->GetOutputFilesForSource(file, &tool_type, &tool_outputs)) { + compile_type = "CustomBuild"; + std::unique_ptr<XmlElementWriter> build = group->SubElement( + compile_type, "Include", SourceFileWriter(path_output, file)); + build->SubElement("Command")->Text("call ninja.exe -C $(OutDir) " + + tool_outputs[0].value()); + build->SubElement("Outputs")->Text("$(OutDir)" + + tool_outputs[0].value()); + } else { + compile_type = "None"; + group->SubElement(compile_type, "Include", + SourceFileWriter(path_output, file)); } + source_types->push_back(SourceFileCompileTypePair(&file, compile_type)); } } @@ -562,8 +569,10 @@ return true; } -void VisualStudioWriter::WriteFiltersFileContents(std::ostream& out, - const Target* target) { +void VisualStudioWriter::WriteFiltersFileContents( + std::ostream& out, + const Target* target, + const SourceFileCompileTypePairs& source_types) { out << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << std::endl; XmlElementWriter project( out, "Project", @@ -589,35 +598,31 @@ std::set<std::string> processed_filters; - for (const SourceFile& file : target->sources()) { - SourceFileType type = GetSourceFileType(file); - if (type == SOURCE_H || type == SOURCE_CPP || type == SOURCE_C) { - std::unique_ptr<XmlElementWriter> cl_item = files_group.SubElement( - type == SOURCE_H ? "ClInclude" : "ClCompile", "Include", - SourceFileWriter(file_path_output, file)); + for (const auto& file_and_type : source_types) { + std::unique_ptr<XmlElementWriter> cl_item = files_group.SubElement( + file_and_type.compile_type, "Include", + SourceFileWriter(file_path_output, *file_and_type.file)); - std::ostringstream target_relative_out; - filter_path_output.WriteFile(target_relative_out, file); - std::string target_relative_path = target_relative_out.str(); - ConvertPathToSystem(&target_relative_path); - base::StringPiece filter_path = FindParentDir(&target_relative_path); + std::ostringstream target_relative_out; + filter_path_output.WriteFile(target_relative_out, *file_and_type.file); + std::string target_relative_path = target_relative_out.str(); + ConvertPathToSystem(&target_relative_path); + base::StringPiece filter_path = FindParentDir(&target_relative_path); - if (!filter_path.empty()) { - std::string filter_path_str = filter_path.as_string(); - while (processed_filters.find(filter_path_str) == - processed_filters.end()) { - auto it = processed_filters.insert(filter_path_str).first; - filters_group - ->SubElement("Filter", - XmlAttributes("Include", filter_path_str)) - ->SubElement("UniqueIdentifier") - ->Text(MakeGuid(filter_path_str, kGuidSeedFilter)); - filter_path_str = FindParentDir(&(*it)).as_string(); - if (filter_path_str.empty()) - break; - } - cl_item->SubElement("Filter")->Text(filter_path); + if (!filter_path.empty()) { + std::string filter_path_str = filter_path.as_string(); + while (processed_filters.find(filter_path_str) == + processed_filters.end()) { + auto it = processed_filters.insert(filter_path_str).first; + filters_group + ->SubElement("Filter", XmlAttributes("Include", filter_path_str)) + ->SubElement("UniqueIdentifier") + ->Text(MakeGuid(filter_path_str, kGuidSeedFilter)); + filter_path_str = FindParentDir(&(*it)).as_string(); + if (filter_path_str.empty()) + break; } + cl_item->SubElement("Filter")->Text(filter_path); } } }
diff --git a/tools/gn/visual_studio_writer.h b/tools/gn/visual_studio_writer.h index 2971896..99c5370 100644 --- a/tools/gn/visual_studio_writer.h +++ b/tools/gn/visual_studio_writer.h
@@ -21,6 +21,7 @@ class Builder; class BuildSettings; class Err; +class SourceFile; class Target; class VisualStudioWriter { @@ -78,8 +79,19 @@ std::string config_platform; }; + struct SourceFileCompileTypePair { + SourceFileCompileTypePair(const SourceFile* file, const char* compile_type); + ~SourceFileCompileTypePair(); + + // Source file. + const SourceFile* file; + // Compile type string. + const char* compile_type; + }; + using SolutionProjects = std::vector<std::unique_ptr<SolutionProject>>; using SolutionFolders = std::vector<std::unique_ptr<SolutionEntry>>; + using SourceFileCompileTypePairs = std::vector<SourceFileCompileTypePair>; VisualStudioWriter(const BuildSettings* build_settings, const char* config_platform, @@ -90,8 +102,11 @@ bool WriteProjectFileContents(std::ostream& out, const SolutionProject& solution_project, const Target* target, + SourceFileCompileTypePairs* source_types, Err* err); - void WriteFiltersFileContents(std::ostream& out, const Target* target); + void WriteFiltersFileContents(std::ostream& out, + const Target* target, + const SourceFileCompileTypePairs& source_types); bool WriteSolutionFile(const std::string& sln_name, Err* err); void WriteSolutionFileContents(std::ostream& out, const base::FilePath& solution_dir_path);
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 9cd4aeb..34e02a3f 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -84224,7 +84224,9 @@ <int value="0" label="Snippets were shown to the user"/> <int value="1" label="User scrolled through the snippets"/> <int value="2" label="User clicked on a snippet into the host website"/> - <int value="3" label="User swiped a snippet away"/> + <int value="3" label="User swiped a snippet away (obsolete)"/> + <int value="4" label="User swiped a snippet away after visiting"/> + <int value="5" label="User swiped a snippet away without visiting"/> </enum> <enum name="SocketStreamConnectionType" type="int">
diff --git a/tools/perf/benchmarks/page_cycler.py b/tools/perf/benchmarks/page_cycler.py index e32ab036..deaf9a49 100644 --- a/tools/perf/benchmarks/page_cycler.py +++ b/tools/perf/benchmarks/page_cycler.py
@@ -35,18 +35,6 @@ report_speed_index=options.report_speed_index) -# This is an old page set, we intend to remove it after more modern benchmarks -# work on CrOS. -@benchmark.Enabled('chromeos') -class PageCyclerDhtml(_PageCycler): - """Benchmarks for various DHTML operations like simple animations.""" - page_set = page_sets.DhtmlPageSet - - @classmethod - def Name(cls): - return 'page_cycler.dhtml' - - class PageCyclerIntlArFaHe(_PageCycler): """Page load time for a variety of pages in Arabic, Farsi and Hebrew.
diff --git a/tools/perf/page_sets/page_cycler/dhtml.py b/tools/perf/page_sets/page_cycler/dhtml.py deleted file mode 100644 index 1647f06..0000000 --- a/tools/perf/page_sets/page_cycler/dhtml.py +++ /dev/null
@@ -1,45 +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. -from telemetry.page import page as page_module -from telemetry import story - - -class DhtmlPage(page_module.Page): - - def __init__(self, url, page_set): - super(DhtmlPage, self).__init__(url=url, page_set=page_set) - - -class DhtmlPageSet(story.StorySet): - - """ DHTML page_cycler benchmark """ - - def __init__(self): - super(DhtmlPageSet, self).__init__( - # pylint: disable=line-too-long - serving_dirs=set(['../../../../data/page_cycler/dhtml']), - cloud_storage_bucket=story.PARTNER_BUCKET) - - urls_list = [ - 'file://../../../../data/page_cycler/dhtml/colorfade/', - 'file://../../../../data/page_cycler/dhtml/diagball/', - 'file://../../../../data/page_cycler/dhtml/fadespacing/', - 'file://../../../../data/page_cycler/dhtml/imageslide/', - 'file://../../../../data/page_cycler/dhtml/layers1/', - 'file://../../../../data/page_cycler/dhtml/layers2/', - 'file://../../../../data/page_cycler/dhtml/layers4/', - 'file://../../../../data/page_cycler/dhtml/layers5/', - 'file://../../../../data/page_cycler/dhtml/layers6/', - 'file://../../../../data/page_cycler/dhtml/meter/', - 'file://../../../../data/page_cycler/dhtml/movingtext/', - 'file://../../../../data/page_cycler/dhtml/mozilla/', - 'file://../../../../data/page_cycler/dhtml/replaceimages/', - 'file://../../../../data/page_cycler/dhtml/scrolling/', - 'file://../../../../data/page_cycler/dhtml/slidein/', - 'file://../../../../data/page_cycler/dhtml/slidingballs/', - 'file://../../../../data/page_cycler/dhtml/zoom/' - ] - - for url in urls_list: - self.AddStory(DhtmlPage(url, self))
diff --git a/ui/accessibility/BUILD.gn b/ui/accessibility/BUILD.gn index 53d08015..dcd546b 100644 --- a/ui/accessibility/BUILD.gn +++ b/ui/accessibility/BUILD.gn
@@ -97,7 +97,7 @@ configs += [ ":atk", ":atk_warnings", - "//build/config/linux:gconf", + "//build/config/linux/gconf", "//build/config/linux:glib", ] }
diff --git a/ui/base/BUILD.gn b/ui/base/BUILD.gn index f535be9..f057dfa2 100644 --- a/ui/base/BUILD.gn +++ b/ui/base/BUILD.gn
@@ -884,7 +884,7 @@ } if (use_pango) { - configs += [ "//build/config/linux:pangocairo" ] + configs += [ "//build/config/linux/pangocairo" ] } if (use_x11) { @@ -942,6 +942,8 @@ "//ui/resources:ui_test_pak", # TODO(brettw): this does nothing. "//third_party/mesa:osmesa", ] + } else if (is_android) { + data += [ "test/data/data_pack_unittest/truncated-header.pak" ] } if (is_linux || is_win) { data += [
diff --git a/ui/base/ime/BUILD.gn b/ui/base/ime/BUILD.gn index e60caafc..b6da6377 100644 --- a/ui/base/ime/BUILD.gn +++ b/ui/base/ime/BUILD.gn
@@ -164,7 +164,7 @@ } if (use_pango) { - configs += [ "//build/config/linux:pangocairo" ] + configs += [ "//build/config/linux/pangocairo" ] } else { sources -= [ "composition_text_util_pango.cc",
diff --git a/ui/gfx/BUILD.gn b/ui/gfx/BUILD.gn index ffabe80..026ed2a 100644 --- a/ui/gfx/BUILD.gn +++ b/ui/gfx/BUILD.gn
@@ -417,7 +417,7 @@ } if (use_cairo) { - configs += [ "//build/config/linux:pangocairo" ] + configs += [ "//build/config/linux/pangocairo" ] } }
diff --git a/ui/gl/BUILD.gn b/ui/gl/BUILD.gn index ea3d06a..481798e 100644 --- a/ui/gl/BUILD.gn +++ b/ui/gl/BUILD.gn
@@ -5,14 +5,24 @@ import("//build/config/ui.gni") import("//testing/test.gni") +use_egl = is_win || is_android || is_linux +use_glx = use_x11 + if (is_android) { import("//build/config/android/config.gni") import("//build/config/android/rules.gni") } config("gl_config") { - if (use_x11) { - defines = [ "GL_GLEXT_PROTOTYPES" ] + defines = [] + if (use_glx) { + defines += [ + "GL_GLEXT_PROTOTYPES", + "USE_GLX", + ] + } + if (use_egl) { + defines += [ "USE_EGL" ] } } @@ -135,7 +145,7 @@ "//ui/gfx/geometry", ] - if (is_win || is_android || is_linux) { + if (use_egl) { sources += [ "egl_util.cc", "egl_util.h", @@ -143,6 +153,8 @@ "gl_bindings_autogen_egl.h", "gl_context_egl.cc", "gl_context_egl.h", + "gl_egl_api_implementation.cc", + "gl_egl_api_implementation.h", "gl_fence_egl.cc", "gl_fence_egl.h", "gl_image_egl.cc", @@ -162,23 +174,41 @@ } if (use_x11) { sources += [ + "gl_context_x11.cc", + "gl_implementation_x11.cc", + "gl_surface_egl_x11.cc", + "gl_surface_egl_x11.h", + "gl_surface_x11.cc", + ] + + data_deps = [ + "//third_party/angle:libEGL", + "//third_party/angle:libGLESv2", + ] + } + if (use_ozone) { + sources += [ + "gl_context_ozone.cc", + "gl_image_ozone_native_pixmap.cc", + "gl_image_ozone_native_pixmap.h", + "gl_implementation_ozone.cc", + "gl_surface_ozone.cc", + ] + + deps += [ "//ui/ozone" ] + } + if (use_glx) { + sources += [ "gl_bindings_autogen_glx.cc", "gl_bindings_autogen_glx.h", "gl_context_glx.cc", "gl_context_glx.h", - "gl_context_x11.cc", - "gl_egl_api_implementation.cc", - "gl_egl_api_implementation.h", "gl_glx_api_implementation.cc", "gl_glx_api_implementation.h", "gl_image_glx.cc", "gl_image_glx.h", - "gl_implementation_x11.cc", - "gl_surface_egl_x11.cc", - "gl_surface_egl_x11.h", "gl_surface_glx.cc", "gl_surface_glx.h", - "gl_surface_x11.cc", ] configs += [ @@ -188,10 +218,6 @@ ] deps += [ "//ui/gfx/x" ] - data_deps = [ - "//third_party/angle:libEGL", - "//third_party/angle:libGLESv2", - ] } if (is_win) { sources += [ @@ -201,8 +227,6 @@ "gl_bindings_autogen_wgl.h", "gl_context_wgl.cc", "gl_context_wgl.h", - "gl_egl_api_implementation.cc", - "gl_egl_api_implementation.h", "gl_surface_wgl.cc", "gl_surface_wgl.h", "gl_wgl_api_implementation.cc", @@ -242,8 +266,6 @@ } if (is_android) { sources += [ - "gl_egl_api_implementation.cc", - "gl_egl_api_implementation.h", "gl_image_surface_texture.cc", "gl_image_surface_texture.h", ] @@ -260,18 +282,6 @@ "//ui/android:ui_java", ] } - if (use_ozone) { - sources += [ - "gl_context_ozone.cc", - "gl_egl_api_implementation.cc", - "gl_egl_api_implementation.h", - "gl_image_ozone_native_pixmap.cc", - "gl_image_ozone_native_pixmap.h", - "gl_implementation_ozone.cc", - "gl_surface_ozone.cc", - ] - deps += [ "//ui/ozone" ] - } } source_set("gl_unittest_utils") { @@ -318,10 +328,7 @@ if (use_x11) { configs += [ "//build/config/linux:x11" ] - deps += [ - "//ui/gfx/x", - "//ui/platform_window/x11", - ] + deps += [ "//ui/platform_window/x11" ] } } @@ -334,14 +341,14 @@ "test/run_all_unittests.cc", ] - if (is_win || is_android || is_linux) { + if (use_egl) { sources += [ "egl_api_unittest.cc", "test/egl_initialization_displays_unittest.cc", ] } - if (use_x11) { + if (use_glx) { sources += [ "glx_api_unittest.cc" ] }
diff --git a/ui/gl/gl.gyp b/ui/gl/gl.gyp index a1fce09..df645846 100644 --- a/ui/gl/gl.gyp +++ b/ui/gl/gl.gyp
@@ -148,6 +148,14 @@ 'gl_surface_egl.cc', 'gl_surface_egl.h', ], + 'direct_dependent_settings': { + 'defines': [ + 'USE_EGL', + ], + }, + 'defines': [ + 'USE_EGL', + ], 'include_dirs': [ '<(DEPTH)/third_party/khronos', ], @@ -175,11 +183,15 @@ 'gl_surface_glx.cc', 'gl_surface_glx.h', ], - 'all_dependent_settings': { + 'direct_dependent_settings': { 'defines': [ 'GL_GLEXT_PROTOTYPES', + 'USE_GLX', ], }, + 'defines': [ + 'USE_GLX', + ], 'dependencies': [ '<(DEPTH)/build/linux/system.gyp:x11', '<(DEPTH)/build/linux/system.gyp:xcomposite',
diff --git a/ui/gl/gl_bindings.cc b/ui/gl/gl_bindings.cc index 0f47871..3dfe634b 100644 --- a/ui/gl/gl_bindings.cc +++ b/ui/gl/gl_bindings.cc
@@ -4,13 +4,13 @@ #include "build/build_config.h" -#if defined(OS_WIN) || defined(USE_X11) || defined(OS_ANDROID) || defined(USE_OZONE) +#if defined(USE_EGL) #include <EGL/egl.h> #endif #include "ui/gl/gl_bindings.h" -#if defined(USE_X11) +#if defined(USE_GLX) #include "ui/gfx/x/x11_types.h" // nogncheck #endif @@ -18,7 +18,7 @@ #include "ui/gl/gl_surface_wgl.h" #endif -#if defined(OS_WIN) || defined(USE_X11) || defined(OS_ANDROID) || defined(USE_OZONE) +#if defined(USE_EGL) #include "ui/gl/gl_surface_egl.h" #endif @@ -38,7 +38,7 @@ } #endif -#if defined(OS_WIN) || defined(USE_X11) || defined(OS_ANDROID) || defined(USE_OZONE) +#if defined(USE_EGL) std::string DriverEGL::GetPlatformExtensions() { EGLDisplay display = GLSurfaceEGL::InitializeDisplay(); if (display == EGL_NO_DISPLAY) @@ -54,7 +54,7 @@ } #endif -#if defined(USE_X11) +#if defined(USE_GLX) std::string DriverGLX::GetPlatformExtensions() { const char* str = glXQueryExtensionsString(gfx::GetXDisplay(), 0); return str ? std::string(str) : "";
diff --git a/ui/gl/gl_bindings.h b/ui/gl/gl_bindings.h index 62952f54..c973bed 100644 --- a/ui/gl/gl_bindings.h +++ b/ui/gl/gl_bindings.h
@@ -28,7 +28,7 @@ #include <GL/wglext.h> #elif defined(OS_MACOSX) #include <OpenGL/OpenGL.h> -#elif defined(USE_X11) +#elif defined(USE_GLX) #include <GL/glx.h> #include <GL/glxext.h> @@ -372,16 +372,16 @@ #include "gl_bindings_autogen_gl.h" #include "gl_bindings_autogen_osmesa.h" +#if defined(USE_EGL) +#include "gl_bindings_autogen_egl.h" +#endif + #if defined(OS_WIN) -#include "gl_bindings_autogen_egl.h" #include "gl_bindings_autogen_wgl.h" -#elif defined(USE_X11) -#include "gl_bindings_autogen_egl.h" +#endif + +#if defined(USE_GLX) #include "gl_bindings_autogen_glx.h" -#elif defined(USE_OZONE) -#include "gl_bindings_autogen_egl.h" -#elif defined(OS_ANDROID) -#include "gl_bindings_autogen_egl.h" #endif namespace gfx { @@ -436,7 +436,7 @@ }; #endif -#if defined(OS_WIN) || defined(USE_X11) || defined(OS_ANDROID) || defined(USE_OZONE) +#if defined(USE_EGL) struct GL_EXPORT DriverEGL { void InitializeStaticBindings(); void InitializeExtensionBindings(); @@ -452,7 +452,7 @@ }; #endif -#if defined(USE_X11) +#if defined(USE_GLX) struct GL_EXPORT DriverGLX { void InitializeStaticBindings(); void InitializeExtensionBindings(); @@ -476,30 +476,19 @@ GL_EXPORT extern DriverGL g_driver_gl; GL_EXPORT extern DriverOSMESA g_driver_osmesa; +#if defined(USE_EGL) +GL_EXPORT extern EGLApi* g_current_egl_context; +GL_EXPORT extern DriverEGL g_driver_egl; +#endif + #if defined(OS_WIN) - -GL_EXPORT extern EGLApi* g_current_egl_context; GL_EXPORT extern WGLApi* g_current_wgl_context; -GL_EXPORT extern DriverEGL g_driver_egl; GL_EXPORT extern DriverWGL g_driver_wgl; +#endif -#elif defined(USE_X11) - -GL_EXPORT extern EGLApi* g_current_egl_context; +#if defined(USE_GLX) GL_EXPORT extern GLXApi* g_current_glx_context; -GL_EXPORT extern DriverEGL g_driver_egl; GL_EXPORT extern DriverGLX g_driver_glx; - -#elif defined(USE_OZONE) - -GL_EXPORT extern EGLApi* g_current_egl_context; -GL_EXPORT extern DriverEGL g_driver_egl; - -#elif defined(OS_ANDROID) - -GL_EXPORT extern EGLApi* g_current_egl_context; -GL_EXPORT extern DriverEGL g_driver_egl; - #endif } // namespace gfx
diff --git a/ui/gl/gl_implementation.cc b/ui/gl/gl_implementation.cc index af06cbe..dfb1548b 100644 --- a/ui/gl/gl_implementation.cc +++ b/ui/gl/gl_implementation.cc
@@ -58,24 +58,16 @@ base::ThreadLocalPointer<GLApi>* g_current_gl_context_tls = NULL; OSMESAApi* g_current_osmesa_context; +#if defined(USE_EGL) +EGLApi* g_current_egl_context; +#endif + #if defined(OS_WIN) - -EGLApi* g_current_egl_context; WGLApi* g_current_wgl_context; +#endif -#elif defined(USE_X11) - -EGLApi* g_current_egl_context; +#if defined(USE_GLX) GLXApi* g_current_glx_context; - -#elif defined(USE_OZONE) - -EGLApi* g_current_egl_context; - -#elif defined(OS_ANDROID) - -EGLApi* g_current_egl_context; - #endif GLImplementation GetNamedGLImplementation(const std::string& name) {
diff --git a/ui/gl/gl_implementation_ozone.cc b/ui/gl/gl_implementation_ozone.cc index 715084f..85c4a1b 100644 --- a/ui/gl/gl_implementation_ozone.cc +++ b/ui/gl/gl_implementation_ozone.cc
@@ -85,8 +85,9 @@ new GLContextStubWithExtensions()); mock_context->SetGLVersionString("3.0"); InitializeDynamicGLBindingsGL(mock_context.get()); - } else + } else { InitializeDynamicGLBindingsGL(context); + } break; default: return false; @@ -96,11 +97,15 @@ } void InitializeDebugGLBindings() { + InitializeDebugGLBindingsEGL(); + InitializeDebugGLBindingsGL(); + InitializeDebugGLBindingsOSMESA(); } void ClearGLBindings() { ClearGLBindingsEGL(); ClearGLBindingsGL(); + ClearGLBindingsOSMESA(); SetGLImplementation(kGLImplementationNone); UnloadGLNativeLibraries(); }
diff --git a/ui/gl/gl_surface_x11.cc b/ui/gl/gl_surface_x11.cc index 18e8946..c6a0653 100644 --- a/ui/gl/gl_surface_x11.cc +++ b/ui/gl/gl_surface_x11.cc
@@ -24,6 +24,8 @@ namespace gfx { +namespace { + // This OSMesa GL surface can use XLib to swap the contents of the buffer to a // view. class NativeViewGLSurfaceOSMesa : public GLSurfaceOSMesa { @@ -56,33 +58,6 @@ DISALLOW_COPY_AND_ASSIGN(NativeViewGLSurfaceOSMesa); }; -bool GLSurface::InitializeOneOffInternal() { - switch (GetGLImplementation()) { - case kGLImplementationDesktopGL: - if (!GLSurfaceGLX::InitializeOneOff()) { - LOG(ERROR) << "GLSurfaceGLX::InitializeOneOff failed."; - return false; - } - break; - case kGLImplementationOSMesaGL: - if (!NativeViewGLSurfaceOSMesa::InitializeOneOff()) { - LOG(ERROR) << "NativeViewGLSurfaceOSMesa::InitializeOneOff failed."; - return false; - } - break; - case kGLImplementationEGLGLES2: - if (!GLSurfaceEGL::InitializeOneOff()) { - LOG(ERROR) << "GLSurfaceEGL::InitializeOneOff failed."; - return false; - } - break; - default: - break; - } - - return true; -} - NativeViewGLSurfaceOSMesa::NativeViewGLSurfaceOSMesa( gfx::AcceleratedWidget window) : GLSurfaceOSMesa(SURFACE_OSMESA_BGRA, gfx::Size(1, 1)), @@ -268,6 +243,35 @@ Destroy(); } +} // namespace + +bool GLSurface::InitializeOneOffInternal() { + switch (GetGLImplementation()) { + case kGLImplementationDesktopGL: + if (!GLSurfaceGLX::InitializeOneOff()) { + LOG(ERROR) << "GLSurfaceGLX::InitializeOneOff failed."; + return false; + } + break; + case kGLImplementationOSMesaGL: + if (!NativeViewGLSurfaceOSMesa::InitializeOneOff()) { + LOG(ERROR) << "NativeViewGLSurfaceOSMesa::InitializeOneOff failed."; + return false; + } + break; + case kGLImplementationEGLGLES2: + if (!GLSurfaceEGL::InitializeOneOff()) { + LOG(ERROR) << "GLSurfaceEGL::InitializeOneOff failed."; + return false; + } + break; + default: + break; + } + + return true; +} + scoped_refptr<GLSurface> GLSurface::CreateViewGLSurface( gfx::AcceleratedWidget window) { TRACE_EVENT0("gpu", "GLSurface::CreateViewGLSurface");
diff --git a/ui/views/widget/native_widget_aura_unittest.cc b/ui/views/widget/native_widget_aura_unittest.cc index 24df658..87049cd 100644 --- a/ui/views/widget/native_widget_aura_unittest.cc +++ b/ui/views/widget/native_widget_aura_unittest.cc
@@ -15,6 +15,7 @@ #include "ui/aura/layout_manager.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/window.h" +#include "ui/aura/window_observer.h" #include "ui/aura/window_tree_host.h" #include "ui/events/event.h" #include "ui/events/event_utils.h" @@ -88,7 +89,7 @@ TEST_F(NativeWidgetAuraTest, CenterWindowLargeParent) { // Make a parent window larger than the host represented by // WindowEventDispatcher. - std::unique_ptr<aura::Window> parent(new aura::Window(NULL)); + std::unique_ptr<aura::Window> parent(new aura::Window(nullptr)); parent->Init(ui::LAYER_NOT_DRAWN); parent->SetBounds(gfx::Rect(0, 0, 1024, 800)); std::unique_ptr<Widget> widget(new Widget()); @@ -105,7 +106,7 @@ TEST_F(NativeWidgetAuraTest, CenterWindowSmallParent) { // Make a parent window smaller than the host represented by // WindowEventDispatcher. - std::unique_ptr<aura::Window> parent(new aura::Window(NULL)); + std::unique_ptr<aura::Window> parent(new aura::Window(nullptr)); parent->Init(ui::LAYER_NOT_DRAWN); parent->SetBounds(gfx::Rect(0, 0, 480, 320)); std::unique_ptr<Widget> widget(new Widget()); @@ -123,7 +124,7 @@ TEST_F(NativeWidgetAuraTest, CenterWindowSmallParentNotAtOrigin) { // Make a parent window smaller than the host represented by // WindowEventDispatcher and offset it slightly from the origin. - std::unique_ptr<aura::Window> parent(new aura::Window(NULL)); + std::unique_ptr<aura::Window> parent(new aura::Window(nullptr)); parent->Init(ui::LAYER_NOT_DRAWN); parent->SetBounds(gfx::Rect(20, 40, 480, 320)); std::unique_ptr<Widget> widget(new Widget()); @@ -138,7 +139,7 @@ TEST_F(NativeWidgetAuraTest, CreateMinimized) { Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.parent = NULL; + params.parent = nullptr; params.context = root_window(); params.show_state = ui::SHOW_STATE_MINIMIZED; params.bounds.SetRect(0, 0, 1024, 800); @@ -150,6 +151,72 @@ widget->CloseNow(); } +// A WindowObserver that counts kShowStateKey property changes. +class TestWindowObserver : public aura::WindowObserver { + public: + explicit TestWindowObserver(gfx::NativeWindow window) : window_(window) { + window_->AddObserver(this); + } + ~TestWindowObserver() override { + window_->RemoveObserver(this); + } + + // aura::WindowObserver: + void OnWindowPropertyChanged(aura::Window* window, + const void* key, + intptr_t old) override { + if (key != aura::client::kShowStateKey) + return; + count_++; + state_ = window_->GetProperty(aura::client::kShowStateKey); + } + + int count() const { return count_; } + ui::WindowShowState state() const { return state_; } + void Reset() { count_ = 0; } + + private: + gfx::NativeWindow window_; + int count_ = 0; + ui::WindowShowState state_ = ui::WindowShowState::SHOW_STATE_DEFAULT; + + DISALLOW_COPY_AND_ASSIGN(TestWindowObserver); +}; + +// Tests that window transitions from normal to minimized and back do not +// involve extra show state transitions. +TEST_F(NativeWidgetAuraTest, ToggleState) { + Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); + params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; + params.parent = nullptr; + params.context = root_window(); + params.show_state = ui::SHOW_STATE_NORMAL; + params.bounds.SetRect(0, 0, 1024, 800); + Widget widget; + widget.Init(params); + std::unique_ptr<TestWindowObserver> observer( + new TestWindowObserver(widget.GetNativeWindow())); + widget.Show(); + EXPECT_FALSE(widget.IsMinimized()); + EXPECT_EQ(0, observer->count()); + EXPECT_EQ(ui::WindowShowState::SHOW_STATE_DEFAULT, observer->state()); + + widget.Minimize(); + EXPECT_TRUE(widget.IsMinimized()); + EXPECT_EQ(1, observer->count()); + EXPECT_EQ(ui::WindowShowState::SHOW_STATE_MINIMIZED, observer->state()); + observer->Reset(); + + widget.Show(); + widget.Restore(); + EXPECT_EQ(1, observer->count()); + EXPECT_EQ(ui::WindowShowState::SHOW_STATE_NORMAL, observer->state()); + + observer.reset(); + EXPECT_FALSE(widget.IsMinimized()); + widget.CloseNow(); +} + class TestLayoutManagerBase : public aura::LayoutManager { public: TestLayoutManagerBase() {} @@ -223,7 +290,7 @@ std::unique_ptr<TestWidget> widget(new TestWidget()); Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.parent = NULL; + params.parent = nullptr; params.context = root_window(); params.show_state = ui::SHOW_STATE_MAXIMIZED; params.bounds = gfx::Rect(10, 10, 100, 200); @@ -281,7 +348,7 @@ Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.delegate = new PropertyTestWidgetDelegate(widget.get()); - params.parent = NULL; + params.parent = nullptr; params.context = root_window(); widget->Init(params); EXPECT_TRUE(layout_manager->added()); @@ -439,7 +506,7 @@ gfx::Point(70, 70))); delete view_with_layer; - view_with_layer = NULL; + view_with_layer = nullptr; EXPECT_EQ(child->GetNativeWindow(), parent->GetNativeWindow()->GetEventHandlerForPoint( @@ -471,7 +538,7 @@ } TEST_F(NativeWidgetAuraTest, NoCrashOnThemeAfterClose) { - std::unique_ptr<aura::Window> parent(new aura::Window(NULL)); + std::unique_ptr<aura::Window> parent(new aura::Window(nullptr)); parent->Init(ui::LAYER_NOT_DRAWN); parent->SetBounds(gfx::Rect(0, 0, 480, 320)); std::unique_ptr<Widget> widget(new Widget());
diff --git a/ui/views/widget/widget.cc b/ui/views/widget/widget.cc index c715a3b3..d2b27c9 100644 --- a/ui/views/widget/widget.cc +++ b/ui/views/widget/widget.cc
@@ -353,10 +353,12 @@ UpdateWindowTitle(); non_client_view_->ResetWindowControls(); SetInitialBounds(params.bounds); - if (params.show_state == ui::SHOW_STATE_MAXIMIZED) + if (params.show_state == ui::SHOW_STATE_MAXIMIZED) { Maximize(); - else if (params.show_state == ui::SHOW_STATE_MINIMIZED) + } else if (params.show_state == ui::SHOW_STATE_MINIMIZED) { Minimize(); + saved_show_state_ = ui::SHOW_STATE_MINIMIZED; + } } else if (params.delegate) { SetContentsView(params.delegate->GetContentsView()); SetInitialBoundsForFramelessWindow(params.bounds); @@ -606,10 +608,8 @@ !IsFullscreen()) { native_widget_->ShowMaximizedWithBounds(initial_restored_bounds_); } else { - ui::WindowShowState show_state = - IsFullscreen() ? ui::SHOW_STATE_FULLSCREEN : - IsMinimized() ? ui::SHOW_STATE_MINIMIZED : saved_show_state_; - native_widget_->ShowWithWindowState(show_state); + native_widget_->ShowWithWindowState( + IsFullscreen() ? ui::SHOW_STATE_FULLSCREEN : saved_show_state_); } // |saved_show_state_| only applies the first time the window is shown. // If we don't reset the value the window may be shown maximized every time